Search code examples
connectionconnection-poolingjedisjava-5

Jedis Cache implementation without JedisPool/commons-pool2-2.0


How to implement Jedis without JedisPool/commons-pool2-2.0 because still we are using jdk 1.5(commons-pool2-2.0 does not support JDK 1.5)

How to implement a thread-safe connection pooling?


Solution

  • I'm not sure about Jedis compatibility with Java 5. You can create your own pooling based on the older commons-pool 1.6 library. You do not need to have commons-pool2 on your class path to run jedis. I used Jedis 2.7.3 and commons-pool 1.6 to validate the solution approach.

    Find the example code attached:

    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 {
    
            }
        }
    }