如何在Spring Boot应用程序中使用Redis?

本文详细介绍如何在SpringBoot项目中使用Redis缓存,包括配置Lettuce或Jedis客户端库,设置连接池参数,激活缓存功能,并提供具体代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在Spring Boot应用程序中使用Redis缓存的步骤:

1.要获得Redis连接,我们可以使用Lettuce或Jedis客户端库,Spring Boot 2.0启动程序spring-boot-starter-data-redis默认使用了Lettuce。要获得Redis的池化连接工厂,我们需要在类路径上提供commons-pool2,下面展示使用Lettuce情况下的Maven依赖项配置:

org.springframework.bootspring-boot-starter-data-redisorg.apache.commonscommons-pool2

2.在application.properties中配置spring.redis.*前缀的参数:

spring.redis.host=localhost

spring.redis.port=6379

spring.redis.password=

spring.redis.lettuce.pool.max-active=7

spring.redis.lettuce.pool.max-idle=7

spring.redis.lettuce.pool.min-idle=2

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

spring.redis.lettuce.shutdown-timeout=200ms

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

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

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

3. 在 @SpringBootApplication类使用@EnableCaching激活Redis:

@SpringBootApplication

@EnableCaching

publicclassSpringBootAppStarter {

publicstaticvoidmain(String[] args) {

SpringApplication.run(SpringBootAppStarter.class, args);

}

}

如果想用Jedis 客户端,需要排除Lettuce,加入Jedis:

org.springframework.bootspring-boot-starter-data-redisio.lettucelettuce-coreredis.clientsjedis

jedis将自动在类路径上解决commons-pool2, application配置:

spring.redis.host=localhost spring.redis.port=6379spring.redis.password= spring.redis.jedis.pool.max-active=7spring.redis.jedis.pool.max-idle=7spring.redis.jedis.pool.min-idle=2spring.redis.jedis.pool.max-wait=-1ms

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值