Spring Aop之Redis缓存

源码链接

点我哦O(∩_∩)O

引入依赖

<!-- redis 相关依赖 -->
 <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-redis</artifactId>
   <version>1.5.7.RELEASE</version>
</dependency>

目录结构

Spring Aop之Redis缓存_第1张图片

appcation.yml配置

spring:
#数据库配置
  datasource:
    username: root
    password:
    url: jdbc:mysql://localhost:3306/aopredis
    driver-class-name: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
  http:
    encoding:
      charset: UTF-8
      force: true
#redis配置
  redis:
    database: 0
    host: 192.168.72.128
    port: 6379

AddCache

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AddCache {

}

RedisCache

@Configuration
@Aspect
public class RedisCache {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Around("@annotation(cn.czboy.annotation.AddCache)")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        StringBuilder sb = new StringBuilder();
        //获取类名
        String className = proceedingJoinPoint.getTarget().getClass().getName();
        System.out.println("类名:"+className);

        //获取方法名
        String methodName = proceedingJoinPoint.getSignature().getName();
        System.out.println("方法名:"+methodName);
        sb.append(methodName);

        //获取参数
        Object[] args = proceedingJoinPoint.getArgs();
        for(Object arg:args){
            System.out.println("参数:"+arg);
            sb.append(arg);
        }
        String str = sb.toString();
        System.out.println("SpringBuilder:"+sb);
        Boolean aBoolean = redisTemplate.hasKey(className);
        HashOperations hashOperations = redisTemplate.opsForHash();
        Object  result = null;
        if(aBoolean){
            result = hashOperations.get(className,str);
        }else{
            result = proceedingJoinPoint.proceed();
            HashMap<Object, Object> map = new HashMap<>();
            map.put(str,result);
            hashOperations.putAll(className,map);
        }
        return result;
    }
}

GoodsServiceImpl

@Service
public class GoodsServiceImpl implements GoodsService{

    @Autowired
    private GoodsDao goodsDao;

    @Override
    @AddCache
    public Goods queryGoods(String id) {
        Goods goods = goodsDao.queryGoods(id);
        if (goods == null) {
            System.out.println("Goods为空!!!");
        }
        return goods;
    }
}

你可能感兴趣的:(java,缓存)