封装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;
}
}