Redis连接池工具类

3 篇文章 0 订阅

Redis连接池工具类

package com.actionsoft.apps.wide.redis.utils;

import java.util.concurrent.locks.ReentrantLock;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * Redis 连接池工具类
 * @author caspar
 * 
 */
public class JedisPoolUtils {

	protected static ReentrantLock lockPool = new ReentrantLock();
	protected static ReentrantLock lockJedis = new ReentrantLock();

	private static PropertiesConfig config = new PropertiesConfig();
	
	// Redis服务器IP
	//private static String ADDR_ARRAY = "127.0.0.1";
	private static String ADDR_ARRAY = config.getPropertyValue("server");

	// Redis的端口号
	// private static int PORT = 6379;
	private static int PORT = config.getPropertyValueInt("port");

	// 访问密码
	// private static String AUTH = FileUtil.getPropertyValue("/properties/redis.properties", "auth");

	// 可用连接实例的最大数目,默认值为8;
	// 如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
	// private static int MAX_ACTIVE = 1200;
	private static int MAX_ACTIVE = config.getPropertyValueInt("max_active");

	// 控制一个pool最多有多少个状态为idle(空闲的)的jedis实例,默认值也是8。
	// private static int MAX_IDLE = 400;
	private static int MAX_IDLE = config.getPropertyValueInt("max_idle");

	// 等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出JedisConnectionException;
	// private static int MAX_WAIT = 10000;
	private static int MAX_WAIT = config.getPropertyValueInt("max_wait");

	// 超时时间
	// private static int TIMEOUT = 10000;
	private static int TIMEOUT = config.getPropertyValueInt("timeout");

	// 在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;
	// private static boolean TEST_ON_BORROW = true;
	private static boolean TEST_ON_BORROW = config.getPropertyValueBoolean("test_on_borrow");

	private static JedisPool jedisPool = null;

	/**
	 * redis过期时间,以秒为单位
	 */
	public final static int EXRP_HOUR = 60 * 60; // 一小时
	public final static int EXRP_DAY = 60 * 60 * 24; // 一天
	public final static int EXRP_MONTH = 60 * 60 * 24 * 30; // 一个月

	/**
	 * 初始化Redis连接池
	 */
	private static void initialPool() {
		try {
			JedisPoolConfig config = new JedisPoolConfig();
			config.setMaxTotal(MAX_ACTIVE);
			config.setMaxIdle(MAX_IDLE);
			config.setMaxWaitMillis(MAX_WAIT);
			config.setTestOnBorrow(TEST_ON_BORROW);
			jedisPool = new JedisPool(config, ADDR_ARRAY, PORT, TIMEOUT, "123456");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 在多线程环境同步初始化
	 */
	private static void poolInit() {
		// 断言 ,当前锁是否已经锁住,如果锁住了,就啥也不干,没锁的话就执行下面步骤
		assert !lockPool.isHeldByCurrentThread();
		lockPool.lock();
		try {
			if (jedisPool == null) {
				initialPool();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lockPool.unlock();
		}
	}

	public static Jedis getJedis() {
		// 断言 ,当前锁是否已经锁住,如果锁住了,就啥也不干,没锁的话就执行下面步骤
		assert !lockJedis.isHeldByCurrentThread();
		lockJedis.lock();

		if (jedisPool == null) {
			poolInit();
		}
		Jedis jedis = null;
		try {
			if (jedisPool != null) {
				jedis = jedisPool.getResource();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			returnResource(jedis);
			lockJedis.unlock();
		}
		return jedis;
	}

	/**
	 * 释放jedis资源
	 * 
	 * @param jedis
	 */
	public static void returnResource(final Jedis jedis) {
		if (jedis != null && jedisPool != null) {
			closeJedis(jedis);
		}
	}

	/**
	 * 设置 String
	 * 
	 * @param key
	 * @param value
	 */
	public synchronized static void setString(String key, String value) {
		try {
			value = StringUtil.isEmpty(value) ? "" : value;
			getJedis().set(key, value);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 设置 过期时间
	 * 
	 * @param key
	 * @param seconds
	 *            以秒为单位
	 * @param value
	 */
	public synchronized static void setString(String key, int seconds, String value) {
		try {
			value = StringUtil.isEmpty(value) ? "" : value;
			getJedis().setex(key, seconds, value);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 关闭 jedis
	public static void closeJedis(Jedis jedis) {
		try {
			if (jedis != null) {
				if (jedis != null) {
					jedis.close();
				}
			}
		} catch (Exception e) {
			closeBrokenResource(jedis);
		}
	}

	/**
	 * Return jedis connection to the pool, call different return methods
	 * depends on whether the connection is broken
	 */
	public static void closeBrokenResource(Jedis jedis) {
		try {
			jedisPool.returnBrokenResource(jedis);
		} catch (Exception e) {
			destroyJedis(jedis);
		}
	}

	/**
	 * 在 Jedis Pool 以外强行销毁 Jedis
	 */
	public static void destroyJedis(Jedis jedis) {
		if (jedis != null) {
			try {
				jedis.quit();
			} catch (Exception e) {
				e.printStackTrace();
			}
			try {
				jedis.disconnect();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 获取String值
	 * 
	 * @param key
	 * @return value
	 */
	public synchronized static String getString(String key) {
		if (getJedis() == null || !getJedis().exists(key)) {
			return null;
		}
		return getJedis().get(key);
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

喵叻嗰咪

如果有用,请作者喝杯咖啡吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值