【问题标题】:Jedis Cache implementation without JedisPool/commons-pool2-2.0没有 JedisPool/commons-pool2-2.0 的 Jedis Cache 实现
【发布时间】:2015-07-23 17:32:54
【问题描述】:

如何在没有 JedisPool/commons-pool2-2.0 的情况下实现 Jedis,因为我们仍在使用 jdk 1.5(commons-pool2-2.0 不支持 JDK 1.5)

如何实现线程安全的连接池?

【问题讨论】:

    标签: connection connection-pooling jedis java-5


    【解决方案1】:

    我不确定 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 {
    
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-03
      • 2018-12-10
      • 1970-01-01
      相关资源
      最近更新 更多