异常描述:redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool
在网上找了很多资料,最后按照http://jiasky.iteye.com/blog/1469190所说设置了JedisPoolConfig中maxActive后,同时跑100个线程去操作时没有报异常错误,但是超过100个线程就会报异常错误,线程跑得越多,Could not get a resource from the pool的异常错误也越多。
解决办法:Jedis 对象用完以后,要释放掉,不让会一直占用,所以会出现无法获取新的资源。
String key = "comcurrency";
redis.opsForValue().set(key, 100, 1L, TimeUnit.HOURS);
ExecutorService service = Executors.newCachedThreadPool();
final CountDownLatch cdOrder = new CountDownLatch(1);
final CountDownLatch cdAnswer = new CountDownLatch(100);
for (int i = 0; i < 100; i++) {
Runnable runnable = new Runnable() {
public void run() {
try {
Integer andSet = redis.opsForValue().getAndSet(key, 1);
if (100 == andSet) {
System.out.println("我是第一个拿到100的。。。" + Thread.currentThread().getName());
} else if (1 == andSet) {
System.out.println("真可惜100已经被人拿了。。。" + Thread.currentThread().getName());
}
cdOrder.await();
Thread.sleep((long) (Math.random() * 10000));
} catch (Exception e) {
e.printStackTrace();
} finally {
cdAnswer.countDown();
//注意:这里要释放,不然会报资源不足
redis = null;
}
}
};
service.execute(runnable);
}
try {
Thread.sleep((long) (Math.random() * 10000));
cdOrder.countDown();
cdAnswer.await();
} catch (Exception e) {
e.printStackTrace();
}
service.shutdown();
}