美文网首页
Jedis系列:Jedis多线程访问

Jedis系列:Jedis多线程访问

作者: seawish | 来源:发表于2018-12-05 15:46 被阅读14次

    正文

    jedisPool.getResource()方法无法在普通多线程中使用,可能触发whenExhaustedAction:

    whenExhaustedAction: 当“连接池”中active数量达到阀值时,即connection资源耗尽时,连接池需要采取的手段, 默认为1:
    -> 0 : 抛出异常,
    -> 1 : 阻塞,直到有可用链接资源
    -> 2 : 强制创建新的链接资源

    // 普通多线程模式
    // 该方法无法运行
    Thread thread = new Thread(null, null, "thread" + j) {
                    public void run() {
                        System.out.println(this.getName());
                        Jedis jedis = jedisPool.getResource();    // 在whenExhaustedAction=1时,线程运行到这一步可能block
                        System.out.println(jedis);
                    }
    
    

    使用ExecutorService可以解决jedisconnection资源耗尽问题。该方式需要将ExecutorService与jedisPool结合,以进行多线程下的jedis访问。

    // 正确使用方法
    import java.util.concurrent.CountDownLatch;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    
    import redis.clients.jedis.Jedis;
    import redis.clients.jedis.JedisPool;
    
    public class JedisPoolTest {
    
        private static final ExecutorService pool = Executors.newCachedThreadPool();
    
        private static final CountDownLatch latch = new CountDownLatch(20);
    
        private static final JedisPool jPool = new JedisPool();
    
        public static void main(String[] args) {
            long start = System.currentTimeMillis();
            for(int i=0;i<20;i++){
                pool.execute(new RedisTest());
            }
            try {
                latch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(System.currentTimeMillis() - start);
            pool.shutdownNow();
    
        }
    
        static class RedisTest implements Runnable{
    
            @Override
            public void run() {
                Jedis jedis = jPool.getResource();
                int i = 10000;
                try{
                    while(i-->0){
                            jedis.set("hello", "world");
                    }
                }finally{
                    jedis.close();
                    latch.countDown();
                }
            }
    
        }
    
    }
    

    参考文献


    本文作者: seawish
    版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 3.0 许可协议。转载请注明出处!

    相关文章

      网友评论

          本文标题:Jedis系列:Jedis多线程访问

          本文链接:https://www.haomeiwen.com/subject/kjqwcqtx.html