Spring 中使用redis缓存方法记录
标签:hide hat generated 路径 chat cut get ring code
背景
在平时项目中,可能会有某个条件的查询,会多次进到db里面去查,这样就会重复的查询相同的数据,但是我们的数据又不是需要更改及显示的,这时候就可以用到
方法的缓存了。例如在我们调用微信小程序时,需要获取access_token,并且其有效时间为7200秒,过期后再次获取,我们就可以把获取access_token的方法作为
缓存。以下为我实现的过程记录。
1、重写 RedisSerializer 中的 serialize 和 deserialize


1 public class GenericFastJson2JsonRedisSerializerimplements RedisSerializer {
2 public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
3 public GenericFastJson2JsonRedisSerializer() {
4 super();
5 }
6 @Override
7 public byte[] serialize(T t) throws SerializationException {
8 if (t == null) {
9 return new byte[0];
10 }
11 FastJsonWraper wraperSet =new FastJsonWraper(t);
12 return JSON.toJSONString(wraperSet, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
13 }
14 @Override
15 public T deserialize(byte[] bytes) throws SerializationException {
16 if (bytes == null || bytes.length ) {
17 return null;
18 }
19 String deserializeStr = new String(bytes, DEFAULT_CHARSET);
20 FastJsonWraper wraperGet=JSON.parseObject(deserializeStr,FastJsonWraper.class);
21 return wraperGet.getValue();
22 }
23 }
重写RedisSerializer
2、实现缓存的获取和设置


1 public class RedisCache implements Cache {
2
3 private Logger logger = Logger.getLogger(RedisCache.class);
4 private RedisTemplate redisTemplate;
5
6 private String name;
7
8 private String resultType;
9
10 private long expireInSencods;
11
12 public static final String KEY_PREFIX = "wx:";
13
14
15 @Override
16 public Object getNativeCache() {
17 return this.redisTemplate;
18 }
19
20
21 @Override
22 public ValueWrapper get(Object key) {
23 if (logger.isDebugEnabled()) {
24 logger.debug("------缓存获取-------" + key.toString());
25 }
26 final String keyf = KEY_PREFIX + key.toString();
27 Object object = null;
28 object = redisTemplate.execute(new RedisCallback
View Code
3、在spring-redis.xml中配置 spring mvc自定义缓存,bean 中的class为我们缓存实现类的包路径,属性均为缓存实现类中的属性。


1 class="org.springframework.cache.support.SimpleCacheManager">
2 3 4 class="xxxx.xxx.xxx.RedisCache">
5 6 7 8 9 value="xxxx.xx.xxx.xx"/>
10 11 12 13
Spring mvc 自定义缓存
4、在代码中使用缓存,使用注解 @Cacheable,其中缓存名字cacheNames需要与我们spring redis中配置bean的对应起来


@Cacheable(cacheNames = CACHE_NAME,key = "#appid+‘:‘+#secret",unless = "#result == null")
@Override
public WeChatAppResponseDto getAccessToken(String appid, String secret) {
}
代码中的使用
然后执行代码可以发现,在第一次进入的时候,进入方法内部,然后返回结果,再次访问就没有进入方法内部了,可以打断点在缓存获取方法中查看,后面的都直接在缓存中获取了。其实通过引入的相关依赖也可以看出来,该注解功能是利用AOP来实现的。
Spring 中使用redis缓存方法记录
标签:hide hat generated 路径 chat cut get ring code
原文地址:https://www.cnblogs.com/rolayblog/p/11176270.html
评论