關於redis併發的程式

javawebkaifa發表於2013-06-29
最近專案中要使用redis來進行資料儲存,我安裝了一臺redis(單機)。我的想法是,併發200去set(key,value)和併發200去get(key)
package com.ljq.utils;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;


public class RedisAPI {
private static JedisPool pool = null;
static int count = 0;

public static JedisPool getPool() {
if (pool == null) {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxActive(1000);
config.setMaxIdle(5);
config.setMaxWait(1000 * 100);
config.setTestOnBorrow(true);
pool = new JedisPool(config, "192.168.1.123", 6379);
}
return pool;
}

public static void returnResource(JedisPool pool, Jedis redis) {
if (redis != null) {
pool.returnResource(redis);
}
}

public static String get(String key){
String value = null;
try {

JedisPool pool = null;
Jedis jedis = null;
try {
pool = getPool();
jedis = pool.getResource();
value = jedis.get(key);
} catch (Exception e) {
pool.returnBrokenResource(jedis);
e.printStackTrace();
} finally {
returnResource(pool, jedis);
}
} catch (Exception e) {
// TODO: handle exception
}

return value;
}

public static String set(String key,String contents){
String value = null;
try {

JedisPool pool = null;
Jedis jedis = null;
try {
pool = getPool();
jedis = pool.getResource();
value = jedis.set(key,contents);
} catch (Exception e) {
pool.returnBrokenResource(jedis);
e.printStackTrace();
} finally {
returnResource(pool, jedis);
}
} catch (Exception e) {
// TODO: handle exception
}

return value;
}


public static void main(String[] args) {
try {
for(int i = 0;i<200;i++){
new Thread( new Runnable() {
public void run() {
System.out.println(set("age","100"));//也可以get(key)
System.out.println("---------------------:"+(++count));
}
}).start();
}
} catch (Exception e) {
// TODO: handle exception
}
}
}
==========================================================================
現在報異常::
redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool
at redis.clients.util.Pool.getResource(Pool.java:22)
at com.ljq.utils.RedisAPI.set(RedisAPI.java:61)
at com.ljq.utils.RedisAPI$1.run(RedisAPI.java:82)
at java.lang.Thread.run(Thread.java:619)
Caused by: java.util.NoSuchElementException: Could not create a validated object, cause: ValidateObject failed
at org.apache.commons.pool.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:1191)
at redis.clients.util.Pool.getResource(Pool.java:20)
... 3 more
我不知道為什麼我配置的執行緒池的1000,怎麼200就報錯!!!急

相關文章