RedisClusterManagerUtil 工具类

RedisClusterManagerUtil 工具类

import java.io.IOException;
import java.io.PrintStream;
import java.io.Serializable;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;
import org.apache.commons.lang.SerializationUtils;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.apache.log4j.Logger;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;

public class RedisClusterManager {
	private final Logger _LOG = Logger.getLogger(RedisClusterManager.class);

	protected int DEFAULT_EXPIRED_TIME_SECONDS_OBJECT = 1296000;

	private static final RedisClusterManager _INSTANCE = new RedisClusterManager();

	private JedisCluster oCluster = null;

	private RedisClusterManager() {
		_init();
	}

	private void _init() {
		Set jedisClusterNodes = new HashSet();

		ResourceBundle oResBundle = null;
		try {
			oResBundle = ResourceBundle.getBundle("redis", Locale.CHINESE);
		} catch (Exception e) {
			this._LOG.warn("failed to load redis.properties : " + e.getMessage());
			return;
		}

		if (oResBundle == null) {
			return;
		}
		String sRedisCluster = null;
		String[] arrHostAndPort = null;
		if (oResBundle.containsKey("REDIS.CLUSTER")) {
			sRedisCluster = oResBundle.getString("REDIS.CLUSTER");
			if (!(StringUtil.isNullOrBlanks(sRedisCluster))) {
				arrHostAndPort = sRedisCluster.split("[\\s+\\;\\,]");
			}
		}
		if ((arrHostAndPort == null) || (arrHostAndPort.length <= 0)) {
			this._LOG.error("redis cluster host and port list must be specified.");
			return;
		}

		int iTempPort = 6379;
		String sTempHost = null;
		CallResult oIntResult = null;
		for (String item : arrHostAndPort) {
			if (!(StringUtil.isNullOrBlanks(item))) {
				String[] arrTemp = item.split("\\:");

				iTempPort = 6379;

				if (arrTemp.length > 0) {
					sTempHost = arrTemp[0];
				}

				if (arrTemp.length > 1) {
					oIntResult = StringUtil.str2int(arrTemp[1]);
					if (oIntResult.isSuccessful()) {
						iTempPort = ((Integer) oIntResult.getReturnedObject()).intValue();
					}
				}

				jedisClusterNodes.add(new HostAndPort(sTempHost, iTempPort));
			}
		}

		GenericObjectPoolConfig oConfig = new GenericObjectPoolConfig();

		oConfig.setMaxTotal(20);
		if (oResBundle.containsKey("REDIS.CONN.TOTAL")) {
			oIntResult = StringUtil.str2int(oResBundle.getString("REDIS.CONN.TOTAL"));
			if (oIntResult.isSuccessful()) {
				oConfig.setMaxTotal(((Integer) oIntResult.getReturnedObject()).intValue());
			}

		}

		oConfig.setMaxIdle(2);
		if (oResBundle.containsKey("REDIS.CONN.IDLE.MAX")) {
			oIntResult = StringUtil.str2int(oResBundle.getString("REDIS.CONN.IDLE.MAX"));
			if (oIntResult.isSuccessful()) {
				oConfig.setMaxIdle(((Integer) oIntResult.getReturnedObject()).intValue());
			}
		}

		oConfig.setTestWhileIdle(true);
		oConfig.setTestOnBorrow(true);
		oConfig.setTestOnReturn(false);

		if (oResBundle.containsKey("REDIS.DEFAULT.EXPIRE.SECONDS")) {
			oIntResult = StringUtil.str2int(oResBundle.getString("REDIS.DEFAULT.EXPIRE.SECONDS"));
			if (oIntResult.isSuccessful()) {
				this.DEFAULT_EXPIRED_TIME_SECONDS_OBJECT = ((Integer) oIntResult.getReturnedObject()).intValue();
			}

		}

		if (this.oCluster != null) {
			try {
				this.oCluster.close();
			} catch (IOException localIOException1) {
			}
			this._LOG.info("existed redis pool has been shutdown.");
		}

		this.oCluster = new JedisCluster(jedisClusterNodes, oConfig);
		this._LOG.info(String.format("redis cluster client is created on %s", new Object[]{sRedisCluster}));
	}

	public static final RedisClusterManager getInstance() {
		return _INSTANCE;
	}

	public boolean putString(String sKey, String sValue, int expiredInSeconds) {
		boolean result = false;

		if (StringUtil.isNullOrBlanks(sKey)) {
			return result;
		}

		if (this.oCluster != null) {
			this.oCluster.set(sKey, sValue);
			if (expiredInSeconds > 0) {
				this.oCluster.expire(sKey, expiredInSeconds);
			}

			result = true;
		}

		return result;
	}

	public boolean putString(String sKey, String sValue) {
		return putString(sKey, sValue, this.DEFAULT_EXPIRED_TIME_SECONDS_OBJECT);
	}

	public String getString(String sKey) {
		String result = null;
		if (StringUtil.isNullOrBlanks(sKey)) {
			return result;
		}

		if (this.oCluster != null) {
			result = this.oCluster.get(sKey);
		}

		return result;
	}

	public boolean putObject(String sKey, Serializable object, int expiredInSeconds) {
		boolean result = false;

		if (StringUtil.isNullOrBlanks(sKey)) {
			return result;
		}

		if (this.oCluster != null) {
			byte[] datas = SerializationUtils.serialize(object);
			byte[] arrKey = sKey.getBytes();

			this.oCluster.set(arrKey, datas);
			if (expiredInSeconds > 0) {
				this.oCluster.expire(arrKey, expiredInSeconds);
			}

			result = true;
		}

		return result;
	}

	public boolean putObject(String sKey, Serializable object) {
		return putObject(sKey, object, this.DEFAULT_EXPIRED_TIME_SECONDS_OBJECT);
	}

	public  T getObject(String sKey, Class oclass) {
		Object result = null;
		if (StringUtil.isNullOrBlanks(sKey)) {
			return result;
		}

		if (this.oCluster != null) {
			byte[] arrKey = sKey.getBytes();

			byte[] datas = this.oCluster.get(arrKey);

			if ((datas != null) && (datas.length > 0)) {
				result = SerializationUtils.deserialize(datas);
			}
		}

		return result;
	}

	public boolean putMap(String sKey, Map oMap, int expiredInSeconds) {
		boolean result = false;

		if ((StringUtil.isNullOrBlanks(sKey)) || (oMap == null) || (oMap.size() <= 0)) {
			return result;
		}

		if (this.oCluster != null) {
			this.oCluster.hmset(sKey, oMap);
			if (expiredInSeconds > 0) {
				this.oCluster.expire(sKey, expiredInSeconds);
			}

			result = true;
		}

		return result;
	}

	public boolean putMap(String sKey, Map oMap) {
		return putMap(sKey, oMap, this.DEFAULT_EXPIRED_TIME_SECONDS_OBJECT);
	}

	public boolean putMap(String sKey, String sField, String sValue, int expiredInSeconds) {
		boolean result = false;

		if ((StringUtil.isNullOrBlanks(sKey)) || (StringUtil.isNullOrBlanks(sField))) {
			return result;
		}

		if (this.oCluster != null) {
			this.oCluster.hset(sKey, sField, sValue);
			if (expiredInSeconds > 0) {
				this.oCluster.expire(sKey, expiredInSeconds);
			}

			result = true;
		}

		return result;
	}

	public boolean putMap(String sKey, String sField, String sValue) {
		return putMap(sKey, sField, sValue, this.DEFAULT_EXPIRED_TIME_SECONDS_OBJECT);
	}

	public Map getMap(String sKey) {
		Map result = null;
		if (StringUtil.isNullOrBlanks(sKey)) {
			return result;
		}

		if (this.oCluster != null) {
			result = this.oCluster.hgetAll(sKey);
		}

		return result;
	}

	public Map getMap(String sKey, String[] fields) {
		Map result = null;

		Map mapAll = getMap(sKey);
		if ((mapAll != null) && (mapAll.size() > 0) && (fields != null) && (fields.length > 0)) {
			result = new LinkedHashMap();
			for (String field : fields) {
				result.put(field, mapAll.get(field));
			}

		}

		return result;
	}

	public boolean existsMapItem(String sKey, String sField) {
		if ((StringUtil.isNullOrBlanks(sKey)) || (StringUtil.isNullOrBlanks(sField))) {
			return false;
		}

		if (this.oCluster != null) {
			return this.oCluster.hexists(sKey, sField).booleanValue();
		}

		return false;
	}

	public boolean putMapValueAsObject(String sKey, String sField, Serializable oValue, int expiredInSeconds) {
		boolean result = false;

		if ((StringUtil.isNullOrBlanks(sKey)) || (StringUtil.isNullOrBlanks(sField))) {
			return result;
		}

		if (this.oCluster != null) {
			byte[] arrKey = sKey.getBytes();

			this.oCluster.hset(arrKey, sField.getBytes(), SerializationUtils.serialize(oValue));
			if (expiredInSeconds > 0) {
				this.oCluster.expire(arrKey, expiredInSeconds);
			}

			result = true;
		}

		return result;
	}

	public boolean putMapValueAsObject(String sKey, String sField, Serializable oValue) {
		return putMapValueAsObject(sKey, sField, oValue, this.DEFAULT_EXPIRED_TIME_SECONDS_OBJECT);
	}

	public  T getMapValueAsObject(String sKey, String sField, Class oClass) {
		Object result = null;

		if ((StringUtil.isNullOrBlanks(sKey)) || (StringUtil.isNullOrBlanks(sField))) {
			return result;
		}

		if (this.oCluster != null) {
			byte[] datas = this.oCluster.hget(sKey.getBytes(), sField.getBytes());
			if ((datas != null) && (datas.length > 0)) {
				Object tmpObject = SerializationUtils.deserialize(datas);
				result = tmpObject;
			}
		}

		return result;
	}

	public void remove(String sKey) {
		if (StringUtil.isNullOrBlanks(sKey)) {
			return;
		}

		if (this.oCluster != null)
			this.oCluster.del(sKey);
	}

	public void close() {
		if (this.oCluster == null)
			return;
		try {
			this.oCluster.close();
		} catch (IOException localIOException) {
		}
	}

	public void restart() {
		_init();
	}

	public static void main(String[] args) {
		RedisClusterManager _MGR = getInstance();
		_MGR.putString("keya1", "wer", 3600);
		System.out.println(_MGR.getString("keya1"));
	}
}


你可能感兴趣的:(数据库)