有朋友问我一个关于接口优化的问题,他的优化点很清晰,因为接口中调用了内部不少的 service 去组成了一个完成的业务功能。每一个 service 中的逻辑都是独立的,这样就致使了不少查询是重复的,看下图你就明白了。git
上层查询传递下去
对于这种场景最好的就是在上层将须要的数据查询出来,而后传递到下层去消费。这样就不用重复查询了。github
若是开始写代码的时候是这样作的没问题,但不少时候,以前写的时候都是独立的,或者复用的老逻辑,里面就是有独立的查询。数据库
若是要作优化就只能将老的方法重载一个,将须要的信息直接传递过去。缓存
public void xxx(int goodsId) { Goods goods = goodsService.get(goodsId); .....}public void xxx(Goods goods) { .....}加缓存
若是你的业务场景容许数据有必定延迟,那么重复调用你能够直接经过加缓存来解决。这样的好处在于不会重复查询数据库,而是直接从缓存中取数据。微信
更大的好处在于对于优化类的影响最小,原有的代码逻辑都不用改变,只须要在查询的方法上加注解进行缓存便可。ide
public void xxx(int goodsId) { Goods goods = goodsService.get(goodsId); .....}public void xxx(Goods goods) { Goods goods = goodsService.get(goodsId); .....}class GoodsService { @Cached(expire = 10, timeUnit = TimeUnit.SECONDS) public Goods get(int goodsId) { return dao.findById(goodsId); }}
若是你的业务场景不容许有缓存的话,上面这个方法就不能用了。那么是否是还得改代码,将须要的信息一层层往下传递呢?优化
自定义线程内的缓存咱们总结下目前的问题:lua
总结后发现这个场景适合用 ThreadLocal 来传递数据,对已有代码改动量最小,并且也只对当前线程生效,不会影响其余线程。线程
public void xxx(int goodsId) { Goods goods = ThreadLocal.get(); if (goods == null) { goods = goodsService.get(goodsId); } .....}
上面代码就是使用了 ThreadLocal 来获取数据,若是有的话就直接使用,不用去从新查询,没有的话就去查询,不影响老逻辑。code
虽然能实现效果,可是不太好,不够优雅。也不够通用,若是一次请求内要缓存多种类型的数据怎么处理? ThreadLocal 就不能存储固定的类型。还有就是老的逻辑仍是得改,加了个判断。
下面介绍一种比较优雅的方式:
注意:ThreadLocal 不能跨线程,若是有跨线程需求,请使用阿里的 ttl 来装饰。
注解定义
@Target({ ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) public @interface ThreadLocalCache { /** * 缓存key,支持SPEL表达式 * @return */ String key() default ""; }存储定义
/** * 线程内缓存管理 * * @做者 尹吉欢 * @时间 2020-07-12 10:47 */ public class ThreadLocalCacheManager { private static ThreadLocal<Map> threadLocalCache = new ThreadLocal<>(); public static void setCache(Map value) { threadLocalCache.set(value); } public static Map getCache() { return threadLocalCache.get(); } public static void removeCache() { threadLocalCache.remove(); } public static void removeCache(String key) { Map cache = threadLocalCache.get(); if (cache != null) { cache.remove(key); } }}切面定义
/** * 线程内缓存 * * @做者 尹吉欢 * @时间 2020-07-12 10:48 */ @Aspect public class ThreadLocalCacheAspect { @Around(value = "@annotation(localCache)") public Object aroundAdvice(ProceedingJoinPoint joinpoint, ThreadLocalCache localCache) throws Throwable { Object[] args = joinpoint.getArgs(); Method method = ((MethodSignature) joinpoint.getSignature()).getMethod(); String className = joinpoint.getTarget().getClass().getName(); String methodName = method.getName(); String key = parseKey(localCache.key(), method, args, getDefaultKey(className, methodName, args)); Map cache = ThreadLocalCacheManager.getCache(); if (cache == null) { cache = new HashMap(); } Map finalCache = cache; Map<String, Object> data = new HashMap<>(); data.put("methodName", className + "." + methodName); Object cacheResult = CatTransactionManager.newTransaction(() -> { if (finalCache.containsKey(key)) { return finalCache.get(key); } return null; }, "ThreadLocalCache", "CacheGet", data); if (cacheResult != null) { return cacheResult; } return CatTransactionManager.newTransaction(() -> { Object result = null; try { result = joinpoint.proceed(); } catch (Throwable throwable) { throw new RuntimeException(throwable); } finalCache.put(key, result); ThreadLocalCacheManager.setCache(finalCache); return result; }, "ThreadLocalCache", "CachePut", data); } private String getDefaultKey(String className, String methodName, Object[] args) { String defaultKey = className + "." + methodName; if (args != null) { defaultKey = defaultKey + "." + JsonUtils.toJson(args); } return defaultKey; } private String parseKey(String key, Method method, Object[] args, String defaultKey){ if (!StringUtils.hasText(key)) { return defaultKey; } LocalVariableTableParameterNameDiscoverer nameDiscoverer = new LocalVariableTableParameterNameDiscoverer(); String[] paraNameArr = nameDiscoverer.getParameterNames(method); ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); for(int i = 0;i < paraNameArr.length; i++){ context.setVariable(paraNameArr[i], args[i]); } try { return parser.parseExpression(key).getValue(context, String.class); } catch (SpelEvaluationException e) { // 解析不出SPEL默认为类名+方法名+参数 return defaultKey; } } }过滤器定义
/** * 线程缓存过滤器 * * @做者 尹吉欢 * @我的微信 jihuan900 * @微信公众号 猿天地 * @GitHub https://github.com/yinjihuan * @做者介绍 http://cxytiandi.com/about * @时间 2020-07-12 19:46 */ @Slf4j public class ThreadLocalCacheFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { filterChain.doFilter(servletRequest, servletResponse); // 执行完后清除缓存 ThreadLocalCacheManager.removeCache(); } }自动配置类
@Configuration public class ThreadLocalCacheAutoConfiguration { @Bean public FilterRegistrationBean idempotentParamtFilter() { FilterRegistrationBean registration = new FilterRegistrationBean(); ThreadLocalCacheFilter filter = new ThreadLocalCacheFilter(); registration.setFilter(filter); registration.addUrlPatterns("/*"); registration.setName("thread-local-cache-filter"); registration.setOrder(1); return registration; } @Bean public ThreadLocalCacheAspect threadLocalCacheAspect() { return new ThreadLocalCacheAspect(); }}使用案例
@Service public class TestService { /** * ThreadLocalCache 会缓存,只对当前线程有效 * @return */ @ThreadLocalCache public String getName() { System.out.println("开始查询了"); return "yinjihaun"; } /** * 支持SPEL表达式 * @param id * @return */ @ThreadLocalCache(key = "#id") public String getName(String id) { System.out.println("开始查询了"); return "yinjihaun" + id; }}
功能代码: github.com/yinjihuan/k…
案例代码: github.com/yinjihuan/k…