项目中有使用到缓存,每次需要将缓存代码和业务代码杂糅在一起,以及分散各处的key,严重影响代码的可读性。以下是使用AOP对其简单尝试。直接上代码:

1、定义缓存注解:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Cache {
long timeOut() default 0; TimeUnit timeUnit() default TimeUnit.HOURS;
}

2、定义参数唯一键注解,使用此注解标记此输入参数参与构成唯一键:

@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface CacheUniqueKey {
}

3、CacheAspect

@Component
@Slf4j
@Aspect
@Data
public class CacheAspect {
private final CacheCenter<String> cacheCenter;
   // 缓存开关配置
@Value("${service.cache}")
private boolean cacheEnable = false; @Around(value = "@annotation(com.yingying.survey.component.cache.Cache)&&@annotation(cache)")
public Object around(ProceedingJoinPoint joinPoint, Cache cache) throws Throwable {
if (!cacheEnable) {
return joinPoint.proceed();
} long timeOut = cache.timeOut();
TimeUnit timeUnit = cache.timeUnit();
if (timeOut == 0) {
return joinPoint.proceed();
} Class<?> clazz = joinPoint.getTarget().getClass();
String clazzSimpleName = clazz.getSimpleName();
String methodName = joinPoint.getSignature().getName(); Signature signature = joinPoint.getSignature();
Class declaringType = ((MethodSignature) signature).getReturnType(); String uniqueParam = methodParamsResolve(joinPoint);
String cacheKey = clazzSimpleName + ":" + methodName + ":" + uniqueParam;
if (cacheCenter.isExistCache(cacheKey)) {
String loadCache = cacheCenter.loadCache(cacheKey);
log.info("data from cache:{}", loadCache);
if (declaringType.isArray()) {
return JSONArray.parseArray(loadCache, declaringType);
} else {
return JSON.parse(loadCache, declaringType);
}
} Object proceedResult = joinPoint.proceed();
// 为了从缓存中取值时不出现空指针的情况,现不对返回值为空的结果缓存。
if (proceedResult != null) {
String cacheData = JSON.json(proceedResult);
CacheUnit cacheUnit = new CacheUnit().setTimeUnit(timeUnit).setCacheOutTime(timeOut).setCacheKey(cacheKey);
cacheCenter.insertCache(cacheUnit, cacheData);
} return proceedResult;
} private String methodParamsResolve(ProceedingJoinPoint joinPoint) {
Signature signature = joinPoint.getSignature();
Method method = ((MethodSignature) signature).getMethod();
Annotation[][] parameterAnnotations = method.getParameterAnnotations(); String uniqueParam = "";
int idx = 0;
for (Annotation[] annotations : parameterAnnotations) {
for (Annotation annotation : annotations) {
if (annotation instanceof CacheUniqueKey) {
Object[] args = joinPoint.getArgs();
uniqueParam = (String) args[idx];
return uniqueParam;
}
}
idx++;
}
return uniqueParam;
}
}

4、缓存配置单元:

@Data
@Accessors(chain = true)
public class CacheUnit {
@NotBlank
@NotNull
private String cacheKey; private long cacheOutTime = 0; @NotNull
private TimeUnit timeUnit;
}

5、缓存中心实现接口:

public interface CacheCenter<T> {
boolean isExistCache(@NotNull @NotBlank String cacheKey); T loadCache(@NotNull @NotBlank String cacheKey); boolean insertCache(@NotNull CacheUnit cacheUnit, @NotNull T cacheData);
}

6、基于Redis的缓存中心实现:

@Service("cacheCenter")
@Data
public class RedisCacheCenter implements CacheCenter<String> {
private final RedisService redisService; @Override
public boolean isExistCache(@NotNull @NotBlank String cacheKey) {
return redisService.exists(cacheKey);
} @Override
public String loadCache(@NotNull @NotBlank String cacheKey) {
return redisService.get(cacheKey);
} @Override
public boolean insertCache(@NotNull CacheUnit cacheUnit, @NotNull String cacheData) {
long cacheOutTime = TimeUnit.SECONDS.convert(cacheUnit.getCacheOutTime(), cacheUnit.getTimeUnit());
redisService.set(cacheUnit.getCacheKey().getBytes(), cacheData.getBytes(), cacheOutTime);
return true;
}
}

7、应用案例:

基于Redis的Service缓存实现的更多相关文章

  1. 基于redis的分布式缓存disgear开源到github上了

    disgear是笔者参考solrcloud架构基于redis实现的分布式的缓存,支持数据切分到多台机器上,支持HA,支持读写分离和主节点失效自动选举,目前把它开放到github上,开放给大家 gith ...

  2. Govern Service 基于 Redis 的服务治理平台

    Govern Service 基于 Redis 的服务治理平台(服务注册/发现 & 配置中心) Govern Service 是一个轻量级.低成本的服务注册.服务发现. 配置服务 SDK,通过 ...

  3. 基于Spring接口,集成Caffeine+Redis两级缓存

    原创:微信公众号 码农参上,欢迎分享,转载请保留出处. 在上一篇文章Redis+Caffeine两级缓存,让访问速度纵享丝滑中,我们介绍了3种整合Caffeine和Redis作为两级缓存使用的方法,虽 ...

  4. 基于redis分布式缓存实现(新浪微博案例)

    第一:Redis 是什么? Redis是基于内存.可持久化的日志型.Key-Value数据库 高性能存储系统,并提供多种语言的API. 第二:出现背景 数据结构(Data Structure)需求越来 ...

  5. .NET基于Redis缓存实现单点登录SSO的解决方案[转]

    一.基本概念 最近公司的多个业务系统要统一整合使用同一个登录,这就是我们耳熟能详的单点登录,现在就NET基于Redis缓存实现单点登录做一个简单的分享. 单点登录(Single Sign On),简称 ...

  6. .NET基于Redis缓存实现单点登录SSO的解决方案

    一.基本概念 最近公司的多个业务系统要统一整合使用同一个登录,这就是我们耳熟能详的单点登录,现在就NET基于Redis缓存实现单点登录做一个简单的分享. 单点登录(Single Sign On),简称 ...

  7. 基于redis分布式缓存实现

    Redis的复制功能是完全建立在之前我们讨论过的基 于内存快照的持久化策略基础上的,也就是说无论你的持久化策略选择的是什么,只要用到了Redis的复制功能,就一定会有内存快照发生,那么首先要注意你 的 ...

  8. 基于Redis缓存的Session共享(附源码)

    基于Redis缓存的Session共享(附源码) 在上一篇文章中我们研究了Redis的安装及一些基本的缓存操作,今天我们就利用Redis缓存实现一个Session共享,基于.NET平台的Seesion ...

  9. redis结合自定义注解实现基于方法的注解缓存,及托底缓存的实现

    本次分享如何使用redis结合自定义注解实现基于方法的注解缓存,及托底缓存的实现思路    现在的互联网公司大多数都是以Redis作为缓存,使用缓存的优点就不赘述了,写这篇文章的目的就是想帮助同学们如 ...

随机推荐

  1. (BUILDER)建造者与(FACTORY)工厂模式 的比较

    首先,说明下 参考博文 1.   建造者      http://www.cnblogs.com/zhili/p/BuilderPattern.html 2.   抽象工厂    http://www ...

  2. (排序)P1781 宇宙总统

    题解: 此题的关键不在排序,而在于大数字 我们可以用字符串进行存储,比较他们的长度,长度一样时比较他们的大小即可 #include<iostream>using namespace std ...

  3. tensorflow--conv函数

    #第一种yolo3中程序 def convolutional(input_data, filters_shape, trainable, name, downsample=False, activat ...

  4. 洛谷 P1020 导弹拦截

    题目传送门 解题思路: 其实就是求一遍最长不上升子序列和最长上升子序列 AC代码: #include<iostream> #include<cstdio> #include&l ...

  5. Exchange 2016 CU12安装报错

    1.         报错信息: Exchange 2016 升级 CU12补丁报错,主要是在进行第10步安装管理工具时报SeSecurityPrivilega错误,详细如下: 查看安装log信息如下 ...

  6. linux环境java程序cpu爆表问题查证

    1.top命令查找导致cup爆表的进程 2. top -H -p10832 (10832是Java进程的PID)命令找出了具体的线程 3.使用用命令 jstack 10832> jstack.t ...

  7. MobX 在 hook 中的使用

    关于 mobX 在 react 16.8.0 以上的用法 以下例子均取自官网文档 一般用法: import { observer, useLocalStore } from 'mobx-react'; ...

  8. UML-类图定义

    1.之前,学习过领域模型(概念模型),与类图的区别: 1).属于OOA 2).没有方法,只有属性和关联 类图属于OOD,属于静态对象建模 2.例子 3.类元包含哪些? 1).类(抽象类) 2).接口

  9. python语法基础-并发编程-线程-线程理论和线程的启动

    #######################       线程介绍         ############################## """ 线程介绍 为什 ...

  10. Mysql分析排序和锁阅读总结

    对于 MySQL 数据库而言,数据是存储在文件里的,而为了能够快速定位到某张表里的某条记录进行查询和修改,我们需要将这些数据以一定的数据结构进行存储,这个数据结构就是我们说的索引.能够支持快速查找的数 ...