All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.wicp.tams.common.redis.pool.JedisPoolTams Maven / Gradle / Ivy

The newest version!
/*
 * **********************************************************************
 * Copyright (c) 2022 .
 * All rights reserved.
 * 项目名称:common
 * 项目描述:公共的工具集
 * 版权说明:本软件属andy.zhou([email protected])所有。
 * ***********************************************************************
 */
package net.wicp.tams.common.redis.pool;

import java.util.Map;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

import net.wicp.tams.common.Conf;
import net.wicp.tams.common.exception.ExceptAll;
import net.wicp.tams.common.exception.ProjectExceptionRuntime;
import net.wicp.tams.common.redis.RedisAssit;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.exceptions.JedisConnectionException;

public class JedisPoolTams extends AbsPool {
	private volatile JedisPool jedisPool;

	private final String serverName;

	public JedisPoolTams() {
		this.serverName = "default";
	}

	public JedisPoolTams(String serverName, final GenericObjectPoolConfig poolConfig, final String host,
			final int port, final int timeout) {
		this.serverName = serverName;
		poolConfig.setJmxEnabled(true);
		poolConfig.setJmxNamePrefix("jedis-pool");
		Map data = Conf
				.getAllConfigValues(String.format("%s.%s", "common.redis.redisserver", serverName), true);
		JedisPool jedisPool = new JedisPool(poolConfig, host, port, timeout, data.get("password"),
				RedisAssit.getConfigInt(data, "defaultDb"), data.get("clientName"));
		setJedisPool(jedisPool);
	}

	public void setJedisPool(JedisPool jedisPool) {
		if (jedisPool == null) {
			throw new ProjectExceptionRuntime(ExceptAll.ssh_pool_conn, "jedisPool池不允许为空值");
		}
		doLeak(this.serverName, jedisPool);
		this.jedisPool = jedisPool;
	}

	@Override
	public Jedis getResource() {
		if (this.jedisPool == null) {
			throw new ProjectExceptionRuntime(ExceptAll.ssh_pool_conn, "jedisPool为空,请检查相关配置是否有问题,不能连接到redis");
		}
		Jedis ret = null;
		try {
			ret = this.jedisPool.getResource();
		} catch (JedisConnectionException e) {
			if (this.jedisPool != null && ret != null) {
				this.jedisPool.returnBrokenResource(ret);
			}
		}
		return ret;
	}

	@Override
	public void destroy() {
		this.jedisPool.destroy();
		this.jedisPool = null;
	}

	@Override
	public boolean isInit() {
		return this.jedisPool != null;
	}

	@Override
	public void returnResource(Jedis jedis) {
		if (this.jedisPool != null) {
			this.jedisPool.returnResource(jedis);
		}
	}

	@Override
	public void returnBrokenResource(Jedis jedis) {
		if (this.jedisPool != null) {
			this.jedisPool.returnBrokenResource(jedis);
		}
	}

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy