redis集群使用Java工具类(Java jedis集群工具类)
package com.xiaomi.weather.vote.webservices.util.redisCache; import com.google.common.base.Strings;
import org.apache.log4j.Logger;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig; import java.io.InputStream;
import java.util.*; /**
* Created by mi on 16-12-22.
*/
public class RedisClusterClient {
private static final Logger logger = Logger.getLogger(RedisClusterClient.class);
private static String isOn = "true"; // 是否启用缓存
private static JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); // 配置信息
public JedisCluster jedisCluster = null;
Set<HostAndPort> jedisClusterNodes = new HashSet<HostAndPort>(); public static RedisClusterClient redisClusterClient = new RedisClusterClient(); public RedisClusterClient() {
init();
} public static RedisClusterClient getInsance() {
if (redisClusterClient != null) {
return redisClusterClient;
} else {
redisClusterClient = new RedisClusterClient();
return redisClusterClient;
}
} public boolean init() {
try {
// 读取配置文件
InputStream path = RedisClusterClient.class.getClassLoader().getResourceAsStream("cache.properties");
Properties pros = new Properties();
pros.load(path);
this.isOn = pros.getProperty("redis.onoff", "true");// 默认开启缓存
if (this.isOn.equals("false")) {// 未开启缓存
return false;
} //
String servers = pros.getProperty("redisMultiCluster.clusters", null);
if (Strings.isNullOrEmpty(servers)) {
logger.error("RedisJavaClient.servers 配置错误; in file:cache.properties");
this.isOn = "false";
return false;
}
String[] hostAndPorts = servers.split("\\|");
for (int i = 0; i < hostAndPorts.length; i++) {
String hostAndPort = hostAndPorts[i];
if (!hostAndPort.contains(":")) {
return false;
}
jedisClusterNodes.add(new HostAndPort(hostAndPort.split(":")[0], Integer.parseInt(hostAndPort.split(":")[1])));
}
try {
jedisPoolConfig.setMaxTotal(Integer.parseInt(pros.getProperty("redisMultiCluster.maxTotal", "8")));
jedisPoolConfig.setMaxIdle(Integer.parseInt(pros.getProperty("redisMultiCluster.maxIdle", "8")));
jedisPoolConfig.setMinIdle(Integer.parseInt(pros.getProperty("redisMultiCluster.minIdle", "0")));
jedisPoolConfig
.setBlockWhenExhausted(Boolean.parseBoolean(pros.getProperty("redisMultiCluster.blockWhenExhausted", "true")));
jedisPoolConfig.setMaxWaitMillis(Integer.parseInt(pros.getProperty("redisMultiCluster.maxWaitMillis", "true")));
jedisPoolConfig.setTestOnBorrow(Boolean.parseBoolean(pros.getProperty("redisMultiCluster.testOnBorrow", "true")));
jedisPoolConfig.setTestOnCreate(Boolean.parseBoolean(pros.getProperty("redisMultiCluster.testOnCreate", "true")));
jedisPoolConfig.setTestOnReturn(Boolean.parseBoolean(pros.getProperty("redisMultiCluster.testOnReturn", "true")));
jedisPoolConfig.setTestWhileIdle(Boolean.parseBoolean(pros.getProperty("redisMultiCluster.testWhileIdle", "false"))); } catch (Exception e) {
logger.error("{未知异常}", e);
}
jedisCluster = new JedisCluster(jedisClusterNodes, jedisPoolConfig);
logger.info("缓存初始化成功");
path.close();
return true;
} catch (Exception e) {
logger.error("{缓存初始化错误}", e);
this.isOn = "false";
}
return false;
} public boolean setnx(String key, String value, int expireTime) {
if (!isOn.equals("true")) {
logger.info("缓存未开启");
return false;
}
try {
Long setSuccess = jedisCluster.setnx(key, value);
if (setSuccess == 1) {
if (1 == jedisCluster.expire(key, expireTime)) {
return true;
} else {
this.deleteKey(key);
return false;
}
} else {
return false;
}
} catch (Exception e) {
logger.error("{}", e);
}
return false;
} public boolean set(String key, String value, int expireTime) {
if (!isOn.equals("true")) {
logger.info("缓存未开启");
return false;
}
try {
jedisCluster.setex(key, expireTime, value);
return true;
} catch (Exception e) {
logger.error("{}", e);
}
return false;
} public String get(String key) {
if (!isOn.equals("true")) {
logger.info("缓存未开启");
return "";
}
try {
return jedisCluster.get(key);
} catch (Exception e) {
logger.error("{}", e);
}
return null;
} public <T> boolean setList(String key, List<T> list, Class<T> tClass, int expireTime) {
if (!isOn.equals("true")) {
logger.info("缓存未开启");
return false;
}
try {
if (this.setnx(key + "Lock", "true", expireTime)) {
this.deleteKey(key);
for (T t : list) {
jedisCluster.rpush(key, SerializationDefine.Object2String(t));
}
if (1 == jedisCluster.expire(key, expireTime)) {
return true;
} else {
this.deleteKey(key);
return false;
}
}
return true;
} catch (Exception e) {
logger.error("{}", e);
}
return false;
} public <T> List<T> getList(String key, Class<T> tClass) {
if (!isOn.equals("true")) {
logger.info("缓存未开启");
return null;
}
try {
List<T> tList = new ArrayList<T>();
List<String> strList = jedisCluster.lrange(key, 0L, -1L);
for (String str : strList) {
tList.add(SerializationDefine.String2Object(str, tClass));
} return tList.size() == 0 ? null : tList;
} catch (Exception e) {
logger.error("{}", e);
return null;
}
} public <T> boolean setMap(String key, Map<String, T> map, Class<T> tClass, int expireTime) {
if (!isOn.equals("true")) {
logger.info("缓存未开启");
return false;
}
Map<String, String> catchMap = new HashMap<String, String>();
if (this.setnx(key + "Lock", "true", expireTime)) {
this.deleteKey(key);
for (Map.Entry<String, T> entry : map.entrySet()) {
catchMap.put(entry.getKey(), SerializationDefine.Object2String(entry.getValue()));
}
jedisCluster.hmset(key, catchMap);
if (1 == jedisCluster.expire(key, expireTime)) {
return true;
} else {
this.deleteKey(key);
return false;
} }
return true;
} public <T> Map<String, T> getMap(String key, Class<T> tClass) {
if (!isOn.equals("true")) {
logger.info("缓存未开启");
return null;
}
try {
Map<String, String> catchMap = jedisCluster.hgetAll(key);
Map<String, T> retMap = new HashMap<String, T>();
for (Map.Entry<String, String> entry : catchMap.entrySet()) {
retMap.put(entry.getKey(), SerializationDefine.String2Object(entry.getValue(), tClass));
}
return retMap;
} catch (Exception e) {
logger.error("{}", e);
return null;
} } public boolean deleteKey(String key) {
if (!isOn.equals("true")) {
logger.info("缓存未开启");
return false;
}
try {
if (1 == jedisCluster.del(key)) {
return true;
} else {
throw new Exception("redis异常,删除key失败:method = deleteKey; key = " + key);
}
} catch (Exception e) {
logger.error("{严重异常}", e);
} return false;
} /**
* 加1操作
*
* @param key
* @return
*/
public boolean incr(String key) {
if (!isOn.equals("true")) {
logger.info("缓存未开启");
return false;
}
try {
jedisCluster.incr(key);
return true;
} catch (Exception e) {
logger.error("{}", e);
return false;
}
} /**
* 减1操作
*
* @param key
* @return
*/
public boolean decr(String key) {
if (!isOn.equals("true")) {
logger.info("缓存未开启");
return false;
}
try {
jedisCluster.decr(key);
return true;
} catch (Exception e) {
logger.error("{}", e);
return false;
}
} /**
* 判断是否已缓存
*
* @param key
* @return
*/
public boolean isExist(String key) {
if (!isOn.equals("true")) {
logger.info("缓存未开启");
return false;
}
try {
return jedisCluster.exists(key);
} catch (Exception e) {
return false;
}
}
}
RedisClusterClient
说明,当redis连接不够用时,此setnx可能存在一些bug,即超时时间可能设置不成功!
所以当存在连接可能不够用的情况时,尽量不要使用setnx。
配置文件:
redis.onoff=true
redis.defaultExpireInSecond=900
redis.namespace=${cache_namespace}
redis.prefix=api-v3
RedisJavaClient.onoff=true
RedisJavaClient.servers=${redis_servers}
##==========================================================
redisMultiCluster.defaultExpireInSecond=900
redisMultiCluster.prefix=location-v3
redisMultiCluster.namespace=${cache_namespace}
redisMultiCluster.onoff=true
redisMultiCluster.clusters=${redis_clusters}
redisMultiCluster.route=route1:0|route2:1
redisMultiCluster.rule=com.xiaomi.weather.commons.cache.SubKeyRule
redisMultiCluster.startIndex=0
redisMultiCluster.endIndex=5 ##-------------连接池配置------------------
#最大连接数,最大资源空闲数目,最小资源空闲数目
redisMultiCluster.maxTotal=30
redisMultiCluster.maxIdle=30
redisMultiCluster.minIdle=10
#连接耗尽时,是否等待;等待时长(ms)
redisMultiCluster.blockWhenExhausted=true
redisMultiCluster.maxWaitMillis=500 #输出连接时是否检测空闲超时,回收连接检测,创建连接检测,输出连接检测,
redisMultiCluster.testWhileIdle=false
redisMultiCluster.testOnReturn=true
redisMultiCluster.testOnCreate=true
redisMultiCluster.testOnBorrow=true #(暂时不可用)资源耗尽时的处理措施0 - 抛异常,1 - 阻塞等待可用资源,2-强制创建新连接
redisMultiCluster.whenExhaustedAction=1
序列化类:
package com.xiaomi.weather.vote.webservices.util.redisCache; import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Preconditions; /**
* Created by mi on 16-12-22.
*/
public class SerializationDefine {
public static String Object2String(Object obj) {
Preconditions.checkArgument(obj != null, "序列化对象为null");
return JSONObject.toJSONString(obj);
} public static <T> T String2Object(String str, Class<T> tClass) {
return JSONObject.parseObject(str, tClass);
}
}
工具类第二版,修复删除key,而key不存在时报异常的bug;
package com.xiaomi.weather.vote.webservices.util.redisCache; import com.google.common.base.Strings;
import org.apache.log4j.Logger;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig; import java.io.InputStream;
import java.util.*; /**
* Created by mi on 16-12-22.
*/
public class RedisClusterClient {
private static final Logger logger = Logger.getLogger(RedisClusterClient.class);
private static String isOn = "true"; // 是否启用缓存
private static JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); // 配置信息
public JedisCluster jedisCluster = null;
Set<HostAndPort> jedisClusterNodes = new HashSet<HostAndPort>(); public static RedisClusterClient redisClusterClient = new RedisClusterClient(); public RedisClusterClient() {
init();
} public static RedisClusterClient getInsance() {
if (redisClusterClient != null) {
return redisClusterClient;
} else {
redisClusterClient = new RedisClusterClient();
return redisClusterClient;
}
} public boolean init() {
try {
// 读取配置文件
InputStream path = RedisClusterClient.class.getClassLoader().getResourceAsStream("cache.properties");
Properties pros = new Properties();
pros.load(path);
this.isOn = pros.getProperty("redis.onoff", "true");// 默认开启缓存
if (this.isOn.equals("false")) {// 未开启缓存
return false;
} //
String servers = pros.getProperty("redisMultiCluster.clusters", null);
if (Strings.isNullOrEmpty(servers)) {
logger.error("RedisJavaClient.servers 配置错误; in file:cache.properties");
this.isOn = "false";
return false;
}
String[] hostAndPorts = servers.split("\\|");
for (int i = 0; i < hostAndPorts.length; i++) {
String hostAndPort = hostAndPorts[i];
if (!hostAndPort.contains(":")) {
return false;
}
jedisClusterNodes.add(new HostAndPort(hostAndPort.split(":")[0], Integer.parseInt(hostAndPort.split(":")[1])));
}
try {
jedisPoolConfig.setMaxTotal(Integer.parseInt(pros.getProperty("redisMultiCluster.maxTotal", "8")));
jedisPoolConfig.setMaxIdle(Integer.parseInt(pros.getProperty("redisMultiCluster.maxIdle", "8")));
jedisPoolConfig.setMinIdle(Integer.parseInt(pros.getProperty("redisMultiCluster.minIdle", "0")));
jedisPoolConfig
.setBlockWhenExhausted(Boolean.parseBoolean(pros.getProperty("redisMultiCluster.blockWhenExhausted", "true")));
jedisPoolConfig.setMaxWaitMillis(Integer.parseInt(pros.getProperty("redisMultiCluster.maxWaitMillis", "true")));
jedisPoolConfig.setTestOnBorrow(Boolean.parseBoolean(pros.getProperty("redisMultiCluster.testOnBorrow", "true")));
jedisPoolConfig.setTestOnCreate(Boolean.parseBoolean(pros.getProperty("redisMultiCluster.testOnCreate", "true")));
jedisPoolConfig.setTestOnReturn(Boolean.parseBoolean(pros.getProperty("redisMultiCluster.testOnReturn", "true")));
jedisPoolConfig.setTestWhileIdle(Boolean.parseBoolean(pros.getProperty("redisMultiCluster.testWhileIdle", "false"))); } catch (Exception e) {
logger.error("{未知异常}", e);
}
jedisCluster = new JedisCluster(jedisClusterNodes, jedisPoolConfig);
logger.info("缓存初始化成功");
path.close();
return true;
} catch (Exception e) {
logger.error("{缓存初始化错误}", e);
this.isOn = "false";
}
return false;
} public boolean setnx(String key, String value, int expireTime) {
if (!isOn.equals("true")) {
logger.info("缓存未开启");
return false;
}
try {
Long setSuccess = jedisCluster.setnx(key, value);
if (setSuccess == 1) {//写入成功
if (1 == jedisCluster.expire(key, expireTime)) {
return true;
} else {
this.deleteKey(key);
return false;
}
} else {
return false;
}
} catch (Exception e) {
try {
this.deleteKey(key);
} catch (Exception ex) {
logger.error("删除key异常:key = " + key);
}
logger.error("{}", e);
}
return false;
} public boolean set(String key, String value, int expireTime) {
if (!isOn.equals("true")) {
logger.info("缓存未开启");
return false;
}
try {
jedisCluster.setex(key, expireTime, value);
return true;
} catch (Exception e) {
logger.error("{}", e);
}
return false;
} public String get(String key) {
if (!isOn.equals("true")) {
logger.info("缓存未开启");
return "";
}
try {
return jedisCluster.get(key);
} catch (Exception e) {
logger.error("{}", e);
}
return null;
} public <T> boolean setList(String key, List<T> list, Class<T> tClass, int expireTime) {
if (!isOn.equals("true")) {
logger.info("缓存未开启");
return false;
}
try {
if (this.setnx(key + "Lock", "true", expireTime)) {
this.deleteKey(key);
for (T t : list) {
jedisCluster.rpush(key, SerializationDefine.Object2String(t));
}
if (1 == jedisCluster.expire(key, expireTime)) {
return true;
} else {
this.deleteKey(key);
return false;
}
}
return true;
} catch (Exception e) {
logger.error("{}", e);
}
return false;
} public <T> List<T> getList(String key, Class<T> tClass) {
if (!isOn.equals("true")) {
logger.info("缓存未开启");
return null;
}
try {
List<T> tList = new ArrayList<T>();
List<String> strList = jedisCluster.lrange(key, 0L, -1L);
for (String str : strList) {
tList.add(SerializationDefine.String2Object(str, tClass));
} return tList.size() == 0 ? null : tList;
} catch (Exception e) {
logger.error("{}", e);
return null;
}
} public <T> boolean setMap(String key, Map<String, T> map, Class<T> tClass, int expireTime) {
if (!isOn.equals("true")) {
logger.info("缓存未开启");
return false;
}
Map<String, String> catchMap = new HashMap<String, String>();
try {
if (this.setnx(key + "Lock", "true", expireTime)) {
this.deleteKey(key);
for (Map.Entry<String, T> entry : map.entrySet()) {
catchMap.put(entry.getKey(), SerializationDefine.Object2String(entry.getValue()));
}
jedisCluster.hmset(key, catchMap);
if (1 == jedisCluster.expire(key, expireTime)) {
return true;
} else {
this.deleteKey(key);
return false;
} }
} catch (Exception e) {
logger.error("{严重异常}", e);
}
return true;
} public <T> Map<String, T> getMap(String key, Class<T> tClass) {
if (!isOn.equals("true")) {
logger.info("缓存未开启");
return null;
}
try {
Map<String, String> catchMap = jedisCluster.hgetAll(key);
Map<String, T> retMap = new HashMap<String, T>();
for (Map.Entry<String, String> entry : catchMap.entrySet()) {
retMap.put(entry.getKey(), SerializationDefine.String2Object(entry.getValue(), tClass));
}
return retMap;
} catch (Exception e) {
logger.error("{}", e);
return null;
} } public boolean deleteKey(String key) throws Exception {
if (!isOn.equals("true")) {
logger.info("缓存未开启");
return false;
}
try {
if (!this.isExist(key)) {//key不存在
return true;
}
if (1 == jedisCluster.del(key)) {
return true;
} else {
throw new Exception("redis异常,删除key失败:method = deleteKey; key = " + key);
}
} catch (Exception e) {
logger.error("{严重异常}", e);
throw new Exception("redis异常,删除key失败:method = deleteKey; key = " + key);
}
} /**
* 加1操作
*
* @param key
* @return
*/
public boolean incr(String key) {
if (!isOn.equals("true")) {
logger.info("缓存未开启");
return false;
}
try {
jedisCluster.incr(key);
return true;
} catch (Exception e) {
logger.error("{}", e);
return false;
}
} /**
* 减1操作
*
* @param key
* @return
*/
public boolean decr(String key) {
if (!isOn.equals("true")) {
logger.info("缓存未开启");
return false;
}
try {
jedisCluster.decr(key);
return true;
} catch (Exception e) {
logger.error("{}", e);
return false;
}
} /**
* 判断是否已缓存
*
* @param key
* @return
*/
public boolean isExist(String key) throws Exception {
if (!isOn.equals("true")) {
logger.info("缓存未开启");
return false;
}
try {
return jedisCluster.exists(key);
} catch (Exception e) {
logger.error("{严重异常}判断key是否存在发生异常... ... key = " + key, e);
throw new Exception("{严重异常}判断key是否存在发生异常... ...key = " + key);
}
} public static void main(String[] arges) {
try {
System.out.println(RedisClusterClient.getInsance().jedisCluster.del("panpanpan"));
} catch (Exception e) {
e.printStackTrace();
} }
}
redis集群使用Java工具类(Java jedis集群工具类)的更多相关文章
- 编写Spark的WordCount程序并提交到集群运行[含scala和java两个版本]
编写Spark的WordCount程序并提交到集群运行[含scala和java两个版本] 1. 开发环境 Jdk 1.7.0_72 Maven 3.2.1 Scala 2.10.6 Spark 1.6 ...
- 005-guava 集合-集合工具类-java.util.Collections中未包含的集合工具[Maps,Lists,Sets],Iterables、Multisets、Multimaps、Tables
一.概述 工具类与特定集合接口的对应关系归纳如下: 集合接口 属于JDK还是Guava 对应的Guava工具类 Collection JDK Collections2:不要和java.util.Col ...
- Java集合框架(六)—— Collections工具类
操作集合的工具类Collections Java提供了一个操作Set.List和Map等集合的工具类:Collections,该工具类里提供了大量方法对集合元素进行排序.查询和修改等操作,还提供了将集 ...
- java调用kettle的job和transfer工具类
package com.woaiyitiaocai.util; import java.util.Map; import java.util.UUID; import org.apache.log4j ...
- Java学习笔记 -- Java定时调度工具Timer类
1 关于 (时间宝贵的小姐姐请跳过) 本教程是基于Java定时任务调度工具详解之Timer篇的学习笔记. 什么是定时任务调度 基于给定的时间点,给定的时间间隔或者给定的执行次数自动执行的任务. 在Ja ...
- JavaSE-基础语法(二)-系统类(java.lang.*)和工具类(java.util.*)
系统类(java.lang.*)和工具类(java.util.*) 一.系统类(java.lang.*) 这个包下包含java语言的核心类,如String.Math.System和Thread类等,使 ...
- Java+大数据开发——Hadoop集群环境搭建(一)
1集群简介 HADOOP集群具体来说包含两个集群:HDFS集群和YARN集群,两者逻辑上分离,但物理上常在一起 HDFS集群: 负责海量数据的存储,集群中的角色主要有 NameNode / DataN ...
- 反射工具类.提供调用getter/setter方法, 访问私有变量, 调用私有方法, 获取泛型类型Class,被AOP过的真实类等工具函数.java
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Validate; import org.ap ...
- 4 kafka集群部署及kafka生产者java客户端编程 + kafka消费者java客户端编程
本博文的主要内容有 kafka的单机模式部署 kafka的分布式模式部署 生产者java客户端编程 消费者java客户端编程 运行kafka ,需要依赖 zookeeper,你可以使用已有的 zo ...
- 开发工具、Object类(java基础知识十一)
1.常见开发工具介绍 * A:操作系统自带的记事本软件 * B:高级记事本软件 * C:集成开发环境 IDE * (Integrated Development Environment) * ...
随机推荐
- JEECMS 2.4.2 之添加新的可扩展的ftl模版文件、自定义方法
Demo: <@cms.CfgList isPage='1' league='0' recommend='0' lala='0' hot='1' memberId='0' pageNo=page ...
- js引入方式的弹框方法2
html代码: <!DOCTYPE html> <html lang="zh-CN"> <head> <meta http-equiv=& ...
- 巨蟒python全栈开发django6: FBV&CBV&&单表查询的其他方法
练习CBV用法 截图中的action="/cbv/",应该是这样 上边红图,说明mysql有问题,需要重启一下 返回,输入的内容 @wrapper==>cbv=wrapper ...
- mysql_表_操作
1.创建表 # 基本语法: create table 表名( 列名 类型 是否可以为空 默认值 自增 主键, 列名 类型 是否可以为空 )ENGINE=InnoDB DEFAULT CHARSET=u ...
- Springboot中读取自定义名称properties的
Springboot读取自定义的配置文件时候,使用@value,一定要指定配置文件的位置! 否则报错参数化异常!
- Ajax 处理json的方法不同
json字符串从从后台传递到前台的方法有两种 1.使用context.Response(); 2.使用webmethod 方法调用静态函数 返回的字符串 前者返回的json是obj类型,而后者返回的是 ...
- JavaScript中label与break配合使用
语法 label: statement 说明 label语句可以在代码中添加标签,以便将来使用.定义的标签可以在将来由break或continue语句引用.加标签的语句一般都要与for语句等循环语句配 ...
- JavaScript通过preventDefault()使input[type=text]禁止输入但保留光标
一.说明 取消事件的默认动作. 该方法将通知 Web 浏览器不要执行与事件关联的默认动作(如果存在这样的动作).例如,如果 type 属性是 "submit",在事件传播的任意阶段 ...
- mustache模板技术(转)
项目首页:http://mustache.github.com/ 项目文档:http://mustache.github.com/mustache.5.html Demo: http://mus ...
- 人工智能-基于百度baidu-ai和图灵机器人实现学说话机器人
本文引用了2个js文件,这里提供下CDN资源,! <script type="application/javascript" src="https://cdn.bo ...