SpringbootSessionRedis存储与序列化及缓存注解
版本:
springboot 2.2.0
redis 4.0
Maven
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
spring:
cache:# ⽤于⽀持缓存注册
type: redis
cache-names: c1,c2,c3 # 可配置多个Key前缀
redis:
time-to-live: 10m
session:# ⽤户session存储
store-type: redis
timeout: 5m # session过期时间
redis:
namespace: session:redis # 存储在redis中的键名
redis:
host: 192.168.1.100
port:6379
database:0
Redis Session序列化配置
/**
* SpringSession Redis序列化
* *注:bean的名称必须为springSessionDefaultRedisSerializer
*
* @see org.springframework.fig.annotation.web.http.RedisHttpSessionConfiguration
*/
@Component("springSessionDefaultRedisSerializer")
public class SessionSerializer extends GenericJackson2JsonRedisSerializer {
}
RedisTemplate
适⽤于复杂对象的保存
@Bean(name ="redisTemplate")
public RedisTemplate<Object, Object>redisTemplate(RedisConnectionFactory redisConnectionFactory){
RedisTemplate<Object, Object> template =new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
// 设置序列化⼯具 jackson2
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer =new Jackson2JsonRedisSerializer<>(Object.class); ObjectMapper om =new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.setSerializationInclusion(JsonInclude.Include.NON_NULL);
jackson2JsonRedisSerializer.setObjectMapper(om);
// 序列化设置
// 默认
// template.setDefaultSerializer(jackson2JsonRedisSerializer);
// key-value
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(jackson2JsonRedisSerializer);
// hash
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
适⽤于简单键值对的保存
@Bean(name ="stringRedisTemplate")
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory){
StringRedisTemplate template =new StringRedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
⽰例
@Resource
private RedisTemplate redisTemplate;
@Resource
private StringRedisTemplate stringRedisTemplate;
stringRedisTemplate.opsForValue().set("spring:uid","10001");
stringRedisTemplate.opsForValue().set("spring:name","xxx");
Product product1 =new Product();
product1.setId(1001l);
product1.setName("apple");
product1.setCurMoney(new BigDecimal("19.9"));
product1.setDisabled(false);
product1.setCreateTime(new Date());
Product product2 =new Product();
product2.setId(1002l);
product2.setName("pair");
product2.setCurMoney(new BigDecimal("99.9"));
product2.setDisabled(true);
product2.setCreateTime(new Date());
redisTemplate.opsForHash().put("spring:hash","product1", product1);
redisTemplate.opsForHash().put("spring:hash","product2", product2);
redisTemplate.opsForSet().add("spring:set", product1, product2);
缓存注解
public RedisCacheManager redisCacheManager(RedisTemplate redisTemplate){
// 初始化RedisCacheWriter
RedisCacheWriter redisCacheWriter = ConnectionFactory());
// ·设置默认的key前缀
// ·设置序列化⽅式
// ·设置过期时间,如果不设置,会使⽤dis.time-to-live
CacheKeyPrefix cacheKeyPrefix = name -> name +":";
RedisCacheConfiguration defaultRedisCacheConfiguration = RedisCacheConfiguration
.defaultCacheConfig()
putePrefixWith(cacheKeyPrefix)
.serializeKeysWith(RedisSerializationContext.SerializationPair.KeySerializer()))
.serializeValuesWith(RedisSerializationContext.SerializationPair.ValueSerializer()))
.entryTtl(Duration.ofHours(1));
RedisCacheConfiguration redisCacheConfiguration1 = RedisCacheConfiguration
.defaultCacheConfig()
putePrefixWith(cacheKeyPrefix)
.
serializeKeysWith(RedisSerializationContext.SerializationPair.KeySerializer()))
.serializeValuesWith(RedisSerializationContext.SerializationPair.ValueSerializer()))
.entryTtl(Duration.ofSeconds(100));
RedisCacheConfiguration redisCacheConfiguration2 = RedisCacheConfiguration
.defaultCacheConfig()
putePrefixWith(cacheKeyPrefix)
.serializeKeysWith(RedisSerializationContext.SerializationPair.KeySerializer()))
.serializeValuesWith(RedisSerializationContext.SerializationPair.ValueSerializer()))
.entryTtl(Duration.ofMinutes(5));
// 根据cacheName设置不同的序列化⽅式和过期时间
Map<String, RedisCacheConfiguration> redisCacheConfigurationMap =new HashMap<>();
redisCacheConfigurationMap.put("c1", redisCacheConfiguration1);
redisCacheConfigurationMap.put("c2", redisCacheConfiguration2);
// 初始化RedisCacheManager
RedisCacheManager cacheManager =new RedisCacheManager(redisCacheWriter, defaultRedisCacheConfiguration, redisCacheConfigurationMap); return cacheManager;
}
⽰例(⽅便演⽰,直接创建对象返回,可以从是否打印⽅法⾥的findById**来看有没有被缓存)
public class ProductService {
@Cacheable(cacheNames ="c1", key ="'product'+#id") public Product findById(Long id){
System.out.println("findById"+ id);
Product product =new Product();
product.setId(1001l);
product.setName("apple");
product.setCurMoney(new BigDecimal("19.9"));
product.setDisabled(false);
product.setCreateTime(new Date());
return product;
}
@Cacheable(cacheNames ="c2", key ="'product'+#id") public Product findById2(Long id){
System.out.println("findById"+ id);
Product product =new Product();
product.setId(1001l);
product.setName("apple");
product.setCurMoney(new BigDecimal("19.9"));
product.setDisabled(false);
product.setCreateTime(new Date());
return product;
}
@Cacheable(cacheNames ="c3", key ="'product'+#id") public Product findById3(Long id){
System.out.println("findById"+ id);
cacheableProduct product =new Product();
product.setId(1001l);
product.setName("apple");
product.setCurMoney(new BigDecimal("19.9"));
product.setDisabled(false);
product.setCreateTime(new Date());
return product;
}
@CacheEvict(value ="c3", key ="'product'+#id") public void deleteById(Long id){
System.out.println("deleteById"+ id);
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论