Jedis连接池和线程池

封装RedisUtil通过连接池获取连接对象

因为不涉及到高并发因此不用加锁

//封装jedis连接池
class RedisUtil_1{
    private static JedisPool jedisPool;
    private static Jedis jedis;
    public static Jedis getJedis(){
        if (jedisPool == null) {
            JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
            jedisPoolConfig.setMaxTotal(50);//最大连接数
            jedisPoolConfig.setMaxIdle(10);//最大闲置连接数
            jedisPoolConfig.setMinIdle(10);//最小闲置连接数
            jedisPoolConfig.setTestOnBorrow(true);//测试一下连接对象
            jedisPoolConfig.setMaxWaitMillis(10*1000L);//最大等待时间
            jedisPoolConfig.setBlockWhenExhausted(true);//当繁忙的时候阻塞住等待
//            创建连接池对象  连接池配置            主机名        Redis端口号     超时时间
             jedisPool = new JedisPool(jedisPoolConfig, "hadoop106", 6379, 1000);
        }
        if (jedis == null) {
            jedis = jedisPool.getResource();
        }
        return jedis;
    }
}

通过线程池开启多线程工具类

使用双重校验锁保证线程池对象的单例

public class ThreadPoolUtil {
    public static ThreadPoolExecutor threadPool;
//    TODO 通过单例的方式获得线程池 考虑多并发
    public static ThreadPoolExecutor getThreadPool(){
        if (threadPool == null) {//防止加锁的开销
            synchronized (ThreadPoolUtil.class){
                if (threadPool == null) {//防止线程1释放锁线程2进入代码块内创建两个线程池对象
                    System.out.println("创建单例线程池对象!");
                    threadPool = new ThreadPoolExecutor(4, 20,
                            200, TimeUnit.SECONDS,
                            new LinkedBlockingDeque<Runnable>(Integer.MAX_VALUE));
                }
            }
        }
        return threadPool;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值