SpringBoot 自定义注解清除缓存

 

基于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();

}

 

 

 

共同学习,共同进步,若有补充,欢迎指出,谢谢!

posted @ 2020-01-09 15:34  逆水行舟,平原走马  阅读(3406)  评论(0编辑  收藏  举报