001/** 002 * Copyright (c) 2015-2022, Michael Yang 杨福海 (fuhai999@gmail.com). 003 * <p> 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * <p> 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * <p> 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package io.jboot.components.cache.interceptor; 017 018 019import com.jfinal.aop.Interceptor; 020import com.jfinal.aop.Invocation; 021import com.jfinal.core.Controller; 022import io.jboot.components.cache.AopCache; 023import io.jboot.components.cache.annotation.CachePut; 024import io.jboot.utils.AnnotationUtil; 025 026import java.lang.reflect.Method; 027 028/** 029 * 缓存设置拦截器 030 */ 031public class CachePutInterceptor implements Interceptor { 032 033 @Override 034 public void intercept(Invocation inv) { 035 036 Method method = inv.getMethod(); 037 CachePut cachePut = method.getAnnotation(CachePut.class); 038 if (cachePut == null || (inv.isActionInvocation() && !CacheableInterceptor.isActionCacheEnable())) { 039 inv.invoke(); 040 return; 041 } 042 043 if (inv.isActionInvocation()) { 044 forController(inv, method, cachePut); 045 } else { 046 forService(inv, method, cachePut); 047 } 048 } 049 050 051 private void forController(Invocation inv, Method method, CachePut cachePut) { 052 String unless = AnnotationUtil.get(cachePut.unless()); 053 if (Utils.isUnless(unless, method, inv.getArgs())) { 054 return; 055 } 056 057 Class<?> targetClass = inv.getTarget().getClass(); 058 String cacheName = AnnotationUtil.get(cachePut.name()); 059 Utils.ensureCacheNameNotBlank(method, cacheName); 060 String cacheKey = Utils.buildCacheKey(AnnotationUtil.get(cachePut.key()), targetClass, method, inv.getArgs()); 061 062 Controller controller = inv.getController(); 063 064 inv.invoke(); 065 066 CacheableInterceptor.cacheActionContent(cacheName, cacheKey, cachePut.liveSeconds(), inv , method); 067 } 068 069 070 private void forService(Invocation inv, Method method, CachePut cachePut) { 071 072 inv.invoke(); 073 074 Object data = inv.getReturnValue(); 075 076 String unless = AnnotationUtil.get(cachePut.unless()); 077 if (Utils.isUnless(unless, method, inv.getArgs())) { 078 return; 079 } 080 081 Class<?> targetClass = inv.getTarget().getClass(); 082 String cacheName = AnnotationUtil.get(cachePut.name()); 083 Utils.ensureCacheNameNotBlank(method, cacheName); 084 String cacheKey = Utils.buildCacheKey(AnnotationUtil.get(cachePut.key()), targetClass, method, inv.getArgs()); 085 086 AopCache.putDataToCache(cacheName, cacheKey, data, cachePut.liveSeconds()); 087 } 088 089 090}