redis异常 Could not get a resource from the pool

异常描述: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();
	}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AleneFv

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值