public class RedisUtil {
private static Logger logger = LoggerFactory.getLogger(RedisUtil.class);
private static Map<Integer, JedisPool> pools = new ConcurrentHashMap<Integer, JedisPool>();
static {
JedisPoolConfig poolConfig = initPoolConfig();
pools.put(0, new JedisPool(poolConfig, HQ_REDIS_IP, HQ_REDIS_PORT, 0, HQ_REDIS_PASSWORD, 0));
}
/**
* 初始化 JedisPoolConfig
*
* @return
*/
private static JedisPoolConfig initPoolConfig() {
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxTotal(500);
poolConfig.setMaxIdle(5);
poolConfig.setMaxWaitMillis(1000 * 100);
poolConfig.setTestOnBorrow(true);
return poolConfig;
}
/**
* 初始化连接池
*
* @param database
* @return
*/
private static JedisPool initPoolMap(int database) {
JedisPool jedisPool = null;
JedisPoolConfig poolConfig = initPoolConfig();
pools.put(database, new JedisPool(poolConfig, CommonConstants.HQ_REDIS_IP, CommonConstants.HQ_REDIS_PORT, 0, HQ_REDIS_PASSWORD, database));
jedisPool = pools.get(database);
return jedisPool;
}
/***
* 切换连接池
* @param database
* @return
*/
private static JedisPool select(int database) {
// 切换
JedisPool jedisPool = pools.get(database);
// 不存在,初始化
if (null == jedisPool) {
jedisPool = initPoolMap(database);
}
return jedisPool;
}
/***
* 返还连接池
* @param jedis
* @param database
*/
@Deprecated
private static void returnResource(Jedis jedis, int database) {
pools.get(database).returnResource(jedis);
}
@Deprecated
private static void returnBrokenResource(Jedis jedis, int database) {
pools.get(database).returnBrokenResource(jedis);
}
/***
* 关闭连接
* @param jedis
*/
private static void closeResource(Jedis jedis) {
if (jedis != null)
jedis.close();
}
/***
* 从连接池获取一个实例
* @param database
* @return
*/
public static Jedis getResource(int database) {
return select(database).getResource();
}
/**
* 获取数据
*
* @param key
* @return
*/
public static String get(String key, int market) {
String value = null;
Jedis jedis = null;
try {
jedis = getResource(market);
value = jedis.get(key);
} finally {
// 返还到连接池
closeResource(jedis);
}
return value;
}
/**
* 设置数据
*
* @param key
* @return
*/
public static void set(String key, String value, int market) {
Jedis jedis = null;
try {
jedis = getResource(market);
jedis.set(key, value);
} finally {
// 返还到连接池
closeResource(jedis);
}
}
public static void main(String[] args) {
// set("300033", "80.2", 8);
// set("300034", "70.2", 15);
// set("300035", "60.2", 8);
// set("300036", "50.2", 15);
//
// System.out.println(get("300033", 8));
// System.out.println(get("300034", 15));
// System.out.println(get("300035", 8));
// System.out.println(get("300036", 19));
}
}
redis连接相关基础工具类
最新推荐文章于 2025-12-01 11:11:40 发布
本文介绍了一个使用Java实现的Redis连接池管理类,通过JedisPoolConfig配置最大连接数、空闲连接数等参数,实现了多数据库的支持和连接资源的有效管理。

858

被折叠的 条评论
为什么被折叠?



