Spring Cache自定义缓存格式
来源:互联网 发布:淘宝旗袍第一模特 编辑:程序博客网 时间:2024/06/04 01:37
SpringCache是一个基于注解来更新缓存的组件,对于大多数的缓存操作都适用,本质是基于AOP实现,也不用再重复千轮子,直接使用便是,并且支持SpringEL表达式,对于使用教程网上还是很多的。
很多时候为了兼容性以及方便,会把对象转换成JSON格式存入缓存(Redis)中,这就需要对Cache进行拦截,在加入缓存及获取缓存时做一个JSON格式转换。
通过@EnableCaching 打开Spring Cache,查看@EnableCaching 定义可以看到此切面配置类默认是 ProxyCachingConfiguration,它有一个叫CacheInterceptor 的默认实现。所有缓存操作都需要经过它,只需自定义此类即可。如下所示例:
@Bean@Role(BeanDefinition.ROLE_INFRASTRUCTURE)public CacheInterceptor cacheInterceptor(CacheOperationSource cacheOperationSource) {CacheInterceptor interceptor = new CacheInterceptor() {private static final long serialVersionUID = 1L;@Overrideprotected void doPut(Cache cache, Object key, Object result) {String jsonResult = JSON.toJSONString(result);super.doPut(cache, key, jsonResult);}@Overridepublic Object invoke(MethodInvocation invocation) throws Throwable {Method method = invocation.getMethod();MyCacheOperationInvoker aopAllianceInvoker = new MyCacheOperationInvoker(invocation);try {Object result = execute(aopAllianceInvoker, invocation.getThis(), method,invocation.getArguments());if (result != null && result instanceof String && !aopAllianceInvoker.isDoInvoke()) {Type resultType = method.getGenericReturnType();return JSON.parseObject((String) result, resultType);}return result;} catch (CacheOperationInvoker.ThrowableWrapper th) {throw th.getOriginal();}}};interceptor.setCacheOperationSources(cacheOperationSource);return interceptor;}class MyCacheOperationInvoker implements CacheOperationInvoker {private MethodInvocation invocation;private boolean doInvoke = false;public MyCacheOperationInvoker(MethodInvocation invocation) {this.invocation = invocation;}@Overridepublic Object invoke() {try {doInvoke = true;return invocation.proceed();} catch (Throwable ex) {throw new ThrowableWrapper(ex);}}public boolean isDoInvoke() {return doInvoke;}}
上面方案对于所有缓存都有效,如果缓存使用的是Redis,还可以通过自定义 RedisTemplate ,替换RedisSerializer序列化方式。把自定的RedisTemplate注入到CacheManager中即可。
阅读全文
0 0
- Spring Cache自定义缓存格式
- Spring Cache+Redis实现自定义注解缓存
- mybatis 自定义缓存 cache
- Spring cache 缓存介绍
- Spring Cache缓存介绍
- Spring cache 缓存
- Spring Cache的缓存
- Spring cache 缓存介绍
- spring缓存注解@Cache
- Spring缓存 cache
- Spring cache 缓存介绍
- Spring cache 缓存
- spring cache缓存
- Spring 缓存 @cache 详细介绍
- Spring缓存注解@Cache使用
- Spring缓存注解@Cache使用
- Spring缓存注解@Cache使用
- Spring缓存注解@Cache使用
- ueditor uft-8 jsp版本配置
- crontab 打印错误小技巧
- 【牛腩】牛腩新闻发布系统总结
- easy-UI动态树点击文字实现展开关闭
- MSHFlexGrid与MSFlexGrid之间的区别
- Spring Cache自定义缓存格式
- 商城订单高并发下的数据安全
- ERROR 1290 (HY000): The MySQL server is running with the --skip-grant-tables option so it cannot exe
- LeetCode #34
- opencv中的直线拟合和直线添加【本大龄新程序员的第一篇技术博客】
- 大家心目中的这些「优质」论文,你读过几篇?| PaperDaily #01
- 来自闪闪宝石的光芒
- 解决 innerHTML的浏览器兼容问题
- MyEclips+Tomcat+MySQL Web应用开发入门(一)