文章目录
-
-
-
- 添加依赖:
- 配置 Redis:
- 配置 Jackson2JsonRedisSerializer 进行对象的序列化
- 使用 RedisTemplate:
-
-
添加依赖:
在 pom.xml 文件中添加 Redis 和 Spring Data Redis 的依赖。 Spring boot 集成 redis 的使用, 无需版本号即可直接使用,还有相关配置信息可以直接通过 yml 文件去配置
<dependencies>
<!-- Spring Boot Starter Data Redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
</dependencies>
配置 Redis:
在 application.properties 或 application.yml 文件中配置 Redis 的连接信息。
java
redis:
port: 6380
host: 127.0.0.1
配置 Jackson2JsonRedisSerializer 进行对象的序列化
要在 Spring Boot 项目中配置 Redis 的序列化,你需要自定义 RedisTemplate 的序列化策略。Spring Data Redis 默认使用 JdkSerializationRedisSerializer 来序列化和反序列化对象,但这可能导致较大的内存占用。通常推荐使用 Jackson2JsonRedisSerializer 或 OxmSerializer(如果使用 XML)来进行更高效的序列化。
java
package org.gateway.config.redis;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
// 使用 Jackson2JsonRedisSerializer 替换默认的序列化方式
Jackson2JsonRedisSerializer<Object> jacksonSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jacksonSerializer.setObjectMapper(om);
template.setValueSerializer(jacksonSerializer);
template.setKeySerializer(new StringRedisSerializer());
template.afterPropertiesSet();
return template;
}
}
使用 RedisTemplate:
RedisTemplate 是 Spring Data Redis 提供的一个高级抽象层,用于简化 Redis 的操作。它封装了对 Redis 的基本操作,如设置和获取值、执行列表操作等,并且可以很容易地扩展到更复杂的功能。RedisTemplate 支持多种序列化策略,可以自定义序列化方式以满足特定的应用需求。
我们使用 RedisTemplate 封装一个 RedisUtil 便于使用
java
package org.gateway.utils.redis;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
@Component
@RequiredArgsConstructor
public class RedisUtil {
private final RedisTemplate<String, Object> redisTemplate;
private final ObjectMapper objectMapper;
// String Operations
public void setString(String key, String value) {
ValueOperations<String, Object> ops = redisTemplate.opsForValue();
ops.set(key, value);
}
public String getString(String key) {
ValueOperations<String, Object> ops = redisTemplate.opsForValue();
return (String) ops.get(key);
}
public void setStringWithExpiry(String key, String value, long timeout, TimeUnit unit) {
ValueOperations<String, Object> ops = redisTemplate.opsForValue();
ops.set(key, value, timeout, unit);
}
public Boolean hasKey(String key) {
return redisTemplate.hasKey(key);
}
public void deleteKey(String key) {
redisTemplate.delete(key);
}
// List Operations
public void leftPush(String key, Object value) {
ListOperations<String, Object> ops = redisTemplate.opsForList();
ops.leftPush(key, value);
}
public void rightPush(String key, Object value) {
ListOperations<String, Object> ops = redisTemplate.opsForList();
ops.rightPush(key, value);
}
public List<Object> range(String key, long start, long end) {
ListOperations<String, Object> ops = redisTemplate.opsForList();
return ops.range(key, start, end);
}
public Long listSize(String key) {
ListOperations<String, Object> ops = redisTemplate.opsForList();
return ops.size(key);
}
// Hash Operations
public void putInHash(String key, String field, Object value) {
HashOperations<String, String, Object> ops = redisTemplate.opsForHash();
ops.put(key, field, value);
}
public Object getValueFromHash(String key, String field) {
HashOperations<String, String, Object> ops = redisTemplate.opsForHash();
return ops.get(key, field);
}
public Map<String, Object> getHash(String key) {
HashOperations<String, String, Object> ops = redisTemplate.opsForHash();
return ops.entries(key);
}
public Long hashSize(String key) {
HashOperations<String, String, Object> ops = redisTemplate.opsForHash();
return ops.size(key);
}
// Set Operations
public void addSet(String key, Object member) {
SetOperations<String, Object> ops = redisTemplate.opsForSet();
ops.add(key, member);
}
public Set<Object> membersOfSet(String key) {
SetOperations<String, Object> ops = redisTemplate.opsForSet();
return ops.members(key);
}
public Long setSize(String key) {
SetOperations<String, Object> ops = redisTemplate.opsForSet();
return ops.size(key);
}
// Sorted Set Operations
public void addSortedSet(String key, Object member, double score) {
ZSetOperations<String, Object> ops = redisTemplate.opsForZSet();
ops.add(key, member, score);
}
public Set<Object> rangeByScore(String key, double min, double max) {
ZSetOperations<String, Object> ops = redisTemplate.opsForZSet();
return ops.rangeByScore(key, min, max);
}
public Long sortedSetSize(String key) {
ZSetOperations<String, Object> ops = redisTemplate.opsForZSet();
return ops.zCard(key);
}
// Key Operations
public void expire(String key, long timeout, TimeUnit unit) {
redisTemplate.expire(key, timeout, unit);
}
public Boolean exists(String key) {
return redisTemplate.hasKey(key);
}
public void deleteKeys(Collection<String> keys) {
redisTemplate.delete(keys);
}
public void setObject(String key, Object object) {
try {
String serializedObject = objectMapper.writeValueAsString(object);
redisTemplate.opsForValue().set(key, serializedObject);
} catch (IOException e) {
throw new RuntimeException("Failed to serialize object", e);
}
}
public <T> T getObject(String key, Class<T> clazz) {
String serializedObject = (String) redisTemplate.opsForValue().get(key);
if (serializedObject == null) {
return null;
}
try {
return objectMapper.readValue(serializedObject, clazz);
} catch (IOException e) {
throw new RuntimeException("Failed to deserialize object", e);
}
}
}