记Jedis客户端并发问题

版权声明: https://blog.csdn.net/luoyoub/article/details/81814286

先来看问题,在对分布式锁进行压测时抛出异常:

java.lang.ClassCastException: java.lang.Long cannot be cast to [B
    at redis.clients.jedis.Connection.getStatusCodeReply(Connection.java:239)
    at redis.clients.jedis.Jedis.set(Jedis.java:139)
    at com.quancheng.shared.distribute.concurrent.JedisLock.acquire(JedisLock.java:55)
    at com.quancheng.shared.distribute.concurrent.JedisLock.tryLock(JedisLock.java:93)
    at com.quancheng.shared.distribute.impl.JedisLockTest$LockTask.run(JedisLockTest.java:76)

网上搜一下,都是说是Jedis并发问题,看看github主页issue:
https://github.com/xetorthio/jedis/issues?utf8=%E2%9C%93&q=java.lang.Long+cannot+be+cast+to+%5BB
这里写图片描述
仔细看下来都是说多线程并发导致的问题,jedis官网指南:

/// Jedis implements Closeable. Hence, the jedis instance will be auto-closed after the last statement.
try (Jedis jedis = pool.getResource()) {
  /// ... do stuff here ... for example
  jedis.set("foo", "bar");
  String foobar = jedis.get("foo");
  jedis.zadd("sose", 0, "car"); jedis.zadd("sose", 0, "bike"); 
  Set<String> sose = jedis.zrange("sose", 0, -1);
}
/// ... when closing your application:
pool.close();

或者使用try-finally方式:

Jedis jedis = null;
try {
  jedis = pool.getResource();
  /// ... do stuff here ... for example
  jedis.set("foo", "bar");
  String foobar = jedis.get("foo");
  jedis.zadd("sose", 0, "car"); jedis.zadd("sose", 0, "bike"); 
  Set<String> sose = jedis.zrange("sose", 0, -1);
} finally {
  // You have to close jedis object. If you don't close then
  // it doesn't release back to pool and you can't get a new
  // resource from pool.
  if (jedis != null) {
    jedis.close();
  }
}
/// ... when closing your application:
pool.close();

说的很明白,必须得释放jedis object;每个线程使用一个jedis object;
再结合这位网友分享的经验:https://yq.aliyun.com/articles/236384?spm=a2c4e.11153940.blogcont236383.20.d17a1c96Lm3AHM#cc8
直接看【八、java.lang.ClassCastException: java.lang.Long cannot be cast to java.util.List】
这样看来,是我们自己本身的代码出了问题,并不是大牛的问题^_^

猜你喜欢

转载自blog.csdn.net/luoyoub/article/details/81814286
今日推荐