实现读写代码
@Configuration
@Aspect
public class RedisAop {
@Autowired
private RedisTemplate redisTemplate;
@Around("@annotation(com.baizhi.config.AddCacheAnnotation)")
public Object addCache(ProceedingJoinPoint joinPoint) throws Throwable {
String key = joinPoint.getTarget().getClass().getName();
System.out.println("key: "+key);
StringBuffer buffer = new StringBuffer();
buffer.append(joinPoint.getSignature().getName());
Object[] args = joinPoint.getArgs();
for (Object arg : args) {
buffer.append(arg);
}
String hashKey = buffer.toString();
System.out.println("hashKey: "+hashKey);
HashOperations hashOperations = redisTemplate.opsForHash();
Object result = hashOperations.get(key, hashKey);
if (result == null){
System.out.println("查询数据");
result = joinPoint.proceed();
Map map = new HashMap();
map.put(hashKey,result);
hashOperations.putAll(key,map);
redisTemplate.expire(key,100, TimeUnit.SECONDS);
}else {
System.out.println("查询缓存");
}
return result;
}
@Before("@annotation(com.baizhi.config.DeleteCacheAnnotation)")
public void deleteCache(JoinPoint joinPoint){
String key = joinPoint.getTarget().getClass().getName();
redisTemplate.delete(key);
}
}