技术派整合Redis(多Redis配置/Redis集群)
基本上,主要是后端,现在都离不开redis这个知识点,在我们的技术派项目,也同样使用了redis来做一些相关业务支持(如缓存、排行榜、计数器等)
由于redis的知识点相对较多,所以我们下来看一下,如何在我们的实际项目中,引入redis
redis集成
1. 配置依赖
spring-boot提供了非常简单的redis集成,引入一个包,并配置上对应的redis相关连接配置即可
org.springframework.boot
spring-boot-starter-data-redis
当我们使用默认的 127.0.0.1, 端口号 3379,无密码时,你完全无需在配置文件中做任何其他的操作,直接在需要的地方,引入 RestTemplate 就可以直接使用了,如
@SpringBootApplication
public class Application {
public Application(RedisTemplate redisTemplate) {
// 往Redis中写入key=hello, value=world
redisTemplate.opsForValue().set("hello", "world");
// 查询redis中key=hello的值
String ans = redisTemplate.opsForValue().get("hello");
Assert.isTrue("world".equals(ans));
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
2. 自定义参数配置
在技术派中,自定义的参数配置在 paicoding\paicoding-web\src\main\resources-env\dev\application-dal.yml
(本机开发时,默认是dev环境)

但是,若当我们需要添加连接池相关配置时,如

此时,我们可能需要在pom.xml中添加
org.apache.commons
commons-pool2
3. 多redis连接配置
虽然实际的项目中,不太可能出现一个项目连接多个redis实例的情况,但是,当真的出现了,也是允许的,这种时候,就不能直接使用默认的,需要我们自己来声明ConnectionFactory和 RedisTemplate
配置如下
spring:
redis:
host: 127.0.0.1
port: 6379
password:
lettuce:
pool:
max-active: 32
max-wait: 300
max-idle: 16
min-idle: 8
database: 0
local-redis:
host: 127.0.0.1
port: 6379
database: 0
password:
lettuce:
pool:
max-active: 16
max-wait: 100
max-idle: 8
min-idle: 4
对应的配置类,采用Lettuce,基本设置如下,套路都差不多,先读取配置,初始化ConnectionFactory,然后创建RedisTemplate实例,设置连接工厂
@Configuration
public class RedisAutoConfig {
@Bean
public LettuceConnectionFactory defaultLettuceConnectionFactory(RedisStandaloneConfiguration defaultRedisConfig,
GenericObjectPoolConfig defaultPoolConfig) {
LettuceClientConfiguration clientConfig =
LettucePoolingClientConfiguration.builder().commandTimeout(Duration.ofMillis(100))
.poolConfig(defaultPoolConfig).build();
return new LettuceConnectionFactory(defaultRedisConfig, clientConfig);
}
@Bean
public RedisTemplate defaultRedisTemplate(
LettuceConnectionFactory defaultLettuceConnectionFactory) {
RedisTemplate redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(defaultLe... 未能定位到原文的划线
企业级Agent工作流编排项目PaiFlow
Vibe Coding版本的PaiAgent
派聪明RAG AI知识库Java版本+Go版本
微服务 PmHub、技术派、MYDB
求职派JobClaw(OpenClaw/Hermes架构
PaiCLI(类似Claude Code的Agent
派简历(代码已完成)
等实战项目。
1. 微信扫右侧的优惠券加入知识星球
2. 解锁星球的实战项目教程和源码: 项目源码+教程获取
真诚点赞 诚不我欺
回复