Jedis(Java+Redis) Pool的使用
今天试了一下Jedis里连接池JedisPool的的使用。代码如下:
package com.myapp.jedis.pooldemo; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; /** * Created by baidu on 16/10/18. */ public class TestPool { private static JedisPool pool = null; public static JedisPool getPool() { if (pool == null) { JedisPoolConfig config = new JedisPoolConfig(); config.setMaxTotal(500); config.setMaxIdle(5); config.setMaxWaitMillis(1000*10); //在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的; config.setTestOnBorrow(true); //new JedisPool(config, ADDR, PORT, TIMEOUT, AUTH); pool = new JedisPool(config, "[ip]", 8379, 10000, "[auth]"); } return pool; } public synchronized static Jedis getResource() { if (pool == null) { pool = getPool(); } return pool.getResource(); } // 返还到连接池 // Deprecated // 换成用完之后, redis.close() /* public static void returnResource(Jedis redis) { if (redis != null) { pool.returnResource(redis); } } */ public static void main(String[] args) { Jedis redis = null; int loop = 1; while (loop < 20) { try { long start = System.currentTimeMillis(); redis = getResource(); redis.set("k1", "v1"); String ret = redis.get("k1"); long end = System.currentTimeMillis(); System.out.printf("Get ret from redis: %s with %d millis\n", ret, end-start); } finally { if (redis != null) { redis.close(); } } loop++; } } }
其中,有个函数returnResource已经deprecated了,现在Jedis的close方法重写了,用Jedis.close来释放资源。
跑了20次,运行结果如下:
Get ret from redis: v1 with 564 millis Get ret from redis: v1 with 235 millis Get ret from redis: v1 with 225 millis Get ret from redis: v1 with 214 millis Get ret from redis: v1 with 210 millis Get ret from redis: v1 with 232 millis Get ret from redis: v1 with 209 millis Get ret from redis: v1 with 211 millis Get ret from redis: v1 with 239 millis Get ret from redis: v1 with 207 millis Get ret from redis: v1 with 215 millis Get ret from redis: v1 with 223 millis Get ret from redis: v1 with 291 millis Get ret from redis: v1 with 220 millis Get ret from redis: v1 with 214 millis Get ret from redis: v1 with 219 millis Get ret from redis: v1 with 257 millis Get ret from redis: v1 with 214 millis Get ret from redis: v1 with 211 millis Process finished with exit code 0
可以看出,第一次500多毫秒,之后都是200多毫秒,速度有提高。
分类:
Java学习
, MySQL&Redis&MQ
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!