ehcache redis 双缓存(aop + 自定义注解)
查询数据:先查询ehcache缓存,如果没有数据,再查询redis缓存;如果查询不到,查询后端数据库
插入数据:后端数据库插入数据后,同时插入ehcache、redis缓存
更新数据:后端数据库更新数据后,同时更新ehcache、redis缓存
删除数据:后端数据库删除数据时,同时删除ehcache、redis缓存
****************************
示例
**********************
pojo 层
Person
@Data
public class Person implements Serializable {
private Integer id;
private String name;
private Integer age;
}
**********************
myannotation 层
CustomCacheCacheable:自定义查询注解
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomCacheable { //缓存查询注解
String value() default "";
/*
key为方法参数名、参数名的属性
Person fun(String name,Person person){} //key可用格式:"#name"、“#person.id”
*/
String key() default "";
}
CustomCachePut:自定义缓存添加注解
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomCachePut { //缓存添加注解
String value() default "";
/*
key为方法参数名、参数名的属性、返回值、返回值的属性
Person fun(String name,Person person){} //key可用格式:"#name"、“#person.id”、“#result”、"#result.id"
*/
String key() default "";
}
CustomCacheEvict:自定义缓存删除注解
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomCacheEvict { //缓存删除注解
String value() default "";
/*
key为方法参数名、参数名的属性
Person fun(String name,Person person){} //key可用格式:"#name"、“#person.id”、“#result”、“#result.id”
*/
String key() default "";
}
**********************
aop 层
CustomAspect
@Aspect
@Component
public class CustomAspect {
private final Logger logger= LoggerFactory.getLogger(this.getClass().getName());
@Resource(name = "ehcacheCacheManager")
private CacheManager cacheManager;
@Resource(name = "redisCacheManager")
private RedisCacheManager redisCacheManager;
@Pointcut("@annotation(com.example.demo.myannotation.CustomCacheable)")
public void fun(){
}
@Pointcut("@annotation(com.example.demo.myannotation.CustomCachePut)" +
"||@annotation(com.example.demo.myannotation.CustomCacheEvict)")
public void fun2(){
}
@Around("fun()")
public Person CustomCacheable(ProceedingJoinPoint joinPoint){