SpringCache实战遇坑
1. SpringCache实战遇坑
1.1. pom
- 主要是以下两个
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- 配合redis做缓存 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
1.2. Redis配置
package com.zhiyis.common.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import redis.clients.jedis.JedisPoolConfig;
import java.lang.reflect.Method;
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
private static Logger logger = LoggerFactory.getLogger(RedisConfig.class);
@Value("${spring.redis.host}")
private String redisHost;
@Value("${spring.redis.port}")
private int redisPort;
@Value("${spring.redis.timeout}")
private int redisTimeout;
@Value("${spring.redis.password}")
private String redisAuth;
@Value("${spring.redis.database}")
private int redisDb;
@Value("${spring.redis.pool.max-active}")
private int maxActive;
@Value("${spring.redis.pool.max-wait}")
private int maxWait;
@Value("${spring.redis.pool.max-idle}")
private int maxIdle;
@Value("${spring.redis.pool.min-idle}")
private int minIdle;
@Bean
@Override
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method, Object... params) {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(method.getName());
for (Object obj : params) {
sb.append(obj.toString());
}
return sb.toString();
}
};
}
@Bean
public CacheManager redisCacheManager() {
RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate());
//默认300秒过期
cacheManager.setDefaultExpiration(300);
// 启动时加载远程缓存
cacheManager.setLoadRemoteCachesOnStartup(true);
//是否使用前缀生成器
cacheManager.setUsePrefix(true);
return cacheManager;
}
@Bean
public RedisConnectionFactory redisConnectionFactory() {
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxTotal(maxActive);
poolConfig.setMaxIdle(maxIdle);
poolConfig.setMaxWaitMillis(maxWait);
poolConfig.setMinIdle(minIdle);
poolConfig.setTestOnBorrow(true);
poolConfig.setTestOnReturn(false);
poolConfig.setTestWhileIdle(true);
JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(poolConfig);
jedisConnectionFactory.setPassword(redisAuth);
jedisConnectionFactory.setHostName(redisHost);
jedisConnectionFactory.setDatabase(redisDb);
jedisConnectionFactory.setPort(redisPort);
jedisConnectionFactory.setTimeout(redisTimeout);
return jedisConnectionFactory;
}
@Bean
public RedisTemplate<String, Object> redisTemplate() {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
Jackson2JsonRedisSerializer<Object> serializer = jackson2JsonRedisSerializer();
redisTemplate.setConnectionFactory(redisConnectionFactory());
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(serializer);
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(serializer);
return redisTemplate;
}
@Bean
public Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer() {
final Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
final ObjectMapper objectMapper = Jackson2ObjectMapperBuilder
.json().build();
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
return jackson2JsonRedisSerializer;
}
}
在application.properties填上相应的参数
1.3. 使用
1.3.1. 坑1
- 目前主要使用的就是缓存和删除缓存
@Cacheable(sync = true, value = "on_hospital_list", key = "'3003101006_'+#requestReport.body['carer_id']", condition = "#requestReport.body['carer_id'] != '' ")
@Override
public ResponseReport getHospitalList(RequestReport requestReport) {
ResponseReport responseReport = new ResponseReport();
。。。
return responseReport.returnSuccessResult(hospitals, "获取医院列表成功", requestReport);
}
- 这里没有经验的人可能会纠结很久,因为我封装的入参对象,里面放的是JSONObject或者map作为的body值,这里我一开始是写成requestReport.body.carer_id这样的,但是这样会报如下错误
EL1008E: object of type 'com.alibaba.fastjson.JSONObject' - maybe not public
但你在网上找答案,都是文不对题,或者说其他错误导致相同的报错,反正我是找不到正确的解答
3. 解决方法就是如上代码,直接写成#requestReport.body['carer_id']
1.3.2. 坑2
- 删除缓存,我自定义了一个注解,原因是好像CacheEvict没提供删除多个key的方法
// @CacheEvict(value = "on_hospital_list", key="'3003101006_'+#requestReport.body['carer_id']")
@CacheRemove(value = "on_hospital_list"/*,key={"'3003101006_'+#requestReport.body['carer_id']","'3003101007_'+#requestReport.body['carer_id']"}*/)
@Override
public ResponseReport upDownServer(RequestReport requestReport) {
。。。业务逻辑
return responseReport.returnError("9999", "上下线失败", requestReport);
}
- 注解
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface CacheRemove {
/**
* 需要清除的大类 例如 autocms 所有缓存
*
* @return
*/
String value() default "";
/**
* 需要清除的具体的额类型
*
* @return
*/
String[] key() default {};
}
- 注解实现
import com.zhiyis.framework.annotation.CacheRemove;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
/**
* 清除缓存切面类
*
* @author laoliangliang
* @date 2019/1/14 16:04
*/
@Component
@Aspect
public class CacheRemoveAspect {
Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
RedisTemplate<String, String> redis;
ExpressionParser parser = new SpelExpressionParser();
LocalVariableTableParameterNameDiscoverer discoverer = new LocalVariableTableParameterNameDiscoverer();
/**
* 截获标有@CacheRemove的方法
*/
@Pointcut(value = "(execution(* *.*(..)) && @annotation(com.zhiyis.framework.annotation.CacheRemove))")
private void pointcut() {
}
/**
* 功能描述: 切面在截获方法返回值之后
*/
@AfterReturning(value = "pointcut()")
private void process(JoinPoint joinPoint) {
Object[] args = joinPoint.getArgs();
//获取切入方法的数据
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
//获取切入方法
Method method = signature.getMethod();
//获得注解
CacheRemove cacheRemove = method.getAnnotation(CacheRemove.class);
//注解解析
String[] params = discoverer.getParameterNames(method);
EvaluationContext context = new StandardEvaluationContext();
for (int len = 0; len < params.length; len++) {
context.setVariable(params[len], args[len]);
}
if (cacheRemove != null) {
StringBuilder sb = new StringBuilder();
String value = cacheRemove.value();
if (!value.equals("")) {
sb.append(value);
}
//需要移除的正则key
String[] keys = cacheRemove.key();
sb.append(":");
for (String key : keys) {
Expression expression = parser.parseExpression(key);
String value1 = expression.getValue(context, String.class);
//指定清除的key的缓存
cleanRedisCache(sb.toString() + value1);
}
}
}
private void cleanRedisCache(String key) {
if (key != null) {
//删除缓存
redis.delete(key);
logger.info("清除 " + key + " 缓存");
}
}
}
- 这里的注解写入参数,如果想要使用spel表达式,要写上解析注解的一段代码
参考
SpringCache实战遇坑的更多相关文章
- redis 集群 遇坑1
redis 集群 遇坑1 redis集群需要开2个端口 一个是客户端连接端口 一个是 集群总线端口 集群总线端口 是 客户端端口 + 10000 如 客户端端口是 6380 则集群总线端口 为 163 ...
- rabbitmq在ios中实战采坑
1. rabbitmq在ios中实战采坑 1.1. 问题 ios使用rabbitmq连接,没过多久就断开,并报错.且用android做相同的步骤并不会报错,错误如下 Received connecti ...
- 浅谈Android Studio3.0更新之路(遇坑必入)
>可以参考官网设置-> 1 2 >> Fantasy_Lin_网友评论原文地址是:简书24K纯帅豆写的我也更新一下出处[删除]Fa 转自脚本之家 浅谈Android Studi ...
- Android 上传开源项目到 jcenter 实战踩坑之路
本文微信公众号「AndroidTraveler」首发. 背景 其实 Android 上传开源项目到 jcenter 并不是一件新鲜事,网上也有很多文章. 包括我本人在将开源项目上传到 jcenter ...
- Cat搭建遇坑记
1. Cat搭建遇坑记 1.1. 报错 服务端启动 Unable to get component: class com.dianping.cat.analysis.TcpSocketReceiver ...
- deno+mongo实战踩坑记
自从 deno 1.0 发布以来,有关 deno 的文章很多,大多数都是在讨论怎么安装 deno .deno 有哪些特点 .deno 和 node 有哪些异同.deno是不是 node 的替代品等.咱 ...
- Windows安装Scrapy遇坑解决办
PS: Windows真心不适合开发.且行且珍惜.... 坑: error: Setup script exited with error: Microsoft Visual C++ 9.0 is r ...
- Java之戳中痛点 - (6)避免类型自动转换,例如两个整数相除得浮点数遇坑
先来看一个例子: package com.test; public class calculate { /** * 光速30万公里/秒 */ public static final int LIGHT ...
- Android组件化demo实现以及遇坑分享
首先贴出demo的github地址:GitHub - TenzLiu/TenzModuleDemo: android组件化demo 作者:TenzLiu原文链接:https://www.jianshu ...
随机推荐
- leetcode1:两数之和
给定一个整数数组和一个目标值,找出数组中和为目标值的两个数. 你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用. 实例: 给定 nums = [2, 7, 11, 15],target = ...
- node.js 线程调试配置
{ // 使用 IntelliSense 了解相关属性. // 悬停以查看现有属性的描述. // 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linki ...
- Python之路(第三十六篇)并发编程:进程、同步异步、阻塞非阻塞
一.理论基础 进程的概念起源于操作系统,是操作系统最核心的概念,也是操作系统提供的最古老也是最重要的抽象概念之一.操作系统的其他所有内容都是围绕进程的概念展开的. 即使可以利用的cpu只有一个(早期的 ...
- Python 的经典设计格言,格言来源于 Python 但不限于 Python
The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Si ...
- 最大熵与最大似然,以及KL距离。
DNN中最常使用的离散数值优化目标,莫过于交差熵.两个分布p,q的交差熵,与KL距离实际上是同一回事. $-\sum plog(q)=D_{KL}(p\shortparallel q)-\sum pl ...
- SQL语句操作数据
--切换数据库:手动切换和命令切换 use MySchool --向Student表中插入数据 --语法:INSERT [INTO] 表名 (列名) VALUES (值列表) --注意事项: --1. ...
- 字典 Dictionary
字典 Dictionary {Key-Value} 1.字典是无序的,没有下标(因为有key,取值直接用key值) Key尽量不要用中文编写,以防止编码不同导致取不出来 2.字典常用方法: 查找: ① ...
- 数据结构C语言版-队列
#include <stdlib.h> #include <stdio.h> #include <iostream> using namespace std; ty ...
- Unity3D协程yield的理解
Unity3D的协程概括地将就是:对于一段程序,你可以加上yield标明哪里需要暂停,然后在下一帧或者一段时间后,系统会继续执行这段代码.协程的作用:①延迟一段时间执行代码.②等某个操作完成之后再执行 ...
- BAT:文件中替换字符(保留空格和换行)
@echo off rem CMD:"color --help" :: setting color:back white,content blue color f9 ::old s ...