添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
添加redis服务器信息
application.yml
spring:
redis:
host: eurekaserver01.com
password: EanD5NhsdCWLs6zs
port: 6379
# 连接超时时间(记得添加单位,Duration)
timeout: 10000ms
# Redis默认情况下有16个分片,这里配置具体使用的分片
# database: 0
lettuce:
pool:
# 连接池最大连接数(使用负值表示没有限制) 默认 8
max-active: 8
# 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1
max-wait: -1ms
# 连接池中的最大空闲连接 默认 8
max-idle: 8
# 连接池中的最小空闲连接 默认 0
min-idle: 0
cache:
# 一般来说是不用配置的,Spring Cache 会根据依赖的包自行装配
type: redis
注册redis config bean
@Configuration
@AutoConfigureAfter(RedisAutoConfiguration.class)
@JsonIgnoreProperties(ignoreUnknown = true)
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new RedisObjectSerializer());
return template;
}
}
Object序列化:
public class RedisObjectSerializer implements RedisSerializer<Object> {
private final Converter<Object, byte[]> serializer = new SerializingConverter();
private final Converter<byte[], Object> deSerializer = new DeserializingConverter();
private static final byte[] EMPTY_ARRAY = new byte[0];
@Override
public byte[] serialize(Object o) throws SerializationException {
if (o == null) {
return EMPTY_ARRAY;
}
return serializer.convert(o);
}
@Override
public Object deserialize(byte[] bytes) throws SerializationException {
if (isEmpty(bytes)) {
return null;
}
return deSerializer.convert(bytes);
}
private boolean isEmpty(byte[] data) {
return data == null || data.length == 0;
}
}
使用方式
public User getUserById(Long id) {
Object obj = redisObjTemplate.opsForValue().get(String.valueOf(id));
User user;
if (obj != null) {
log.info("data from redis");
user = (User) obj;
} else {
user = userMapper.selectById(id);
if (user != null) {
redisObjTemplate.opsForValue().set(String.valueOf(id), user);
}
}
return user;
}