使用SpringAOP+Caffeine实现本地缓存

2024-03-26 18:28

本文主要是介绍使用SpringAOP+Caffeine实现本地缓存,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

文章目录

  • 一、背景
  • 二、实现
    • 1、定义注解
    • 2、切面
    • 3、缓存工具类
  • 三、测试

一、背景

公司想对一些不经常变动的数据做一些本地缓存,我们使用AOP+Caffeine来实现

二、实现

1、定义注解

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 LocalCacheable {// 过期时间 默认10分钟long expired() default 600;// key创建器String keyGenerator() default "org.springframework.cache.interceptor.KeyGenerator";
}

2、切面


import com.google.gson.internal.LinkedTreeMap;
import org.apache.commons.lang3.ArrayUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.aop.framework.AopProxyUtils;
import org.springframework.aop.support.AopUtils;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.stereotype.Component;import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;/*** 本地缓存*/
@Aspect
@Component
public class LocalCacheAspect {private static final String separator = ":";@Around("@annotation(com.framework.localcache.LocalCacheable)")public Object around(ProceedingJoinPoint point) throws Throwable {if (AopUtils.isAopProxy(point.getTarget())) {return point.proceed();}Method method = getMethodSignature(point).getMethod();if (method == null) {return point.proceed();}LocalCacheable annotation = method.getAnnotation(LocalCacheable.class);if (annotation == null) {return point.proceed();}// 生成keyString key = generateKey(point);
//         System.out.println("生成的key:" + key);long expired = annotation.expired();Throwable[] throwable = new Throwable[1];Object proceed = LocalCache.cacheData(key, () -> {try {return point.proceed();} catch (Throwable e) {throwable[0] = e;}return null;}, expired);if (throwable[0] != null) {throw throwable[0];}return proceed;}/*** 获取方法*/private MethodSignature getMethodSignature(ProceedingJoinPoint point) {Signature signature = point.getSignature();if (signature instanceof MethodSignature) {return ((MethodSignature) signature);}return null;}/*** 获取key*/private String generateKey(ProceedingJoinPoint point) {// 目标类、方法、参数等Class<?> targetClass = AopProxyUtils.ultimateTargetClass(point.getTarget());Method method = getMethodSignature(point).getMethod();String[] parameterNames = getMethodSignature(point).getParameterNames();Object[] args = point.getArgs();// 解析参数,生成keyLinkedTreeMap<String, Object> paramResolveResult = new LinkedTreeMap<>();if (ArrayUtils.isNotEmpty(args)) {for (int i = 0; i < args.length; i++) {resolveParam(args[i], paramResolveResult, parameterNames[i]);}}StringBuilder key = new StringBuilder(targetClass.getName() + separator + method.getName() + separator);paramResolveResult.forEach((k, v) -> {if (v != null) {key.append(k + "," + v + separator);}});// 根据方法名和参数生成唯一标识return key.toString();}private void resolveParam(Object param, Map<String, Object> paramResolveResult, String prefix) {if (param == null) {return;}Class<?> type = param.getClass();if (type == List.class) {List<Object> param0 = (List) param;for (int i = 0; i < param0.size(); i++) {resolveParam(param0.get(i), paramResolveResult, prefix + "[" + i + "]");}} else if (type == Map.class) {Map<Object, Object> param0 = (Map) param;param0.forEach((k, v) -> {resolveParam(v, paramResolveResult, prefix + "." + k);});} else if (type.isArray()) {Object[] param0 = (Object[]) param;for (int i = 0; i < param0.length; i++) {resolveParam(param0[i], paramResolveResult, prefix + "[" + i + "]");}} else if (type == Byte.class|| type == Short.class|| type == Integer.class|| type == Long.class|| type == Float.class|| type == Double.class|| type == Boolean.class|| type == Character.class|| type == String.class) {paramResolveResult.put(prefix, param);} else if (type.getName().startsWith("java.")) {} else {// 复杂类型Map<String, Object> fieldMap = new HashMap<>();// CGLIB代理if (Enhancer.isEnhanced(type)) {getAllFieldsAndValue(param, type.getSuperclass(), fieldMap);} else {getAllFieldsAndValue(param, type, fieldMap);}fieldMap.forEach((k, v) -> {if (v == null) {return;}resolveParam(v, paramResolveResult, prefix + "." + k);});}}/*** 获取所有字段和值*/private void getAllFieldsAndValue(Object o, Class type, Map<String, Object> fieldMap) {for (Method method : type.getMethods()) {if (method.getName().startsWith("get") && method.getParameterCount() == 0) {try {Object value = method.invoke(o);if (value != null) {fieldMap.put(method.getName().substring(3), value);}} catch (Exception e) {}}}}}

3、缓存工具类

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.CacheLoader;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;/*** 本地缓存*/
public class LocalCache {private static final Map<Long, Cache<Object, Object>> cacheMap = new ConcurrentHashMap<>();/*** 创建本地缓存* @param seconds 过期时间:秒*/private static Cache<Object, Object> createCache(long seconds) {return Caffeine.newBuilder().expireAfterWrite(seconds, TimeUnit.SECONDS).build();}/*** 创建本地缓存* @param seconds 过期时间:秒* @param loader 缓存方法*/private Cache<Object, Object> createLoadingCache(long seconds, CacheLoader<Object, Object> loader) {return Caffeine.newBuilder().expireAfterWrite(seconds, TimeUnit.SECONDS).build(loader);}/*** 获取一个缓存组* @param seconds 缓存过期时间*/private static Cache<Object, Object> getAndLoad(long seconds) {if (cacheMap.containsKey(seconds)) {return cacheMap.get(seconds);}Cache<Object, Object> cache = createCache(seconds);cacheMap.put(seconds, cache);return cache;}/*** 缓存数据,过期时间默认10分钟* @param key key* @param supplier 数据来源的方法*/public static Object cacheData(Object key, Supplier<Object> supplier) {return cacheData(key, supplier, 600);}/*** 缓存数据* @param key key* @param supplier 数据来源的方法* @param seconds 过期时间:秒*/public static Object cacheData(Object key, Supplier<Object> supplier, long seconds) {Assert.state(seconds > 0, "过期时间必须大于0秒");Cache<Object, Object> cache = getAndLoad(seconds);return cache.get(key, k -> supplier.get());}
}

三、测试

    @LocalCacheable@GetMapping("test1")public String test1() {System.out.println("执行了");return "success";}@LocalCacheable@GetMapping("test2")public String test2(String a) {System.out.println("执行了" + a);return "success";}@LocalCacheable@GetMapping("test3")public String test3(String a, int b, String c) {System.out.println("执行了" + a + b + c);return "success";}@LocalCacheable@GetMapping("test4")public String test4(UserInfo user) {System.out.println("执行了" + user);return "success";}@LocalCacheable@GetMapping("test5")public String test5(UserInfo[] users) {System.out.println("执行了" + users);return "success";}@LocalCacheable@GetMapping("test6")public String test6(List<UserInfo> users) {System.out.println("执行了" + users);return "success";}@LocalCacheable@GetMapping("test7")public String test7(UserInfo user) {System.out.println("执行了" + user.getMap());return "success";}

这篇关于使用SpringAOP+Caffeine实现本地缓存的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/849438

相关文章

golang版本升级如何实现

《golang版本升级如何实现》:本文主要介绍golang版本升级如何实现问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录golanwww.chinasem.cng版本升级linux上golang版本升级删除golang旧版本安装golang最新版本总结gola

SpringBoot中SM2公钥加密、私钥解密的实现示例详解

《SpringBoot中SM2公钥加密、私钥解密的实现示例详解》本文介绍了如何在SpringBoot项目中实现SM2公钥加密和私钥解密的功能,通过使用Hutool库和BouncyCastle依赖,简化... 目录一、前言1、加密信息(示例)2、加密结果(示例)二、实现代码1、yml文件配置2、创建SM2工具

Mysql实现范围分区表(新增、删除、重组、查看)

《Mysql实现范围分区表(新增、删除、重组、查看)》MySQL分区表的四种类型(范围、哈希、列表、键值),主要介绍了范围分区的创建、查询、添加、删除及重组织操作,具有一定的参考价值,感兴趣的可以了解... 目录一、mysql分区表分类二、范围分区(Range Partitioning1、新建分区表:2、分

MySQL 定时新增分区的实现示例

《MySQL定时新增分区的实现示例》本文主要介绍了通过存储过程和定时任务实现MySQL分区的自动创建,解决大数据量下手动维护的繁琐问题,具有一定的参考价值,感兴趣的可以了解一下... mysql创建好分区之后,有时候会需要自动创建分区。比如,一些表数据量非常大,有些数据是热点数据,按照日期分区MululbU

Spring IoC 容器的使用详解(最新整理)

《SpringIoC容器的使用详解(最新整理)》文章介绍了Spring框架中的应用分层思想与IoC容器原理,通过分层解耦业务逻辑、数据访问等模块,IoC容器利用@Component注解管理Bean... 目录1. 应用分层2. IoC 的介绍3. IoC 容器的使用3.1. bean 的存储3.2. 方法注

MySQL中查找重复值的实现

《MySQL中查找重复值的实现》查找重复值是一项常见需求,比如在数据清理、数据分析、数据质量检查等场景下,我们常常需要找出表中某列或多列的重复值,具有一定的参考价值,感兴趣的可以了解一下... 目录技术背景实现步骤方法一:使用GROUP BY和HAVING子句方法二:仅返回重复值方法三:返回完整记录方法四:

Python内置函数之classmethod函数使用详解

《Python内置函数之classmethod函数使用详解》:本文主要介绍Python内置函数之classmethod函数使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录1. 类方法定义与基本语法2. 类方法 vs 实例方法 vs 静态方法3. 核心特性与用法(1编程客

IDEA中新建/切换Git分支的实现步骤

《IDEA中新建/切换Git分支的实现步骤》本文主要介绍了IDEA中新建/切换Git分支的实现步骤,通过菜单创建新分支并选择是否切换,创建后在Git详情或右键Checkout中切换分支,感兴趣的可以了... 前提:项目已被Git托管1、点击上方栏Git->NewBrancjsh...2、输入新的分支的

Linux中压缩、网络传输与系统监控工具的使用完整指南

《Linux中压缩、网络传输与系统监控工具的使用完整指南》在Linux系统管理中,压缩与传输工具是数据备份和远程协作的桥梁,而系统监控工具则是保障服务器稳定运行的眼睛,下面小编就来和大家详细介绍一下它... 目录引言一、压缩与解压:数据存储与传输的优化核心1. zip/unzip:通用压缩格式的便捷操作2.

Python实现对阿里云OSS对象存储的操作详解

《Python实现对阿里云OSS对象存储的操作详解》这篇文章主要为大家详细介绍了Python实现对阿里云OSS对象存储的操作相关知识,包括连接,上传,下载,列举等功能,感兴趣的小伙伴可以了解下... 目录一、直接使用代码二、详细使用1. 环境准备2. 初始化配置3. bucket配置创建4. 文件上传到os