SpringBoot整合Redis缓存的方法介绍


本文摘自PHP中文网,作者尚,侵删。

SpringBoot整合Redis缓存的方法:

1、引入缓存依赖

1

2

3

4

5

<dependency>

     <groupId>org.springframework.boot</groupId>

     <artifactId>spring-boot-starter-data-redis</artifactId>

     <version>2.1.5.RELEASE</version>

</dependency>

2. 增加缓存配置

在application.properties文件中增加以下配置

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

## Redis部分

# Redis服务器地址

spring.redis.host=${redis.host}

# Redis服务器连接端口

spring.redis.port=${redis.port}

# Redis服务器连接密码(默认为空)

spring.redis.password=${redis.password}

# 连接池最大连接数(使用负值表示没有限制)

spring.redis.jedis.pool.max-active=${redis.maxTotal}

# 连接池最大阻塞等待时间(使用负值表示没有限制)

spring.redis.jedis.pool.max-wait=-1ms

# 连接池中的最大空闲连接

spring.redis.jedis.pool.max-idle=${redis.maxIdle}

# 连接池中的最小空闲连接

spring.redis.jedis.pool.min-idle=4

# 连接超时时间(毫秒)

spring.redis.timeout=5000

 

## Cache部分

#缓存的名称集合,多个采用逗号分割

spring.cache.cache-names=

#缓存的类型,官方提供了很多,这里我们填写redis

spring.cache.type=redis

#是否缓存null数据,默认是false

spring.cache.redis.cache-null-values=false

#redis中缓存超时的时间,默认60000ms

spring.cache.redis.time-to-live=60000

#缓存数据key是否使用前缀,默认是true

spring.cache.redis.use-key-prefix=true

#缓存数据key的前缀,在上面的配置为true时有效,

spring.cache.redis.key-prefix=

3. 增加开启缓存注解EnableCaching

1

2

3

4

5

6

7

@EnableCaching

public class WebApplication {

 

    public static void main(String[] args) {

        SpringApplication.run(WebApplication.class, args);

    }

}

4. 增加缓存注解

@Cacheable

该注解作用是标识这个方法返回值将会被缓存;

需要注意 condition 和 unless ,它们都是条件判断参数:

  • condition:在调用方法之前进行判断,所以不能将方法的结果值作为判断条件;

  • unless:在调用方法之后进行判断,此时可以拿到方法放回值作为判断条件。

所以依赖方法返回值作为是否进行缓存的操作必须使用 unless 参数,而不是 condition

@CachePut

将方法返回值更新当前缓存

@CacheEvict

将当前缓存过期(清空)

更多相关知识请关注redis入门教程栏目

以上就是SpringBoot整合Redis缓存的方法介绍的详细内容,更多文章请关注木庄网络博客

相关阅读 >>

redis缓存是什么

springBoot整合redis缓存的方法介绍

springBoot事务详细简介

21个使用redis时必须注意的要点(总结)

redis缓存是什么意思

更多相关阅读请进入《springBoot》频道 >>


数据库系统概念 第6版
书籍

数据库系统概念 第6版

机械工业出版社

本书主要讲述了数据模型、基于对象的数据库和XML、数据存储和查询、事务管理、体系结构等方面的内容。



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...