通常,我们为了避免频繁的查询访问数据库或者第三方接口,会把查询结果缓存到redis或者memcached之类的nosql数据库中,避免数据库或者网络开销过大导致程序效率太低或者雪崩效应,但是代码中频繁的操作缓存,会让代码过于冗长,可以通过自定义注解的方式封装缓存的操作,使代码更简洁,话不多说,直接上代码:
1.先定义注解@EnableCacheService
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface EnableCacheService {
/**
* key前缀
*/
String keyPrefix();
/**
* key主体,spel表示,例:#id(取形参中id的值)
*/
String fieldKey();
/**
* 过期时间
*/
int expireTime() default 3600;
TimeUnit timeUnit() default TimeUnit.SECONDS;
CacheOperation cacheOperation();
/**
* 缓存操作类型
*/
enum CacheOperation {
QUERY, // 查询
UPDATE, // 修改
DELETE; // 删除
}
}
2.切面处理类
/**
* EnableRedisService 注解切面处理
* @author: Iffie
* @date: 2018年9月29日
*/
@Aspect
@Component
@Slf4j
@SuppressWarnings("all")
public class CacheServiceAspect {
@Pointcut("@annotation(com.iffie.core.EnableCacheService)")
public void dealCacheServiceCut(){
}
@Autowired
private RedisTemplate redisTemplate;
@Around(value = "dealCacheServiceCut()")
@SuppressWarnings