2015-07-21 41 views

回答

0

我不確定Jedis與Java 5的兼容性。您可以基於較早的commons-pool 1.6庫創建自己的池。您不需要在班級路徑上使用commons-pool2來運行jedis。我使用Jedis 2.7.3和commons-pool 1.6來驗證解決方案。

查找附加示例代碼:

import org.apache.commons.pool.ObjectPool; 
import org.apache.commons.pool.PoolableObjectFactory; 
import org.apache.commons.pool.impl.GenericObjectPool; 
import redis.clients.jedis.Jedis; 

public class JedisWithOwnPooling { 

    public static void main(String[] args) throws Exception { 

     ObjectPool<Jedis> pool = new GenericObjectPool(new JedisFactory("localhost")); 

     Jedis j = pool.borrowObject(); 
     System.out.println(j.ping()); 

     pool.returnObject(j); 

     pool.close(); 

    } 

    private static class JedisFactory implements PoolableObjectFactory<Jedis> { 

     private String host; 

     /** 
     * Add fields as you need. That's only an example. 
     */ 
     public JedisFactory(String host) { 
      this.host = host; 
     } 

     @Override 
     public Jedis makeObject() throws Exception { 
      return new Jedis(host); 
     } 

     @Override 
     public void destroyObject(Jedis jedis) throws Exception { 
      jedis.close(); 
     } 

     @Override 
     public boolean validateObject(Jedis jedis) { 
      return jedis.isConnected(); 
     } 

     @Override 
     public void activateObject(Jedis jedis) throws Exception { 
      if (!jedis.isConnected()) { 
       jedis.connect(); 
      } 
     } 

     @Override 
     public void passivateObject(Jedis jedis) throws Exception { 

     } 
    } 
}