本文主要是记录我使用redis缓存的学习,由于数据量较大,每次搜索都要查询数据库,很耗时间和资源。redis非常好用,效率高。

1、maven依赖关系

在pom.xml文件中引入redis.

<!-- 引入redis缓存 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>            
        </dependency>

2、修改配置文件

在本项目中,我在application.properties文件配置,所以在这里修改。当然在这些之前呢,你的电脑要去redis官网下载redis,并且安装打开。

## Redis 配置
## Redis数据库索引(默认为0)
spring.redis.database=0
## Redis服务器地址
spring.redis.host=127.0.0.1
## Redis服务器连接端口
spring.redis.port=6379
## Redis服务器连接密码(默认为空)
spring.redis.password=
## 连接池最大连接数(使用负值表示没有限制)
spring.redis.max-active=8
## 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.max-wait=-1
## 连接池中的最大空闲连接
spring.redis.max-idle=8
## 连接池中的最小空闲连接
spring.redis.min-idle=0
## 连接超时时间(毫秒)
spring.redis.timeout=3000

一般都是默认的,不需要修改端口那些。

3、序列化类

public class RptGroupAgent implements Serializable

注解开启缓存功能

springboot缓存注解缓存加入到数组 springboot缓存注解开启redis_springboot

4、使用注解开发

@Cacheable(value="RptGroupAgent",key="'localAgentName'+#localAgentName")
    @Override
    public List<RptGroupAgent> getRptGroupAgentByName(String localAgentName) throws Exception {
        List<RptGroupAgent> agents=agentMapper.getRptGroupAgentByName(localAgentName);
        System.out.print("========================"+localAgentName);
        return  agents;

    }

Cacheable最适合我,其他两个一个清空,一个每次还是要执行我的service方法。我需要的是查一次没有缓存的就执行service方法,如果已经缓存的就不要执行,直接从缓存中拿。

5、测试

我在后台的service方法中添加后台输出,如果注解开发成功,那么就不会输出,如果第一次查,没有缓存也会有输出。

第一次我就试试“盖伦”,没出现发过的。

springboot缓存注解缓存加入到数组 springboot缓存注解开启redis_springboot_02


然后后台结果是:

springboot缓存注解缓存加入到数组 springboot缓存注解开启redis_springboot_03


第二次我输入“营业厅”,之前输入过得。

springboot缓存注解缓存加入到数组 springboot缓存注解开启redis_spring_04


结果是:

springboot缓存注解缓存加入到数组 springboot缓存注解开启redis_spring_05


只有我删除的“盖伦”,删除的时候盖字查了一次,营业厅没有继续查数据库,redis注解开发成功!