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);
}
原文:https://www.cnblogs.com/yun965861480/p/11314315.html