java如何配置redis
配置 Redis 与 Java 集成
依赖引入
在 Maven 项目中添加 Jedis 或 Lettuce 依赖(以 Jedis 为例):
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>4.3.1</version>
</dependency>
基本连接配置
创建 Redis 连接池并配置参数:
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxTotal(128); // 最大连接数
poolConfig.setMaxIdle(32); // 空闲连接数
JedisPool jedisPool = new JedisPool(poolConfig, "localhost", 6379);
try (Jedis jedis = jedisPool.getResource()) {
jedis.set("key", "value"); // 示例操作
}
高级配置选项
连接超时与认证
若 Redis 需要密码或自定义超时:
JedisPool jedisPool = new JedisPool(
poolConfig,
"localhost",
6379,
2000, // 连接超时(毫秒)
"your_password"
);
Lettuce 客户端配置
如需使用异步客户端 Lettuce:
<dependency>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
<version>6.2.4.RELEASE</version>
</dependency>
代码示例:
RedisClient client = RedisClient.create("redis://password@localhost:6379");
StatefulRedisConnection<String, String> connection = client.connect();
RedisCommands<String, String> commands = connection.sync();
commands.set("key", "value");
connection.close();
client.shutdown();
Spring Boot 集成配置
配置文件
在 application.properties 中配置:
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=your_password
spring.redis.jedis.pool.max-active=128
自动注入
通过 RedisTemplate 直接操作:
@Autowired
private RedisTemplate<String, String> redisTemplate;
public void setValue(String key, String value) {
redisTemplate.opsForValue().set(key, value);
}
注意事项
- 生产环境建议使用连接池管理资源。
- 敏感信息(如密码)应通过环境变量或配置中心管理。
- Lettuce 支持响应式编程,适合高并发场景。







