Introduction of depend on


        <! - introduce jedis -- -- >
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.8.2</version>
        </dependency>
Copy the code

 

Write a meta-annotation class, RedisCache, that automatically implements AOP caching for classes defined by the annotation


import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

// Where the annotation takes effect
@Target(ElementType.METHOD)
// The annotation takes effect at runtime
@Retention(RetentionPolicy.RUNTIME)
public @interface RedisCache {

}
Copy the code

 

Redis configuration class RedisConf


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.Jedis;

@Configuration
public class RedisConf {

    @Bean
    public Jedis getJedis(a){
        Jedis jedis = new Jedis("192.168.174.888".6379);
        returnjedis; }}Copy the code

 

The Spring AOP implementation monitors the cache of all methods annotated by @redisCache


@Configuration
@Aspect
public class RedisCommonCache {

    @Autowired
    private Jedis jedis;

    private static Logger logger = LoggerFactory.getLogger(RedisCommonCache.class);

    /** * select * from 'Redis' where' Redis' = 'Redis' where' MySQL '=' Redis'@return* /
    // Only the custom annotated method is required
    @Around("@annotation(com.baizhi.annotation.RedisCache)")
    public Object around(ProceedingJoinPoint proceedingJoinPoint)throws Throwable{

        long startTime = System.currentTimeMillis();

        // Get the method name of the target method
        MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();
        String methodName = signature.getName();
        logger.info("Method name:"+methodName);

        // Get the class where the target method resides
        String className = proceedingJoinPoint.getTarget().getClass().getName();
        logger.info("Class name:"+className);
        StringBuilder builder = new StringBuilder();
        builder.append(methodName).append(":");

        // Get the parameters of the target method
        Object[] args = proceedingJoinPoint.getArgs();
        / / stitching valueKey
        for (int i = 0; i < args.length; i++) {
            Object arg = args[i];
            builder.append(arg);
            if (i == args.length-1) {break;
            }
            builder.append(":");
        }
        String valueKey = builder.toString();

        // Check whether the current method exists in the cache
        // Deserialize the data directly from the cache with fastJSON
        Object result = null;
        if(jedis.hexists(className,valueKey)){
            logger.info("********** got data from Redis **********");
            logger.info("KEY value of Redis :"+className);
            logger.info("REDIS的VALUEKEY值:"+valueKey);
            String s = jedis.hget(className, valueKey);
            result =JSONObject.parse(s);

            logger.info("Time to process query on hit :"+(System.currentTimeMillis()-startTime));
        }else {
            // If there is no release, check the database and store it in redis
            logger.info("********** no data from Redis **********");
            logger.info("********** start querying data from MySQL **********");
            // There must be a return value, otherwise there will be a null pointer
            result = proceedingJoinPoint.proceed();
            logger.info("Time taken to process query when no hit :"+(System.currentTimeMillis()-startTime));
            jedis.hset(className,valueKey,JSONObject.toJSONStringWithDateFormat(result,"yyyy-MM-dd HH:mm:ss"));

            logger.info("KEY value of Redis :"+className);
            logger.info("REDIS的VALUEKEY值:"+valueKey);
            logger.info("********** data saved to Redis cache successfully!! * * * * * * * * * *");
        }
        jedis.close();
        return result;
    }

    // The operation will delete the corresponding cache from the Redis, and then query the database again and save it into the Redis cache
    @After("execution(* com.baizhi.service.*.*(..) ) &&! execution(* com.xxxx.service.*.select*(..) ) &&! execution(* com.xxxx.service.*.find*(..) )"
    public void after(JoinPoint joinPoint){ String name = joinPoint.getTarget().getClass().getName(); jedis.del(name); jedis.close(); }}Copy the code