当前位置 : 主页 > 编程语言 > c++ >

RedisHelper助手工具类

来源:互联网 收集:自由互联 发布时间:2021-06-30
RedisHelper.java package com.isoftstone.pcis.util;import java.io.IOException;import java.io.InputStream;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.Properties;import org.apache.log4j.Logger;import r
RedisHelper.java
package com.isoftstone.pcis.util;


import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.log4j.Logger;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Pipeline;


/**
 * 
 * @author qingzhu@isoftstone.com Redis Helper 类处理Redis基本操作
 * 
 */
public class RedisHelper {
	static Logger logger = Logger.getLogger(RedisHelper.class);

	public static String getStringByKey(final String key) {
		return (String) getObjectByKey(key);
	}

	public static Object getObjectByKey(final String key) {
		Jedis jedis = null;
		try {
			jedis = RedisPool.getJedis();
			final String s = DBPREFIX + key;
			byte[] ret = jedis.get(s.getBytes());
			if (ret != null) {
				return SerializeUtils.deserialize(ret);
			} else {
				return null;
			}
		} catch (Exception e) {
			RedisPool.brokenResource(jedis);
			logger.error(e.getMessage());
		} finally {
			RedisPool.retResource(jedis);
		}
		return null;
	}

	public static boolean setObject2Redis(final String key, final String value) {
		return setObject2Redis(key, (Object) value);
	}

	public static boolean setObject2Redis(final String key, final Object value) {
		boolean flag = true;
		Jedis jedis = null;
		try {
			jedis = RedisPool.getJedis();
			byte[] val = SerializeUtils.serialize(value);
			final String s = DBPREFIX + key;
			String ret = jedis.set(s.getBytes(), val);
			flag = ret.equals(OP_REDIS_SUCCESS) ? true : false;
		} catch (Exception e) {
			flag = false;
			RedisPool.brokenResource(jedis);
			logger.error(e.getMessage());
		} finally {
			RedisPool.retResource(jedis);
		}
		return flag;
	}

	/**
	 * 
	 * @param key
	 * @param value
	 * @param nxxx not use
* NX|XX
* NX-- Only set the key if it does not already exist.
* XX-- Only set the key if it already exist.
* @param expx not use
* EX|PX
* EX = seconds; PX = milliseconds
* @param time * @return * @throws BusinessServiceException */ public static boolean setObject2Redis(final String key, final Object value, final String nxxx, final String expx, final long time) { boolean flag = true; Jedis jedis = null; try { jedis = RedisPool.getJedis(); byte[] val = SerializeUtils.serialize(value); final String s = DBPREFIX + key; /** String ret = jedis.set(s.getBytes(), val, nxxx.getBytes(), expx .getBytes(), time); **/ String ret = jedis.set(s.getBytes(),val); jedis.expire(s.getBytes(), (int) time); flag = ret.equals(OP_REDIS_SUCCESS) ? true : false; } catch (Exception e) { e.printStackTrace(); flag = false; RedisPool.brokenResource(jedis); logger.error(e.getMessage()); } finally { RedisPool.retResource(jedis); } return flag; } /** * 异步管道方式 * @param hashMap * @return */ public static boolean setObject4Pipelined(final Map hashMap){ if(hashMap==null) return false; boolean flag = true; Jedis jedis = null; try { jedis = RedisPool.getJedis(); Pipeline pipeline=jedis.pipelined(); for(Iterator iter = hashMap.keySet().iterator();iter.hasNext();){ String key = iter.next(); final String s = DBPREFIX + key; pipeline.set(s.getBytes(), SerializeUtils.serialize(hashMap.get(key))); } List results = pipeline.syncAndReturnAll(); } catch (Exception e) { flag = false; RedisPool.brokenResource(jedis); logger.error(e.getMessage()); } finally { RedisPool.retResource(jedis); } return flag; } public static boolean delObject4Pipelined(final List keys){ boolean flag = true; Jedis jedis = null; try { jedis = RedisPool.getJedis(); Pipeline pipeline = jedis.pipelined(); for(String key : keys){ final String s = DBPREFIX + key; pipeline.del(s); } List results = pipeline.syncAndReturnAll(); } catch (Exception e) { flag = false; RedisPool.brokenResource(jedis); logger.error(e.getMessage()); } finally { RedisPool.retResource(jedis); } return flag; } /** * 删除Redis Key * @param key * @return */ public static boolean delObjectByKey(final String key){ boolean flag = true; Jedis jedis = null; try { jedis = RedisPool.getJedis(); final String s = DBPREFIX + key; Long l = jedis.del(s); flag = l > 0 ? true : false; } catch (Exception e) { flag = false; RedisPool.brokenResource(jedis); logger.error(e.getMessage()); } finally { RedisPool.retResource(jedis); } return flag; } /** * flushDB * @author zhuqing * @return */ public static boolean flushRedisDB(){ boolean flag = true; Jedis jedis = null; try { jedis = RedisPool.getJedis(); jedis.flushDB(); } catch (Exception e) { flag = false; RedisPool.brokenResource(jedis); logger.error(e.getMessage()); } finally { RedisPool.retResource(jedis); } return flag; } private static String DBPREFIX = null; private static final String OP_REDIS_SUCCESS = "OK"; static{ String RESOURCENAME = "/jdbc.properties"; InputStream is = RedisHelper.class.getResourceAsStream(RESOURCENAME); Properties properties = new Properties(); try { properties.load(is); } catch (IOException e) { logger.error(e.getMessage()); } String REDIS_DBPREFIX = properties.getProperty("REDIS_DBPREFIX"); DBPREFIX = REDIS_DBPREFIX; } public static void main(String[] args) { // RedisHelper.getObjectByKey("zhuqing"); // System.out.println(DBPREFIX); // RedisHelper.setObject2Redis("king55", "kkkkk3333"); boolean flag = RedisHelper.setObject2Redis("king44","hahahahah","NX", "EX", Integer.parseInt("100000")); System.out.println(flag); } } RedisPool.java
package com.isoftstone.pcis.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.log4j.Logger;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;
import redis.clients.util.Pool;

public class RedisPool {
	static Logger logger = Logger.getLogger(RedisPool.class);
	private static Pool redisPool;
	private static String RESOURCENAME = "/jdbc.properties";
	private static RedisProp redisProp;
	/**
	 * redis 单节点
	 * @author qingzhu@isoftstone.com
	 * @return
	 */
	protected static Jedis getJedis() {
		Jedis jedis = null;
		//read redis conf
		RedisPool.readRedisPorp();
		if(redisProp.isRedisOnOff()){
			try{
				Pool pool = getJedisPool();
				jedis = (Jedis) pool.getResource();
				jedis.select(redisProp.getRedisDbIndex());
			}catch(Exception ex){
				logger.error(ex.getMessage());
				//如果连接出错redisPool 设置null 重新连接另台IP地址				
				redisPool.destroy();
				redisPool = null;
				
				//再次获取服务地址
				Pool pool = getJedisPool();
				jedis = (Jedis) pool.getResource();
				jedis.select(redisProp.getRedisDbIndex());
			}
		}
		return jedis;
	}
	/**
	 * redis 集群方式
	 * @author qingzhu@isoftstone.com
	 * @return
	 */
	@Deprecated
	private static ShardedJedis getShardedJedis() {
		ShardedJedis shardedJedis = null;
		//read redis conf
		RedisPool.readRedisPorp();
		if(redisProp.isRedisOnOff()){
			Pool pool = getShardedPool();
			shardedJedis = (ShardedJedis) pool.getResource();
			Collection
       
         collection = shardedJedis.getAllShards();
			Iterator
        
          jedis = collection.iterator(); while(jedis.hasNext()){ jedis.next().select(redisProp.getRedisDbIndex()); } } return shardedJedis; } private static void readRedisPorp(){ if(null == redisProp){ synchronized (RedisPool.class) { if(null == redisProp){ InputStream is = RedisPool.class.getResourceAsStream(RESOURCENAME); Properties properties = new Properties(); try { properties.load(is); } catch (IOException e) { logger.error(e.getMessage()); } int REDIS_MAXTOTAL = Integer.parseInt(properties.getProperty("REDIS_MAXTOTAL")); int REDIS_MINTIDLE = Integer.parseInt(properties.getProperty("REDIS_MINTIDLE")); int REDIS_MAXTIDLE = Integer.parseInt(properties.getProperty("REDIS_MAXTIDLE")); int REDIS_MAXWAITMILLIS = Integer.parseInt(properties.getProperty("REDIS_MAXWAITMILLIS")); String REDIS_IP = properties.getProperty("REDIS_IP"); String REDIS_PORT = properties.getProperty("REDIS_PORT"); int REDIS_DBINDEX = Integer.parseInt(properties.getProperty("REDIS_DBINDEX")); boolean REDIS_ON_OFF = Boolean.valueOf(properties.getProperty("REDIS_ON_OFF")); String REDIS_DBPREFIX = properties.getProperty("REDIS_DBPREFIX"); redisProp = new RedisProp(REDIS_IP, REDIS_PORT, REDIS_MAXTOTAL, REDIS_MINTIDLE , REDIS_MAXTIDLE, REDIS_MAXWAITMILLIS, REDIS_DBINDEX, REDIS_ON_OFF,REDIS_DBPREFIX); } } } } private static Pool getJedisPool(){ return getJedisPool(false); } private static Pool getShardedPool(){ return getJedisPool(true); } private static Pool getJedisPool(boolean isSharded) { if (null == redisPool) { synchronized (RedisPool.class) { if (null == redisPool) { try { if(isSharded){ redisPool = getNewShardedPool(); }else{ redisPool = getNewJedisPool(); } } catch (IOException e) { logger.error(e.getMessage()); } } } } return redisPool; } /** * 使用异常时需要销毁Jedis对象 * * @param jedis */ protected static void brokenResource(Object jedis) { if(jedis!=null){ redisPool.returnBrokenResource(jedis); } } /** * 使用完后return 到资源池中 * * @param jedis */ protected static void retResource(Object jedis) { if(jedis!=null){ redisPool.returnResource(jedis); } } /** * 单机获取方式 * @return * @throws IOException */ private static Pool getNewJedisPool() throws IOException { // 构造池 String redisIpStr = redisProp.getRedisIp(); String redisPortStr = redisProp.getRedisPort(); String [] redisIps = redisIpStr.split(";"); String [] redisPorts = redisPortStr.split(";"); //获取Master Pool pool = null; for(int index=0;index
         
           jdsInfoList =new ArrayList
          
           (); String redisIpStr = redisProp.getRedisIp(); String redisPortStr = redisProp.getRedisPort(); String [] redisIps = redisIpStr.split(";"); String [] redisPorts = redisPortStr.split(";"); for(int i=0;i
            
            
             jdbc.properties
             
            
##mysql
#jdbc.url=jdbc:mysql://localhost:3306/jfile
#jdbc.username=root
#jdbc.password=adminx
#jdbc.driverClassName=com.mysql.jdbc.Driver

MY_DATA_SOURCE_JNDI=jdbc/pcis

##oracle
jdbc.url=jdbc:oracle:thin:@10.15.22.80:1521:mytest1
jdbc.username=PCIS_TEST
jdbc.password=PCIS_TEST
jdbc.driverClassName=oracle.jdbc.driver.OracleDriver





#redis
#########redis server ON OFF####################
REDIS_ON_OFF=on
#########redis server ip ads####################
REDIS_IP=10.15.22.120;10.15.22.121
#########redis server port #####################
REDIS_PORT=6379;6379
#########max wait millis ms 5*1000##############
REDIS_MAXWAITMILLIS=5000
#########redis server port #####################
REDIS_MAXTOTAL=1000
#########redis server port #####################
REDIS_MINTIDLE=8
REDIS_MAXTIDLE=100
######### redis db index 0-16 ##################
REDIS_DBINDEX=1
######### redis db prefix ##################
REDIS_DBPREFIX=ZFMI_
网友评论