2015-07-21 16 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 { 

     } 
    } 
}