package com.fr.plugin.db.redis.core; import com.fr.stable.StringUtils; import com.fr.third.redis.clients.jedis.Jedis; import com.fr.third.redis.clients.jedis.JedisPool; import com.fr.third.redis.clients.jedis.JedisPoolConfig; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * @author richie * @version 10.0 * Created by richie on 2019-03-18 */ public class RedisPool { private static final int TIME_OUT = 100 * 1000; private static RedisPool pool = new RedisPool(); public static RedisPool getPool() { return pool; } private Map jedisPoolMap = new ConcurrentHashMap(); public Jedis getResource(String host, int port, String password, int maxTotal, int maxWait) { JedisPool jedisPool = jedisPoolMap.get(host); if (jedisPool == null) { jedisPool = createJedisPool(host, port, password, maxTotal, maxWait); jedisPoolMap.put(host, jedisPool); } return jedisPool.getResource(); } private JedisPool createJedisPool(String host, int port, String password, int maxTotal, int maxWait) { JedisPoolConfig config = new JedisPoolConfig(); config.setMaxTotal(maxTotal); //连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true config.setBlockWhenExhausted(true); //设置的逐出策略类名, 默认DefaultEvictionPolicy(当连接超过最大空闲时间,或连接数超过最大空闲连接数) config.setEvictionPolicyClassName("com.fr.third.org.apache.commons.pool2.impl.DefaultEvictionPolicy"); //是否启用pool的jmx管理功能, 默认true config.setJmxEnabled(true); //MBean ObjectName = new ObjectName("org.apache.commons.pool2:type=GenericObjectPool,name=" + "pool" + i); 默认为"pool", JMX不熟,具体不知道是干啥的...默认就好. config.setJmxNamePrefix("pool"); //是否启用后进先出, 默认true config.setLifo(true); //最大空闲连接数 config.setMaxIdle(10); //最大连接数,可配置 //获取连接时的最大等待毫秒数(如果设置为阻塞时BlockWhenExhausted),如果超时就抛异常, 小于零:阻塞不确定的时间, 默认-1 config.setMaxWaitMillis(maxWait); //逐出连接的最小空闲时间 默认1800000毫秒(30分钟) config.setMinEvictableIdleTimeMillis(1800000); //最小空闲连接数, 默认0 config.setMinIdle(0); //每次逐出检查时 逐出的最大数目 如果为负数就是 : 1/abs(n), 默认3 config.setNumTestsPerEvictionRun(3); //对象空闲多久后逐出, 当空闲时间>该值 且 空闲连接>最大空闲数 时直接逐出,不再根据MinEvictableIdleTimeMillis判断 (默认逐出策略) config.setSoftMinEvictableIdleTimeMillis(1800000); //在获取连接的时候检查有效性, 默认false config.setTestOnBorrow(false); //在空闲时检查有效性, 默认false config.setTestWhileIdle(false); //逐出扫描的时间间隔(毫秒) 如果为负数,则不运行逐出线程, 默认-1 config.setTimeBetweenEvictionRunsMillis(-1); if (StringUtils.isNotBlank(password)) { return new JedisPool(config, host, port, TIME_OUT, password); } else { return new JedisPool(config, host, port, TIME_OUT); } } }