标签:jedis
1.pom.xml中依赖如下:
<dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.6.1</version> </dependency>
2.jedis pool中ping的产生
线上storm的bolt使用jedis pool操作redis,高峰时压力一直比较大,每s处理量多达10w/s,redis持续跑满(单线程,cpu100%),对monitor数据分析,发现50%以上的都是ping操作,ping是用来检测redis是否可用的操作,在jedis pool中由两个参数控制:
setTestOnBorrow //获取连接时是否触发ping setTestOnReturn //释放连接时是否触发ping
默认两个值都是true的,设置为false即可
3.获取不到资源时jedis的处理
1)当setBlockWhenExhausted设置为true(默认即为true)时,阻塞setMaxWaitMillis时间(默认为-1,会一直阻塞),超过时间限制则抛出异常:
Exception in thread "main" redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool at redis.clients.util.Pool.getResource(Pool.java:53) at redis.clients.jedis.JedisPool.getResource(JedisPool.java:99) at main.java.JedisPoolTest.main(JedisPoolTest.java:20) Caused by: java.util.NoSuchElementException: Timeout waiting for idle object at org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:442) at org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:360) at redis.clients.util.Pool.getResource(Pool.java:51) ... 2 more
2)当setBlockWhenExhausted(false);设置为false时,直接抛出异常,不会阻塞
4.jedis的默认db都是0,可以通过构造函数的参数进行设置
5.防止资源泄露,在catch异常的时候使用JedisPool.returnBrokenResource释放连接,可以使用JedisPool.getNumActive获取当前的活动连接数
6.pool的初始化经常使用静态代码块完成
7.sharding的模式也是支持pipline的
附1个jedissharding pipeline的例子:
package main.java; import redis.clients.jedis.JedisPoolConfig; import redis.clients.jedis.JedisShardInfo; import redis.clients.jedis.ShardedJedisPool; import redis.clients.jedis.ShardedJedis; import redis.clients.jedis.ShardedJedisPipeline; import java.util.List; import java.util.LinkedList; public class JedisPoolTest { private static ShardedJedisPool pool = null; private static ShardedJedisPipeline pip = null; public static void main(String[] args) { JedisPoolConfig jc = new JedisPoolConfig(); jc.setBlockWhenExhausted(false); jc.setMaxIdle(8); jc.setMaxTotal(20); jc.setTestOnBorrow(false); jc.setTestOnReturn(false); jc.setMaxWaitMillis(-1); JedisShardInfo jedisShardInfo1 = new JedisShardInfo("192.168.101.42",6379); JedisShardInfo jedisShardInfo2 = new JedisShardInfo("192.168.101.42",6380); List<JedisShardInfo> list = new LinkedList<JedisShardInfo>(); list.add(jedisShardInfo1); list.add(jedisShardInfo2); pool = new ShardedJedisPool(jc, list); ShardedJedis jedis = pool.getResource(); pip = jedis.pipelined(); long start = System.currentTimeMillis(); for(int i = 0;i <= 100;i++){ String key = "shardpool" + String.valueOf(i); pip.del(key); pip.set(key, "test"); } pool.returnResource(jedis); pip.syncAndReturnAll(); long end = System.currentTimeMillis(); long elapse = end - start; System.out.println("10000 itmes elapse time is " + String.valueOf(elapse)); } }
本文出自 “菜光光的博客” 博客,请务必保留此出处http://caiguangguang.blog.51cto.com/1652935/1635752
标签:jedis
原文地址:http://caiguangguang.blog.51cto.com/1652935/1635752