基於SpringBoot ,自定義注解清除緩存
1、pom.xml 添加依賴
<!-- 開發自定義注解的依賴 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
2、定義清除緩存的注解
package com.*.*.*.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * mark that a method in a class need clear the cache * @author dgx */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD}) @Documented public @interface CacheClear { }
3、根據注解,進行切面處理
package com.*.*.*.aspect; import java.lang.reflect.Method; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import com.*.*.*.utils.EhcacheUtil; /** * By the annotation '@CacheClear', clear the cache of method which in a class * @author dgx */ @Aspect @Component public class CacheClearAspect { private static final Logger logger = LoggerFactory.getLogger(CacheClearAspect.class); @Pointcut("@annotation(com.*.*.*.annotation.CacheClear)") public void annotationPointcut() { } @Before("annotationPointcut()") public void beforePointcut(JoinPoint joinPoint) { // 獲取運行期間執行方法的類的名稱(包名加類名) String runtimeClassName = joinPoint.getTarget().getClass().getName(); // 獲取實例和方法 MethodSignature signature = (MethodSignature) joinPoint.getSignature(); Method method = signature.getMethod(); // 獲取定義方法的類(接口被代理,編寫代碼時和代碼運行時的類名是不一致的) Class<?> declaringClass = method.getDeclaringClass(); // 獲取定義方法的類的名稱(包名加類名) String className = declaringClass.getName() ; EhcacheUtil.clearRelatedCacheByMethodName(className, method.getName()+":"); logger.debug("代理:"+runtimeClassName+", "+className + "." + method.getName() + "() 執行前,完成了該方法緩存的清除"); } }
4、在Dao層,給指定方法添加注解
package com.*.*.*.dao; import java.util.List; import java.util.Map; import org.apache.ibatis.annotations.CacheNamespace; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import org.mybatis.caches.ehcache.EhcacheCache; import com.*.*.*.model.Project; import com.*.*.*.annotation.CacheClear; import com.*.*.*.Mapper; @CacheNamespace(implementation = EhcacheCache.class) public interface ProjectMapper extends Mapper<Project>{ @CacheClear @Select("select uuid()") public String createUuid(); }
共同學習,共同進步,若有補充,歡迎指出,謝謝!