1.引入jar
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
2.编写自定义注解类 RedisCache,被该注解定义的类都自动实现AOP
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RedisCache {
}
3.将Jedis交由Spring工厂管理
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.Jedis;
@Configuration
public class RedisConf {
@Bean
public Jedis getJedis(){
return new Jedis("192.168.226.144",6379);
}
}
public class JedisConfig extends CachingConfigurerSupport {
private final org.slf4j.Logger logger = LoggerFactory.getLogger(this.getClass());
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private int port;
@Value("${spring.redis.password}")
private String password;
@Bean
public Jedis getJedis() {
Jedis jedis = new Jedis(host, port);
jedis.auth(password);
logger.info("ip为:"+host,"端口为:"+port,"密码为:"+password);
return jedis;
}
}
4.Spring AOP实现监控所有被自定义注解@RedisCache注解的方法缓存
@Configuration
@Aspect
public class RedisCommonCache {
@Autowired
private Jedis jedis;
private final org.slf4j.Logger logger = LoggerFactory.getLogger(this.getClass());
@Around("execution(* com.zxl.service.*.*(..))")
public Object cache(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();
Method method = signature.getMethod();
logger.info("method为:"+method);
String methodName = method.getName();
logger.info("methodName为:"+methodName);
String className = proceedingJoinPoint.getTarget().getClass().getName();
logger.info("className为:"+className);
StringBuilder builder = new StringBuilder();
builder.append(methodName).append(":");
Object[] args = proceedingJoinPoint.getArgs();
for (int i = 0; i < args.length; i++) {
Object arg = args[i];
builder.append(arg);
if (i == args.length - 1) {
break;
}
builder.append(":");
}
String valueKey = builder.toString();
boolean b = method.isAnnotationPresent(RedisCache.class);
Object result = null;
if (b) {
if (jedis.hexists(className, valueKey)) {
String s = jedis.hget(className, valueKey);
result = JSONObject.parse(s);
} else {
result = proceedingJoinPoint.proceed();
jedis.hset(className, valueKey, JSONObject.toJSONString(result));
}
} else {
proceedingJoinPoint.proceed();
}
jedis.close();
return result;
}
@After("execution(* com.zxl.service.*.*(..)) && !execution(* com.zxl.service.*.select*(..))")
public void after(JoinPoint joinPoint){
String name = joinPoint.getTarget().getClass().getName();
jedis.del(name);
jedis.close();
}
}