关于jedis的使用小结

前端之家收集整理的这篇文章主要介绍了关于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,会一直阻塞),超过时间限制则抛出异常:

Exceptioninthread"main"redis.clients.jedis.exceptions.JedisConnectionException:Couldnotgetaresourcefromthepool
atredis.clients.util.Pool.getResource(Pool.java:53)
atredis.clients.jedis.JedisPool.getResource(JedisPool.java:99)
atmain.java.JedisPoolTest.main(JedisPoolTest.java:20)
Causedby:java.util.NoSuchElementException:Timeoutwaitingforidleobject
atorg.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:442)
atorg.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:360)
atredis.clients.util.Pool.getResource(Pool.java:51)
...2more

2)当setBlockWhenExhausted(false);设置为false时,直接抛出异常,不会阻塞

4.jedis的默认db都是0,可以通过构造函数的参数进行设置

5.防止资源泄露,在catch异常的时候使用JedisPool.returnBrokenResource释放连接,可以使用JedisPool.getNumActive获取当前的活动连接数

6.pool的初始化经常使用静态代码块完成

7.sharding的模式也是支持pipline的

附1个jedissharding pipeline的例子:

packagemain.java;
importredis.clients.jedis.JedisPoolConfig;
importredis.clients.jedis.JedisShardInfo;
importredis.clients.jedis.ShardedJedisPool;
importredis.clients.jedis.ShardedJedis;
importredis.clients.jedis.ShardedJedisPipeline;
importjava.util.List;
importjava.util.LinkedList;
publicclassJedisPoolTest{
privatestaticShardedJedisPoolpool=null;
privatestaticShardedJedisPipelinepip=null;
publicstaticvoidmain(String[]args){
JedisPoolConfigjc=newJedisPoolConfig();
jc.setBlockWhenExhausted(false);
jc.setMaxIdle(8);
jc.setMaxTotal(20);
jc.setTestOnBorrow(false);
jc.setTestOnReturn(false);
jc.setMaxWaitMillis(-1);
JedisShardInfojedisShardInfo1=newJedisShardInfo("192.168.101.42",6379);
JedisShardInfojedisShardInfo2=newJedisShardInfo("192.168.101.42",6380);
List<JedisShardInfo>list=newLinkedList<JedisShardInfo>();
list.add(jedisShardInfo1);
list.add(jedisShardInfo2);
pool=newShardedJedisPool(jc,list);
ShardedJedisjedis=pool.getResource();
pip=jedis.pipelined();
longstart=System.currentTimeMillis();
for(inti=0;i<=100;i++){
Stringkey="shardpool"+String.valueOf(i);
pip.del(key);
pip.set(key,"test");
}
pool.returnResource(jedis);
pip.syncAndReturnAll();
longend=System.currentTimeMillis();
longelapse=end-start;
System.out.println("10000itmeselapsetimeis"+String.valueOf(elapse));
}
}
原文链接:https://www.f2er.com/javaschema/284832.html

猜你在找的设计模式相关文章