0. 写在最前
本文主要作为记录学习Redis的过程,利用自定义注解实现Redis缓存功能。
最近在学习Redis和SpringBoot,本来以为用框架实现缓存是一件比较复杂的事情,没想到SpringBoot已经封装好了方法,只需要配合@Cachable
等注解就可以使用了。惊叹于SpringBoot的优美之余,心中闪现出了自己动手实现一个类似功能的想法,于是便有了这篇文章。
1. 思路
如下是流程图,实现起来应该比较容易,当要获取结果集的时候,先判断缓存是否有,如果有就直接返回缓存的结果集,否者,查询数据库(顺便把结果集放进缓存),最后返回结果集。
根据上面的流程图,我们可以设计出如下的aop模块,定义一些切面,最重要的是判断缓存切面,打印日志等其他切面可选,不是本文重点。
2. 项目搭建
用idea搭建springboot项目:
- pom如下:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>club.jming</groupId>
<artifactId>cache</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>cache</name>
<description>Demo project for Spring Boot with Cache</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis-reactive</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
<version>2.3.5.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-pool2 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.10.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.76</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
- 定义两个实体类(数据库参考这两个,就不贴sql了):
Order:
@Data
public class Order implements Serializable {
private long id;
private long pid;
private long uid;
}
Product:
@Data
public class Product {
private long id;
private String name;
private int stock;
}
- 实现简单的service层
public interface IOrderService {
/**
* 返回所有的订单信息
* @return
*/
List<Order> selectOrders();
}
@Service
@Slf4j
public class OrderServiceImpl implements IOrderService {
@Autowired
private OrderMapper orderMapper;
@Override
public List<Order> selectOrders() {
return orderMapper.selectOrders();
}
}
- 然后是controller层
@RestController
@RequestMapping("/order")
public class OrderController {
@Autowired
private IOrderService orderService;
@RequestMapping("/orders/{key}")
/**
这是自定义的注解,下面会解析
*/
@RedisCache(cacheName = "orders",msg = "orders msg ...")
public List<Order> selectOrders(@PathVariable("key") String key, Order order){
return orderService.selectOrders();
}
}
- application.yaml配置:
#配置端口号
server:
port: 8080
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost/seckill?useSSL=true&useUnicode=true&characterEncoding=UTF8&serverTimezone=GMT
username: root
password:
redis:
lettuce:
pool:
max-active: 8
max-wait: 5
host: 192.168.160.133
port: 6379
mybatis:
mapper-locations: classpath:mybatis/mappers/*Mapper.xml
至此,项目的基本结构搭建完成
3. 注解实现
首先我们自定义一个注解:
注解可以自己添加需要获取的信息,注意元注解的使用
/**
* 自定义缓存注解
* @author 78289
*/
@Target(ElementType.METHOD)
@Inherited
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface RedisCache {
/**
* 缓存组名称
* @return
*/
String cacheName();
/**
* 缓存key
* @return
*/
String key() default "";
/**
* 缓存信息
* @return
*/
String msg();
/**
* 过期时间
* 默认 -2 ,表示随机时间(0~2000ms)
* -1 表示不会过期
* @return
*/
int expireTime() default -2;
}
然后开始使用aop了,先定义一个aspect类,然后定义一个切点(注册到spring容器进行管理才能生效),再通过@Around织入。
/**
* 缓存切面类
* 缓存标注了<code>@RedisCache</code>的方法
* 把方法结果放进名为<code>cacheName</code>的set中
* 缓存key可以自定义
*
* @author 78289
*/
@Aspect
@Component
@Slf4j
public class CacheAspect {
@Autowired
private RedisTemplate redisTemplate;
/**
* 定义切入点
*/
@Pointcut("@annotation(club.jming.cache.aspect.annotation.RedisCache)")
public void pointCut() {
}
/**
* 环绕通知,可以传入参数<code>ProceedingJoinPoint</code>
* 该参数封装了我们需要用到的全部信息
* 包括:
* 1. 代理对象本身
* 2. 目标对象
* 3. 签名信息
* 4. 传入参数数组
* 5. 。。。
* @param joinPoint
* @return
*/
@Around("pointCut()")
public Object around(ProceedingJoinPoint joinPoint) {
//获取注解的 cacheName
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
//获得标注该注解的方法对象
Method method = signature.getMethod();
//获取该注解
RedisCache annotation = method.getAnnotation(RedisCache.class);
//通过注解获取 cacheName,key,msg,expireTime 信息
String cacheName = annotation.cacheName();
String key = annotation.key();
String msg = annotation.msg();
int expireTime = annotation.expireTime();
//如果expireTime == -2 ,则设置位 0~2000ms的随机过期时间
if (expireTime == -2){
expireTime = (int) (Math.random() * 2000);
}
//这里获取了传入参数的第一个作为缓存的key,当然也可以传入一个封装了key信息的对象,但这里为了简化步骤,就随意设定了
if (joinPoint.getArgs().length>0){
key = (String) joinPoint.getArgs()[0];
}
log.info("annotation's meta -- cacheName : {} , key : {} , msg : {}", cacheName, key, msg);
//判断缓存是否存在
try {
//注意,这里我用hash的数据结构作为缓存
if (!redisTemplate.opsForHash().hasKey(cacheName,key)) {
log.info("缓存不存在!");
//执行了拦截方法的方法体,只有缓存不存在才执行标注注解的方法
Object cache = joinPoint.proceed(joinPoint.getArgs());
redisTemplate.opsForHash().put(cacheName,key,cache);
//设置缓存过期时间
redisTemplate.expire(cacheName,expireTime, TimeUnit.MILLISECONDS);
return cache;
} else {
log.info("缓存存在");
return redisTemplate.opsForHash().get(cacheName,key);
}
} catch (Throwable throwable) {
throwable.printStackTrace();
}
return null;
}
}
上面代码中的Object cache = joinPoint.proceed(joinPoint.getArgs());
表示传入参数并执行被拦截的方法,如果不执行上面代码的话,拦截后将不会执行方法体。
4. 总结
- 实践下来,第一次感受到aop的强大,aop通过动态代理,可以让开发者完全掌控被代理对象,比如,当我拦截了某个方法,开发者可以在方法执行前、执行后、结果返回前、抛出异常前执行自定义的操作,甚至通过
@Around
还能掌控方法是否执行。 - 如有错漏,欢迎评论区指正。