Redis连接池Demo快速搭建指南,新手入门与高手优化,你选哪个?

文章导读
新手入门选Jedis连接池快速搭建,代码如下:import redis.clients.jedis.JedisPool;import redis.clients.jedis.JedisPoolConfig;JedisPoolConfig config = new JedisPoolConfig();config.setMaxTotal(20);config.setMaxIdle(10);confi
📋 目录
  1. CSDN博客
  2. 博客园
  3. 掘金
  4. Cnblogs
  5. 阿里云开发者社区
  6. 知乎专栏
A A

新手入门选Jedis连接池快速搭建,代码如下:
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(20);
config.setMaxIdle(10);
config.setMinIdle(5);
JedisPool pool = new JedisPool(config, "127.0.0.1", 6379);
Jedis jedis = pool.getResource();
jedis.set("key", "value");
pool.close();

CSDN博客

Redis连接池是Redis客户端与Redis服务器端之间的连接“容器”,在实际生产中,我们经常会遇到Tomcat、Jetty等容器的连接池,Redis的连接池也是类似的概念。Redis客户端与Redis服务器端进行通信都是通过建立tcp socket连接来实现的。如果想高并发地进行海量请求,需要建立大量连接,但由于连接的建立和断开开销较大(三次握手、四次挥手),维护大量连接对服务器的压力也是非常大的。

博客园

在使用JedisPool时,JedisPoolConfig中的一些参数说明:1)maxTotal:连接池中的最大连接数,默认值为8;2)maxIdle:连接池中的最大空闲连接数,默认值为8;3)minIdle:连接池中的最小空闲连接数,默认值为0;4)maxWaitMillis:获取连接时的最大等待毫秒数(如果设置为阻塞时BlockWhenExhausted),默认值为-1,表示永不超时;

Redis连接池Demo快速搭建指南,新手入门与高手优化,你选哪个?

掘金

高手优化:使用Lettuce连接池,非阻塞IO,支持异步。LettucePoolConfig config = LettucePoolingClientConfiguration.builder().poolConfig(genericObjectPoolConfig()).build();RedisClient client = RedisClient.create("redis://localhost:6379");StatefulRedisConnection connection = client.connect();

Cnblogs

新手最简单Demo:public class RedisPoolTest { private static JedisPool pool = null; @BeforeClass public static void init() { JedisPoolConfig config = new JedisPoolConfig(); config.setMaxTotal(30); pool = new JedisPool(config, "localhost", 6379); } }

Redis连接池Demo快速搭建指南,新手入门与高手优化,你选哪个?

阿里云开发者社区

高手优化点:设置testOnBorrow=true,确保借出连接有效;testOnReturn=true,返回时测试;testWhileIdle=true,空闲时测试;timeBetweenEvictionRunsMillis=30000,每30秒检查一次。

Redis连接池Demo快速搭建指南,新手入门与高手优化,你选哪个?

知乎专栏

连接池参数调优:对于高并发场景,maxTotal设置为CPU核心数*2;minIdle设置为maxTotal的1/3;避免频繁创建连接,提高吞吐量。

FAQ
Q: 新手为什么用JedisPool而不是直接Jedis?
A: 直接new Jedis()每次都创建新连接,开销大,连接池复用连接,效率高。
Q: Lettuce和Jedis哪个好?
A: 新手Jedis简单,高手选Lettuce支持异步和集群。
Q: 连接池满时怎么处理?
A: 设置maxWaitMillis等待,或用BlockWhenExhausted阻塞。
Q: 如何关闭连接池?
A: 在应用关闭时调用pool.close()释放资源。