在 Java 里,有不少用于连接 Redis 的工具,下面为你介绍一些主流的工具及其特点:
Jedis
Jedis 是 Redis 官方推荐的 Java 连接工具,它提供了全面的 Redis 命令支持,且 API 设计直观。
public class JedisExample {
public static void main(String[] args) {
Jedis jedis = new Jedis("localhost", 6379);
jedis.set("key", "value");
String value = jedis.get("key");
System.out.println(value);
jedis.close();
}
}
它的优势在于使用简单,不过在多线程环境下需要配合连接池使用。
下面是jedis连接池的配置使用,需要注意的是使用完连接资源后需要close归还到连接池,在获取资源时候需要重新指定db,在前面的连接close后是仍然保留之前的db
public class JedisUtils {
private static final JedisPool jedisPool;
static {
//配置连接池
JedisPoolConfig poolConfig = new JedisPoolConfig();
//最大连接数
poolConfig.setMaxTotal(5000);
//最大空闲连接
poolConfig.setMaxIdle(1200);
//最小空闲连接
poolConfig.setMinIdle(10);
//最长等待时间,ms
poolConfig.setBlockWhenExhausted(true);
poolConfig.setMaxWaitMillis(-1);
//空闲检查有效性
poolConfig.setTestWhileIdle(true);
//进行有效性检查
// poolConfig.setTestOnBorrow(true);
poolConfig.setTestOnReturn(true);
String pwd = "123456";
String port = "6379";
String timeout = "10000";
String host = "127.0.0.1";
if (StringUtils.isEmpty(pwd)) {
jedisPool = new JedisPool(poolConfig, host, Integer.parseInt(port), Integer.parseInt(timeout));
} else {
jedisPool = new JedisPool(poolConfig, host, Integer.parseInt(port), Integer.parseInt(timeout), pwd);
}
}
public static Jedis getJedisDB(int index) {
log.info("jdeis active num:{}", jedisPool.getNumActive());
Jedis resource = jedisPool.getResource();
resource.select(index);
return resource;
}
Lettuce
Lettuce 是基于 Netty 的高性能 Redis 客户端,它支持同步、异步和响应式编程模式,并且天然适配 Reactive Streams。其特点是线程安全,适合在高并发场景中使用。
public class LettuceExample {
public static void main(String[] args) {
RedisClient redisClient = RedisClient.create(RedisURI.create("redis://localhost:6379"));
StatefulRedisConnection<String, String> connection = redisClient.connect();
RedisCommands<String, String> commands = connection.sync();
commands.set("key", "value");
String value = commands.get("key");
System.out.println(value);
connection.close();
redisClient.shutdown();
}
}
Lettuce 自身提供了GenericObjectPool(基于 Apache Commons Pool)的封装示例,可通过配置PoolConfig控制连接池参数(如最大连接数、空闲连接超时时间等)。
// 配置连接池
GenericObjectPoolConfig<StatefulRedisConnection<String, String>> config = new GenericObjectPoolConfig<>();
config.setMaxTotal(100); // 最大连接数
config.setMinIdle(10); // 最小空闲连接数
// 创建连接工厂
RedisClient client = RedisClient.create("redis://localhost:6379");
RedisURI uri = RedisURI.create("localhost", 6379);
ConnectionFactory<String, String> factory = new JedisConnectionFactory(uri);
// 创建连接池
GenericObjectPool<StatefulRedisConnection<String, String>> pool =
new GenericObjectPool<>(() -> client.connect(), config);
// 从连接池获取连接
try (StatefulRedisConnection<String, String> connection = pool.borrowObject()) {
RedisCommands<String, String> commands = connection.sync();
commands.set("key", "value");
} catch (Exception e) {
// 异常处理
} finally {
pool.returnObject(connection); // 归还连接
}
Redisson
Redisson 是一个在 Redis 基础上实现的分布式和可扩展的 Java 数据结构集合。它提供了如分布式锁、分布式集合等高级功能。
public class RedissonExample {
public static void main(String[] args) {
Config config = new Config();
config.useSingleServer().setAddress("redis://localhost:6379");
RedissonClient redisson = Redisson.create(config);
RLock lock = redisson.getLock("myLock");
lock.lock();
try {
// 执行需要加锁的业务逻辑
} finally {
lock.unlock();
}
redisson.shutdown();
}
}
以下是 Redisson 连接池的典型配置代码
public class RedissonConfigExample {
// 单机模式配置
public static RedissonClient createSingleServerClient() {
Config config = new Config();
config.useSingleServer()
.setAddress("redis://localhost:6379")
.setDatabase(0)
// 连接池配置
.setConnectionPoolSize(100) // 最大连接数
.setConnectionMinimumIdleSize(10) // 最小空闲连接数
.setSubscriptionConnectionPoolSize(50) // 订阅连接池大小
// 超时配置
.setConnectTimeout(5000) // 连接超时时间(毫秒)
.setTimeout(3000) // 命令超时时间(毫秒)
.setRetryAttempts(3) // 重试次数
.setRetryInterval(1500) // 重试间隔(毫秒)
// 空闲检测
.setIdleConnectionTimeout(10000) // 空闲连接超时时间(毫秒)
.setPingConnectionInterval(60000); // 心跳检测间隔(毫秒)
return Redisson.create(config);
}
// 主从模式配置
public static RedissonClient createMasterSlaveClient() {
Config config = new Config();
config.useMasterSlaveServers()
.setMasterAddress("redis://master:6379")
.addSlaveAddress("redis://slave1:6379", "redis://slave2:6379")
// 读写分离配置
.setReadMode(ReadMode.SLAVE) // 读操作优先从从节点获取
.setSubscriptionMode(ReadMode.MASTER) // 订阅操作使用主节点
// 连接池配置(主节点)
.setMasterConnectionPoolSize(100)
.setMasterConnectionMinimumIdleSize(10)
// 连接池配置(从节点)
.setSlaveConnectionPoolSize(100)
.setSlaveConnectionMinimumIdleSize(10)
// 其他通用配置(同单机模式)
.setConnectTimeout(5000)
.setTimeout(3000);
return Redisson.create(config);
}
// 哨兵模式配置
public static RedissonClient createSentinelClient() {
Config config = new Config();
config.useSentinelServers()
.setMasterName("mymaster")
.addSentinelAddress("redis://sentinel1:26379",
"redis://sentinel2:26379",
"redis://sentinel3:26379")
// 哨兵监控相关配置
.setCheckSentinelsList(false) // 是否检查哨兵列表
.setScanInterval(2000) // 哨兵扫描间隔(毫秒)
// 连接池配置
.setMasterConnectionPoolSize(100)
.setSlaveConnectionPoolSize(100)
.setSubscriptionConnectionPoolSize(50)
// 其他配置
.setConnectTimeout(5000)
.setDatabase(0);
return Redisson.create(config);
}
// 集群模式配置
public static RedissonClient createClusterClient() {
Config config = new Config();
config.useClusterServers()
.addNodeAddress("redis://node1:7000", "redis://node2:7001",
"redis://node3:7002", "redis://node4:7003")
// 集群扫描与拓扑发现
.setScanInterval(2000) // 集群状态扫描间隔(毫秒)
.setCheckSlotsCoverage(true) // 是否检查槽覆盖情况
// 负载均衡策略
.setLoadBalancer(new org.redisson.connection.balancer.RoundRobinLoadBalancer())
// 连接池配置(每个节点)
.setNodeConnectionMinimumIdleSize(10)
.setNodeConnectionPoolSize(64)
// 重试与超时
.setRetryAttempts(3)
.setRetryInterval(1500)
.setTimeout(3000);
return Redisson.create(config);
}
public static void main(String[] args) {
// 根据实际环境选择配置方式
RedissonClient client = createSingleServerClient();
// 使用示例
try {
client.getBucket("testKey").set("testValue");
System.out.println(client.getBucket("testKey").get());
} finally {
client.shutdown(); // 关闭客户端时自动释放连接池资源
}
}
}
Redisson 的优势在于提供了丰富的分布式对象和服务。
Spring Data Redis
Spring Data Redis 是 Spring 框架的一部分,它为 Redis 提供了高度抽象的 API。
@Configuration
public class RedisConfig {
@Bean
public JedisConnectionFactory connectionFactory() {
RedisStandaloneConfiguration config = new RedisStandaloneConfiguration("localhost", 6379);
return new JedisConnectionFactory(config);
}
@Bean
public RedisTemplate<String, Object> redisTemplate() {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory());
return template;
}
}
借助 Spring 的依赖注入机制,它能让 Redis 的操作变得更加简便。
可以根据项目的具体需求来挑选合适的 Redis 连接工具。
● 若你追求简单易用的工具,那么 Jedis 是个不错的选择。
● 要是处于高并发场景,Lettuce 会更适合你。
● 当你需要分布式锁或分布式集合等高级功能时,Redisson 是首选。
● 如果你在使用 Spring 框架,Spring Data Redis 能让你更好地集成 Redis。
例如在呼叫中心系统中的配置更新操作上就可以选择jedis、Spring Data Redis完成参数的更迭,在呼叫黑名单系统中就可以选择Lettuce来进行开发,在对部分分布式系统的接口验证上可以使用Redisson