今日份学习: Spring中使用AOP并实现redis缓存?

笔记

在Spring中如何使用AOP?

  1. Spring是如何切换JDK动态代理CGLIB的?
  • spring.aop.proxy-target-class=true (在下方第二个链接中,原生doc中提到过)
  1. @Aspect生命切面
  • @Before
  • @After
  • @Around

Redis

  1. 广泛使用的内存缓存
  2. 常见的数据结构:
  • String
  • List
  • Set
  • Hash
  • ZSet
  1. Redis为什么快?
  • 完全基于内存
  • 优秀的数据结构设计
  • 单一线程,避免上下文切换开销
  • 事件驱动,非阻塞

浏览的一些学习资料

Spring Boot中使用AOP统一处理Web请求日志
Proxying mechanisms: 代理机制(spring doc)
Aspect Oriented Programming with Spring: 使用AOP进行面向切面编程(spring doc)

2020年2月8日 更新:

如何使用再spring boot中redis?

这里我使用了docker容器

  1. 首先引入pom.xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
  1. docker中运行redis,端口为6379
docker run -p 6379:6379 -d redis
  1. 创建了一个名为config的package,并创建了config/AppConfig.java
@Configuration
public class AppConfig {
    @Bean
    RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(factory);
        return redisTemplate;
    }
}

使用AOP实现redis的缓存(代码)

@Aspect
@Configuration
public class CacheAspect {
//    Map<String, Object> cache = new HashMap<>();
    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    @Around("@annotation(emmm.anno.Cache)")
    public Object cache(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();

        String methodName = signature.getName();

        Object cachedValue = redisTemplate.opsForValue().get(methodName);
//        Object cachedValue = cache.get(methodName);

        if (cachedValue != null) {
            System.out.println("from cache");
            return cachedValue;
        } else {
            System.out.println("from db");
            Object realValue = joinPoint.proceed();
            redisTemplate.opsForValue().set(methodName, realValue);
//            cache.put(methodName, realValue);
            return realValue;
        }
    }
}

补:参考到的网址:

docker->redis
docker start
spring doc -> spring data redis
Spring Boot中使用Redis数据库

posted @ 2020-02-07 23:24  带了1个小才艺  阅读(409)  评论(0编辑  收藏  举报