基于Redis的Service缓存实现
项目中有使用到缓存,每次需要将缓存代码和业务代码杂糅在一起,以及分散各处的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缓存实现的更多相关文章
- 基于redis的分布式缓存disgear开源到github上了
disgear是笔者参考solrcloud架构基于redis实现的分布式的缓存,支持数据切分到多台机器上,支持HA,支持读写分离和主节点失效自动选举,目前把它开放到github上,开放给大家 gith ...
- Govern Service 基于 Redis 的服务治理平台
Govern Service 基于 Redis 的服务治理平台(服务注册/发现 & 配置中心) Govern Service 是一个轻量级.低成本的服务注册.服务发现. 配置服务 SDK,通过 ...
- 基于Spring接口,集成Caffeine+Redis两级缓存
原创:微信公众号 码农参上,欢迎分享,转载请保留出处. 在上一篇文章Redis+Caffeine两级缓存,让访问速度纵享丝滑中,我们介绍了3种整合Caffeine和Redis作为两级缓存使用的方法,虽 ...
- 基于redis分布式缓存实现(新浪微博案例)
第一:Redis 是什么? Redis是基于内存.可持久化的日志型.Key-Value数据库 高性能存储系统,并提供多种语言的API. 第二:出现背景 数据结构(Data Structure)需求越来 ...
- .NET基于Redis缓存实现单点登录SSO的解决方案[转]
一.基本概念 最近公司的多个业务系统要统一整合使用同一个登录,这就是我们耳熟能详的单点登录,现在就NET基于Redis缓存实现单点登录做一个简单的分享. 单点登录(Single Sign On),简称 ...
- .NET基于Redis缓存实现单点登录SSO的解决方案
一.基本概念 最近公司的多个业务系统要统一整合使用同一个登录,这就是我们耳熟能详的单点登录,现在就NET基于Redis缓存实现单点登录做一个简单的分享. 单点登录(Single Sign On),简称 ...
- 基于redis分布式缓存实现
Redis的复制功能是完全建立在之前我们讨论过的基 于内存快照的持久化策略基础上的,也就是说无论你的持久化策略选择的是什么,只要用到了Redis的复制功能,就一定会有内存快照发生,那么首先要注意你 的 ...
- 基于Redis缓存的Session共享(附源码)
基于Redis缓存的Session共享(附源码) 在上一篇文章中我们研究了Redis的安装及一些基本的缓存操作,今天我们就利用Redis缓存实现一个Session共享,基于.NET平台的Seesion ...
- redis结合自定义注解实现基于方法的注解缓存,及托底缓存的实现
本次分享如何使用redis结合自定义注解实现基于方法的注解缓存,及托底缓存的实现思路 现在的互联网公司大多数都是以Redis作为缓存,使用缓存的优点就不赘述了,写这篇文章的目的就是想帮助同学们如 ...
随机推荐
- 黑马oracle_day01:03.oracle的查询
01.oracle体系结构 02.oracle的基本操作 03.oracle的查询 04.oracle对象 05.oracle编程 黑马oracle_day01:03.oracle的查询 09scot ...
- 阿里云云服务器测试uwgis的基本流程
基本背景 uWSGI是一个Web服务器,它实现了WSGI协议.uwsgi.http等协议.Nginx中HttpUwsgiModule的作用是与uWSGI服务器进行交换. 要注意 WSGI / uwsg ...
- 操作实践:Java桌面程序实现日志级别热修改
声明:迁移自本人CSDN博客https://blog.csdn.net/u013365635 定位问题的时候往往需要动态修改日志级别并且不能影响业务的正常运行,也就是不能重启应用,此时就要使用到动态日 ...
- html+css web storage课上笔记 2019.3.18
存储 cookie cookie 使用文本来存储信息 使用时服务器发送cookie给客户端,下一次时,浏览器发送给服务器 web storage local storage 本地的硬件设备中,关闭后不 ...
- 吴裕雄--天生自然 JAVASCRIPT开发学习:RegExp 对象
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...
- SQL基础教程(第2版)第3章 聚合与排序:3-4 对查询结果进行排序
第3章 聚合与排序:3-4 对查询结果进行排序 ● 使用ORDER BY子句对查询结果进行排序.● 在ORDER BY子句中列名的后面使用关键字ASC可以(通常省略默认)进行升序排序,使用DESC关键 ...
- keras_yolo3程序框架理解
- TX2在Turtlebot测试kobuki
1.检查TX2开发板上的ROS,输入: $ roscore 如果ROS安装正确显示 started core service [/rosout] 2.输入检测kobuki 命令 ls /dev/kob ...
- 题解【[HAOI2006]受欢迎的牛】
切水题,写题解~ tarjan缩一波点,然后 只有一个出度为0的点:他的size就是答案 有多个初度为0的点:无解,0个 因为是强联通分量,所以肯定有出度为0的点,否则--就是你tarjan写挂了~ ...
- AES加密中遇到的坑
项目背景: 终端数据需要上传到后台,为了安全,使用了AES加密 问题1: 数据首先经过了protobuf进行格式,数据传输到后台无法解析 解决:二进制数据直接进行AES加密后大多无法正常解析,于是在加 ...