首页 > 其他 > 详细

注解+AOP实现redis遍历缓存

时间:2019-08-07 12:59:10      阅读:280      评论:0      收藏:0      [点我收藏+]

1.注解

package com.bgy.robot.framework.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.concurrent.TimeUnit;

@Target(ElementType.METHOD)  
@Retention(RetentionPolicy.RUNTIME)  
public @interface CacheAnnotation {
	
	/**
	 * 缓存key值
	 * @return
	 */
	String key();
	
	/**
	 * 缓存时长
	 * @return
	 */
	long timeToLive();
	
	/**
	 * 缓存时长单位,默认分
	 * @return
	 */
	TimeUnit timeUnit() default TimeUnit.MINUTES;
	
}

 

2.AOP

package com.bgy.robot.aspect;

import java.util.concurrent.TimeUnit;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.bgy.robot.framework.annotation.CacheAnnotation;

@Aspect
public class CacheAspect {
	
	private static Logger LOGGER = LoggerFactory.getLogger(CacheAspect.class);

	@Autowired
    private RedissonClient redissonClient;

	
    @Around("within(com.bgy.robot.payment.paymentservices.service.cache.*) && @annotation(cacheAnnotation)")
    public Object doAround(ProceedingJoinPoint pJoinPoint, CacheAnnotation cacheAnnotation) throws Throwable {
    	String key = cacheAnnotation.key();
    	TimeUnit timeUnit = cacheAnnotation.timeUnit();
    	long timeToLive = cacheAnnotation.timeToLive();
    	
    	//获取参数
    	Object[] args = pJoinPoint.getArgs();
    	if (args[0] == null) return null;
    	
    	key = key.concat(args[0].toString());
    	
    	RBucket<Object> redisSmsCode = redissonClient.getBucket(key);
    	Object obj = redisSmsCode.get();
    	
    	if (obj == null) {
    		Object result = pJoinPoint.proceed();
    		if (result == null) {
    			LOGGER.warn("[{}]无命中。", key);
    			return null;
    		}
			redisSmsCode.set(result);
			redisSmsCode.expire(timeToLive, timeUnit);
			LOGGER.debug("从数据库命中:{}", result);
			return result;
		} else {
			LOGGER.debug("从缓存命中:{}", obj);
			return obj;
		}
		
    }

}

 3.使用

/**
	 * @category 根据编号查询省份
	 * @param regionCode
	 * @return
	 */
	@CacheAnnotation(key=RedisKeyConstant.COMMON_PROVINCE, timeToLive=24, timeUnit=TimeUnit.HOURS)
	public Region selectProvinceByCode(String regionCode) {
		return bizService.selectRegionByCode(regionCode, Region.RegionLevel.PROVINCE);
	}

  

注解+AOP实现redis遍历缓存

原文:https://www.cnblogs.com/yun965861480/p/11314315.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!