redis 工具类

原创
2017/12/07 10:27
阅读数 115

redis 工具类:


import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import redis.clients.jedis.*;

import java.util.Set;

/**
 * 
 * 
 * @desc 操作redis 的client
 * @author Wallker.Gao
 * @date 2017年3月23日下午8:06:37
 * 
 */
@Service
public class RedisManager {

	Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private JedisCluster jedisCluster;

	/** 过期时间,0=不过期 单位s **/
	private Integer expire = 1800;

	/**
	 * 根据String key获取数据
	 * 
	 * @param key
	 * @return
	 */
	public String get(String key) {
		String value = null;
		try {
			value = jedisCluster.get(key);
		} catch (Exception e) {
			logger.error("获取缓存出错", e);
		}
		return value;
	}

	public void set(String key, String value) {
		try {
			String status = jedisCluster.set(key, value);
			if (this.expire != 0) {
				jedisCluster.expire(key, this.expire);
			}
			logger.info("jedis set status = {}", status);
		} catch (Exception e) {
			logger.error("保存缓存出错", e);
		}
	}

	/**
	 * 跟进key ,value ,expire(单位s)过期时间存储,value最大1G
	 * 
	 * @param key
	 * @param value
	 * @param expire
	 */
	public void set(String key, String value, int expire) {
		try {
			String status = jedisCluster.set(key, value);
			if (expire != 0) {
				jedisCluster.expire(key, expire);
			}
			logger.info("jedis set status = {}", status);
		} catch (Exception e) {
			logger.error("保存缓存出错", e);
		}
	}

	/**
	 * @param key
	 * @param value
	 * @return 返回true存储成功,否则失败
	 */
	public boolean setnx(String key, String value) {
		try {
			// 返回1存储成功 返回0存储失败
			Long status = jedisCluster.setnx(key, value);
			if (this.expire != 0) {
				jedisCluster.expire(key, this.expire);
			}
			logger.info("jedis set status = {}", status);
			return status == 1 ? true : false;
		} catch (Exception e) {
			logger.error("保存缓存出错", e);
			return false;
		}
	}

	/**
	 * 跟进key ,value ,expire(单位s)过期时间存储,value最大1G
	 * 
	 * @param key
	 * @param value
	 * @param expire
	 *            返回true存储成功,否则失败
	 */
	public boolean setnx(String key, String value, int expire) {
		try {
			Long status = jedisCluster.setnx(key, value);
			if (expire != 0) {
				jedisCluster.expire(key, expire);
			}
			return status == 1 ? true : false;
		} catch (Exception e) {
			logger.error("保存缓存出错", e);
			return false;
		}
	}

	/**
	 * 获取过期时间(单位s)
	 * 
	 * @param key
	 */
	public Long ttl(String key) {
		Long expire = 0L;
		try {
			expire = jedisCluster.ttl(key);
		} catch (Exception e) {
			logger.error("获取过期时间出错", e);
		} finally {
			// jedisCluster.close();
		}
		return expire;
	}

	public void del(String key) {
		try {
			Long l = jedisCluster.del(key);
			logger.info("jedisCluster del number = {}", l);
		} catch (Exception e) {
			logger.error("删除缓存出错", e);
		} finally {
			// jedisCluster.close();
		}
	}

	/**
	 * 获取所有的keys
	 * 
	 * @param pattern
	 * @return
	 */
	public Set<String> keys(String pattern) {
		Set<String> set = null;
		try {
			set = jedisCluster.hkeys(pattern);
		} catch (Exception e) {
			logger.error("通过表达式获取keys出错", e);
		} finally {
			// jedisCluster.close();
		}
		return set;
	}

	/**
	 * 当前key 是否存在
	 * 
	 * @param key
	 * @return
	 */
	public boolean exists(String key) {
		Boolean exists = null;
		try {
			exists = jedisCluster.exists(key);
		} catch (Exception e) {
			logger.error("", e);
		}
		return exists;
	}

	public String incrId(String key) {
		Long value = null;
		try {
			value = jedisCluster.incr(key);
		} catch (Exception e) {
			logger.error("error in incrId method", e);
		}
		return value + "";
	}

	/**
	 * @param key
	 * @param timeOut
	 * @param max
	 * @param incrNum
	 * @return
	 */
	public boolean maxLimit(String key, Integer timeOut, int max, int incrNum) {
		boolean bo = false;
		Long currentNum = 0L;
		try {
			// Long pttl = jedisCluster.pttl(key);
			Long pttl = jedisCluster.ttl(key);
			if (pttl > 0) {
				currentNum = jedisCluster.incrBy(key, incrNum);
				logger.info("****** Key = {" + key + "} ********* value = " + currentNum + " ******");
				if (currentNum <= max) {
					bo = true;
				}
			} else if (pttl == -1 || pttl == -2 || pttl == 0) {
				// Transaction tx = jedisCluster.multi();
				// Response<Long> rsp = tx.incrBy(key, incrNum);
				// tx.expire(key, timeOut);
				// tx.exec();
				// currentNum = rsp.get();
				if (currentNum <= max) {
					bo = true;
				}
			}
		} catch (Exception ex) {
			logger.error("maxLimit :******Exception******", ex);
		}
		return bo;
	}

	/*** 判断是否需要预警 ****/
	public boolean isNeedWarn(String payKey, boolean nowBool, Long warnSize) {
		if (nowBool) {
			jedisCluster.set(payKey, "0");
			return false;
		}
		Long nowSize = jedisCluster.incr(payKey);
		if (nowSize >= warnSize) {
			jedisCluster.set(payKey, "0");
			return true;
		}
		return false;

	}

	/**
	 * @Title: allow @Description: 进行流量控制,允许访问返回true 不允许访问返回false
	 * @param: @param
	 *             key 放入redis的key
	 * @param: @param
	 *             timeOut 超时时间单位秒
	 * @param: @param
	 *             flowSize 超时时间内允许访问的次数
	 * @param: @return
	 * @param: @throws
	 *             Exception @return: boolean @throws
	 */
	public boolean flow(String key, Integer timeOut, Integer flowSize) {
		boolean bo = false;
		Long flowNum = 0L;
		try {
			Long pttl = jedisCluster.ttl(key);
			if (pttl > 0) {
				String flowNow = jedisCluster.get(key);
				if (StringUtils.isNotEmpty(flowNow)) {
					flowNum = Long.parseLong(flowNow);
				}
				logger.info("==========[flow]===flow flowSize :" + flowSize);
				logger.info("==========[flow]===flow flowNum :" + flowNum);
				if (flowNum < flowSize) {
					bo = true;
				}
			} else if (pttl == -1 || pttl == -2 || pttl == 0) {
				/*
				 * Transaction tx = jedisCluster.multi(); Response<Long> rsp =
				 * tx.incr(key); tx.expire(key, timeOut); tx.exec(); flowNum =
				 * rsp.get();
				 */

				/** TODO begin 集群中,没有事务,可能会存在隐患 **/
				flowNum = jedisCluster.incr(key);
				jedisCluster.expire(key, timeOut);
				// TODO end

				if (flowNum < flowSize) {
					bo = true;
				}
			}
		} catch (Exception ex) {
			logger.error("========Exception===", ex);
		}
		return bo;
	}

}

 

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部