前言
通过SpringAOP技术,动态拦截dao层所有的查询操作,并把mysql数据库中的数据缓存到redis中。下次再次进行同样的查询操作时,从redis中获取数据。一旦进行了增删改操作,需要清除redis缓存。
准备工作
基于SSM项目,缓存前端分页查询数据等操作,如何搭建ssm项目这里不在赘述。
基于AOP使用动态代理,增强功能,拦截所有的查询sql,并做增强操作,需要借助SpringAOP功能,想要使用redis实现缓存业务,需要添加redis和spring整合的相关依赖:
添加对应核心依赖
<!--aop-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.3.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.1</version>
</dependency>
<!--jedis-->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
<!--spring-data-redis-->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.7.2.RELEASE</version>
</dependency>
准备好对应的三层架构Mybatis,Spring,SpringMVC
这里演示的是在以往的ssm项目添加redis缓存功能,主要介绍redis作为缓存使用的应用特点,其他代码不再赘述。
redis实现缓存功能
准备工具类
使用Spring提供的模版类RedisTemplate来操作redis,因此操作redis的相关代码固定,且需要重复书写,所以将操作redis的代码封装成共用的工具类。
RedisUtilNew
@Component
public class RedisUtilNew {
private static ApplicationContext context =new ClassPathXmlApplicationContext("spring/spring-mybatis.xml");
private static RedisTemplate redisTemplate =context.getBean(RedisTemplate.class);
//从redis中获取分页数据
public static Page getPage(int currentPage,User user){
String name = user.getName();
Integer age = user.getAge();
if (name.isEmpty()){
name="all";
}
if (age==null){
age=0;
}
Page page = (Page) redisTemplate.opsForValue().get("page:"+currentPage+":username:"+name+":ag