2016-11-04 81 views
0

我使用Redis的(3.2.100)池連接的Windows緩存在Java.This我數據庫中的數據是我Redis的初始化代碼:如何重用的Redis(JRedis)在Java中

private static Dictionary<Integer, JedisPool> pools = new Hashtable(); 

    static { 
     JedisPoolConfig config = new JedisPoolConfig(); 
     config.setMaxIdle(2); 
     config.setMaxTotal(10); 
     config.setTestOnBorrow(true); 
     config.setMaxWaitMillis(2000); 
     for (int i = 0; i < 16; i++) { 
      JedisPool item = new JedisPool(config, "127.0.0.1", 6379,10*1000); 
      pools.put(i, item); 
     } 
    } 

這就是緩存代碼:

public static String get(String key, Integer db) { 
     JedisPool poolItem = pools.get(db); 
     Jedis jredis = poolItem.getResource(); 
     String result = jredis.get(key); 
     return result; 
    } 

的問題,當了一段時間的程序運行,該方法的getResource拋出的是:

redis.clients.jedis.exceptions.JedisException: Could not get a resource from the pool 

所以如何再利用合作nnection或關閉連接。我正在使用此命令查明客戶端已達到最大值。

D:\Program Files\Redis>redis-cli.exe info clients 
# Clients 
connected_clients:11 
client_longest_output_list:0 
client_biggest_input_buf:0 
blocked_clients:0 

如何解決?

+0

的JedisException應該因爲一個NoSuchElementException的被拋出。你能提供更多關於它的信息嗎? – herokingsley

回答

0

記得關閉Redis的連接,修改該函數是這樣的:

public static String get(String key, Integer db) { 
     JedisPool poolItem = pools.get(db); 
     Jedis jredis = null; 
     String result = null; 
     try { 
      jredis = poolItem.getResource(); 
      result = jredis.get(key); 
     } catch (Exception e) { 
      log.error("get value error", e); 
     } finally { 
      if (jredis != null) { 
       jredis.close(); 
      } 
     } 
     return result; 
    }