<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- lettuce pool 缓存连接池 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.6.2</version>
</dependency>
<!-- jackson json 优化缓存对象序列化 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.10</version>
</dependency>
@Configuration
@EnableCaching //启用缓存
public class RedisConfig extends CachingConfigurerSupport{
@Bean
public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory factory) {
//配置redisTemplate
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(factory);
redisTemplate.setKeySerializer(new Jackson2JsonRedisSerializer());
redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer());
redisTemplate.afterPropertiesSet();
return redisTemplate;//Str
}
}
#redis
# Redis服务器地址
spring.redis.host=10.11.12.237
# Redis服务器连接端口
spring.redis.port=6379
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接超时时间(毫秒)
spring.redis.timeout=10000
spring.redis.cluster.max-redirects=8
# Lettuce
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.lettuce.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.lettuce.pool.max-wait=1ms
# 连接池中的最大空闲连接
spring.redis.lettuce.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.lettuce.pool.min-idle=0
@Componet
public class RedisServiceImp extends RedisService {
@Autowired
RedisTemplate<String, Object> redisTemplate;
/**
* 读取缓存
*
* @param key
* @return
*/
public String get( String key) {
String value = null;
if(this.redisTemplate.hasKey(key)){
value = (String) redisTemplate.opsForValue().get(key)
}
return value;
}
/**
* 写入缓存
*
* @param key
* @param value
* @return
*/
public void set( String key, String value) {
redisTemplate.opsForValue().set(key, value);
}
public void set(String key, String value, long timeOut, TimeUnit timeUnit) {
redisTemplate.opsForValue().set(key, value, timeOut, timeUnit);
}
}