Java调用RedisCluster(JedisCluster)封装工具类
使用Redis4.0以上版本 需要jedis2.9以上
Maven仓库配置:
1 2 3 4 5 |
<dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.0</version> </dependency> |
顺便写了个配置文件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
<?xml version="1.0" encoding="UTF-8"?> <redisCluster timeout="2000" maxRedirections="12"> <nodes> <node host="192.168.1.116" port="5001" type="master"/> <node host="192.168.1.101" port="5002" type="master"/> <node host="192.168.1.110" port="5003" type="master"/> <node host="192.168.1.116" port="5004" type="master"/> <node host="192.168.1.110" port="5005" type="master"/> <node host="10.163.152.94" port="5006" type="master"/> <node host="192.168.1.110" port="5101" type="slave"/> <node host="192.168.1.116" port="5102" type="slave"/> <node host="192.168.1.101" port="5103" type="slave"/> <node host="192.168.1.110" port="5104" type="slave"/> <node host="192.168.1.116" port="5105" type="slave"/> <node host="192.168.1.101" port="5106" type="slave"/> </nodes> <poolConfig> <maxTotal>8</maxTotal> <maxIdle>8</maxIdle> <minIdle>0</minIdle> <maxWaitMillis>1000</maxWaitMillis> <testOnBorrow>true</testOnBorrow> <testOnReturn>true</testOnReturn> <testWhileIdle>true</testWhileIdle> </poolConfig> </redisCluster> |
然后顺便又写了个读取配置文件的工具类,仅适用于本例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 |
package net.code2048.common.utils; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * * @author 破晓(www.code2048.net) * */ public class PropertyConfigUtil { /** * 加载配置文件 * @param name * @return */ public static Properties loadProperty(String name) { InputStream in = PropertyConfigUtil.class.getResourceAsStream("/" + name + ".properties"); return loadProperty(in); } public static Properties loadProperty(InputStream in) { Properties pro = null; try { pro = new Properties(); pro.load(in); in.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return pro; } public static Document loadXML(InputStream stream){ try { if(stream != null) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(stream); return doc; } } catch (Exception e) { e.printStackTrace(); } return null; } public static Document loadXML(String name){ InputStream stream = PropertyConfigUtil.class.getResourceAsStream("/" + name + ".xml"); return loadXML(stream); } /** * 加载xml 配置文件 * @param name * @return */ public static Map<String,Object> loadXML2Map(String name){ Document doc = loadXML(name); return XML2Map(doc); } public static Map<String,Object> loadXML2Map(InputStream stream){ Document doc = loadXML(stream); return XML2Map(doc); } /** * xml 转Map * @param doc * @return */ public static Map<String,Object> XML2Map(Node doc) { Map<String,Object> map = new HashMap<String, Object>(); NamedNodeMap atts = doc.getAttributes(); if(atts != null) { int len = atts.getLength(); Node itemAtt; for(int i=0; i<len; i++) { itemAtt = atts.item(i); map.put(itemAtt.getNodeName(), itemAtt.getNodeValue().trim()); } } NodeList children = doc.getChildNodes(); int len = children.getLength(); Node item; List<Map<String, Object>> items; for(int j=0; j<len; j++) { item = children.item(j); if("#text".equals(item.getNodeName())) continue; // if("#comment".equals(item.getNodeName())) continue; // 注释 if(map.containsKey(item.getNodeName())) items = (List<Map<String, Object>>) map.get(item.getNodeName()); else items = new ArrayList<Map<String, Object>>(); items.add(XML2Map(item)); map.put(item.getNodeName(), items); } for(int j=0; j<len; j++) { item = children.item(j); if(!map.containsKey(item.getNodeName())) continue; items = (List<Map<String, Object>>) map.get(item.getNodeName()); if(items.size() == 1) { Map<String, Object> value = items.get(0); if(value.size() == 0) map.put(item.getNodeName(), item.getTextContent().trim()); else map.put(item.getNodeName(), value); } } return map; } public static String getXMLAttribute(Node doc, String att) { return doc.getNodeValue(); } public static String getXMLItemAttribute(Node doc, String itemName, String att) { return doc.getChildNodes().item(0).getAttributes().getNamedItem(itemName).getNodeValue(); } } |
&( ^___^ )& &( ^___^ )& &( ^___^ )&
好啦!! 东风具备,只差万事
JedisCluster 自带连接池并且连接池的出入都已经封装好 所以不用像使用Jedis单点似的需要手动调用close方法 不过这样一来效率就会下降,
有时间可以再次封装一下,这里全部封装的静态方法
RedisClusterConfig.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 |
package net.net2048.redis.cluster; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import net.daorong.common.utils.PropertyConfigUtil; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import redis.clients.jedis.HostAndPort; import redis.clients.jedis.JedisCluster; /** * * @author 破晓(www.code2048.net) * */ public class RedisClusterConfig { // private static final String configName = "jedis-cluster"; private static final String configName = "jedis-cluster-test"; public static void getConfig() { Map<String, Object> config = PropertyConfigUtil.loadXML2Map(configName); config = (Map<String, Object>) config.get("redisCluster"); maxRedirections = Integer.parseInt((String)config.get("maxRedirections")); timeout = Integer.parseInt((String)config.get("timeout")); Map<String, String> poolConfigMap = (Map<String, String>) config.get("poolConfig"); Map<String, Object> nodes = (Map<String, Object>) config.get("nodes"); List<Map<String, Object>> nodeList = (List<Map<String, Object>>) nodes.get("node"); poolConfig = new GenericObjectPoolConfig(); poolConfig.setMaxTotal(Integer.parseInt(poolConfigMap.get("maxTotal"))); // 链接池中最大连接数 poolConfig.setMaxIdle(Integer.parseInt(poolConfigMap.get("maxIdle"))); // 链接池中最大空闲的连接数 poolConfig.setMinIdle(Integer.parseInt(poolConfigMap.get("minIdle"))); // 连接池中最少空闲的连接数 poolConfig.setMaxWaitMillis(Integer.parseInt(poolConfigMap.get("maxWaitMillis"))); // 当连接池资源耗尽时,等待时间,超出则抛异常,默认为-1即永不超时 poolConfig.setTestOnBorrow(Boolean.getBoolean(poolConfigMap.get("testOnBorrow"))); // borrow的时候检测是有有效,如果无效则从连接池中移除,并尝试获取继续获取 poolConfig.setTestOnReturn(Boolean.getBoolean(poolConfigMap.get("testOnReturn"))); // return的时候检测是有有效,如果无效则从连接池中移除,并尝试获取继续获取 poolConfig.setTestWhileIdle(Boolean.getBoolean(poolConfigMap.get("testWhileIdle"))); // 在evictor线程里头,当evictionPolicy.evict方法返回false时,而且testWhileIdle为true的时候则检测是否有效,如果无效则移除 jedisClusterNodes = new HashSet<HostAndPort>(); for(Map<String, Object> item:nodeList) { jedisClusterNodes.add(new HostAndPort((String)item.get("host"), Integer.parseInt((String)item.get("port")))); } } /** 重定向次数 */ public static int maxRedirections = 6; /** 超时时间 */ public static int timeout = 2000; private static GenericObjectPoolConfig poolConfig; private static Set<HostAndPort> jedisClusterNodes; public static GenericObjectPoolConfig getPoolConfig() { if(poolConfig == null) getConfig(); return poolConfig; } public static Set<HostAndPort> getClusterNodes() { if(jedisClusterNodes == null) getConfig(); return jedisClusterNodes; } public static JedisCluster getJedis() { RedisClusterConfig.getConfig(); // 使用redis集群中的任一节点即可 JedisCluster jedis = new JedisCluster( RedisClusterConfig.getClusterNodes(), RedisClusterConfig.timeout, RedisClusterConfig.maxRedirections, RedisClusterConfig.getPoolConfig()); return jedis; } /** * @param args */ public static void main(String[] args) { RedisClusterConfig.getConfig(); } } |
RedisCluster.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 |
package net.code2048.redis.cluster; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import static net.code2048.common.utils.JsonUtil.jsonToObj; import static net.code2048.common.utils.StringUtil.isEmpty; import redis.clients.jedis.JedisCluster; /** * * @author 破晓(www.code2048.net) * */ public class RedisCluster { private static JedisCluster jedis = RedisClusterConfig.getJedis(); private static final int DEFAULT_ACQUIRY_RESOLUTION_MILLIS = 100; /** * 锁超时时间,防止线程在入锁以后,无限的执行等待 */ private static int expireMsecs = 14 * 1000; // ================================================== // 基础操作 // ================================================== // ********************************读取操作********************************* /** * 查询缓存信息 */ public static String get(String key) { if (isEmpty(key)) { return null; } String value = jedis.get(key); if (isEmpty(value)) { return null; } return value; } /** * 查询缓存信息 */ public static <T> T get(String key, Class<T> clazz) { if (isEmpty(key)) { return null; } String value = jedis.get(key); if (isEmpty(value)) { return null; } return jsonToObj(value, clazz); } /** * 查询缓存信息 */ public static long getLong(String key) { String v = get(key); if (!isEmpty(v)) return Long.parseLong(v); return 0; } /** * 查询缓存信息 */ public static double getDouble(String key) { String v = get(key); if (!isEmpty(v)) return Double.parseDouble(v); return 0; } /** * 查询缓存信息 */ public static int getInt(String key) { String v = get(key); if (!isEmpty(v)) return Integer.parseInt(v); return 0; } /** * 查询缓存信息 */ public static byte[] getByte(String key) { if (isEmpty(key)) { return null; } byte[] value = jedis.get(key.getBytes()); return value; } // ********************************写入操作********************************* /** * 添加缓存信息 */ public static Boolean set(String key, String value) { if (isEmpty(key) || isEmpty(value)) { return false; } String result = jedis.set(key, value); return "ok".equalsIgnoreCase(result); } public static Boolean set(String key, long value) { return set(key, value + ""); } public static Boolean set(String key, int value) { return set(key, value + ""); } public static Boolean set(String key, double value) { return set(key, value + ""); } public static Boolean setByte(String key, byte[] value) { if (isEmpty(key) || value == null) { return false; } String result = jedis.set(key.getBytes(), value); return "ok".equalsIgnoreCase(result); } public static Boolean setOnSeconds(String key, String value, int seconds) { if (isEmpty(key) || isEmpty(value)) { return false; } String result = jedis.set(key, value); if ("ok".equalsIgnoreCase(result)) { if (seconds > 0) jedis.expire(key, seconds); } return "ok".equalsIgnoreCase(result); } public static Boolean setByteOnSeconds(String key, byte[] value, int seconds) { if (isEmpty(key) || value == null) { return false; } String result = jedis.set(key.getBytes(), value); if ("ok".equalsIgnoreCase(result)) { if (seconds > 0) jedis.expire(key, seconds); } return "ok".equalsIgnoreCase(result); } // ********************************其他操作********************************* /** * 设置超时时间 * * @param key * @param seconds * @return */ public static long setExpire(String key, int seconds) { if (isEmpty(key) || seconds <= 0) { return -1; } return jedis.expire(key, seconds); } /** * 删除缓存 */ public static Boolean delete(String key) { if (isEmpty(key)) { return false; } Long result = jedis.del(key); if (result <= 0) { // log.error("redis delete error,key:" + key); return false; } return true; } public static boolean getLock(String key, int retryCount) { boolean ret = true; if (!setnx(key, null)) { try { Thread.sleep(1000); if (retryCount-- > 0) { getLock(key, retryCount); } else { ret = false; } } catch (InterruptedException e) { e.printStackTrace(); ret = false; } } return ret; } public static void unLock(String key) { String currentValueStr = jedis.get(key); // redis里的时间 // 当过期时间不为空而且现在还在锁定的时间内,则进行删除锁操作 if (currentValueStr != null && Long.parseLong(currentValueStr) > System.currentTimeMillis()) { delete(key); } } /** * 查询过期时间 */ public static long ttl(String key) { if (isEmpty(key)) { return -1; } Long result = jedis.ttl(key); return result; } /** * 将 key 的值设为 value ,当且仅当 key 不存在。 设置成功,返回 true 。 设置失败,返回 false 。 */ public static Boolean setnx(String key, String value) { if (isEmpty(key)) { return false; } String v = isEmpty(value) ? String.valueOf(System .currentTimeMillis()) : value; Long result = jedis.setnx(key, String.valueOf(v)); boolean isSuccess = result == 1; jedis.expire(key, 3);// 3秒钟后过期 return isSuccess; } public static Boolean exists(String key) { if (isEmpty(key)) { return null; } Boolean result = jedis.exists(key); return result; } // ================================================== // 词典操作 // ================================================== /** * 添加缓存信息 */ public static long hset(String key, String field, String value) { if (isEmpty(key) || isEmpty(field)) { return 0; } long result = jedis.hset(key, field, value); return result; } /** * 添加缓存信息 */ public static long hset(String key, String field, int value) { return hset(key, field, value+""); } /** * 添加缓存信息 */ public static long hset(String key, String field, long value) { return hset(key, field, value+""); } /** * 添加缓存信息 */ public static long hset(String key, String field, double value) { return hset(key, field, value+""); } /** * 获取缓存信息 */ public static String hget(String key, String field) { if (isEmpty(key) || isEmpty(field)) { return null; } String result = jedis.hget(key, field); return result; } /** * 查询缓存信息 */ public static long hgetLong(String key, String field) { String v = hget(key, field); if (!isEmpty(v)) return Long.parseLong(v); return 0; } /** * 查询缓存信息 */ public static double hgetDouble(String key, String field) { String v = hget(key, field); if (!isEmpty(v)) return Double.parseDouble(v); return 0; } /** * 查询缓存信息 */ public static int hgetInt(String key, String field) { String v = hget(key, field); if (!isEmpty(v)) return Integer.parseInt(v); return 0; } /** * 获取缓存信息 */ public static Long hdel(String key, String field) { if (isEmpty(key) || isEmpty(field)) { return null; } Long result = jedis.hdel(key, field); return result; } /** * 获取缓存信息 */ public static Map<String, String> hgetAll(String key) { if (isEmpty(key)) { return null; } Map<String, String> result = jedis.hgetAll(key); return result; } /** * 校验缓存信息 */ public static boolean hexists(String key, String field) { if (isEmpty(key) || isEmpty(field)) { return false; } Boolean result = jedis.hexists(key, field); return result; } /** * 查询缓存信息 */ public static <T> T hget(String key, String field, Class<T> clazz) { if (isEmpty(key)) { return null; } String value = jedis.hget(key, field); if (isEmpty(value)) { return null; } return jsonToObj(value, clazz); } // ================================================== // 集合操作 // ================================================== public static Long lpush(String key, String... value) { if (isEmpty(key)) return -1l; if (value == null) return -1l; long count = jedis.lpush(key, value); return count; } public static Long rpush(String key, String... value) { if (isEmpty(key)) return -1l; if (value == null) return -1l; long count = jedis.rpush(key, value); return count; } public static Long llen(String key) { if (isEmpty(key)) return -1l; long count = jedis.llen(key); return count; } public static String lindex(String key, long index) { if (isEmpty(key)) return null; String info = jedis.lindex(key, index); return info; } public static String lset(String key, long index, String value) { if (isEmpty(key)) return null; String info = jedis.lset(key, index, value); return info; } public static List<String> lrange(String key, Long from, Long to) { if (isEmpty(key)) return null; if (!isNumber2(from)) return null; if (!isNumber2(to)) return null; // jedis.multi(); List<String> list = jedis.lrange(key, from, to); return list; } public static Boolean isNumber2(Object obj) { if (null == obj) { return false; } return Pattern.compile("^[-+]?[0-9]+(\\.[0-9]+)?$") .matcher(obj.toString()).matches(); } public static <T> T lpop(String key, Class<T> clazz) { if (isEmpty(key)) return null; String value = jedis.lpop(key); if (isEmpty(value) || "nil".equalsIgnoreCase(value)) { return null; } return jsonToObj(value, clazz); } public static String lpop(String key) { if (isEmpty(key)) return null; String value = jedis.lpop(key); return value; } public static String rpop(String key) { if (isEmpty(key)) return null; String value = jedis.rpop(key); if (isEmpty(value) || "nil".equalsIgnoreCase(value)) { return null; } return value; } public static long lrem(String key, String value) { if (isEmpty(key)) return 0; long ret = jedis.lrem(key, 1, value); return ret; } /** * 获得 lock. 实现思路: 主要是使用了redis 的setnx命令,缓存了锁. reids缓存的key是锁的key,所有的共享, * value是锁的到期时间(注意:这里把过期时间放在value了,没有时间上设置其超时时间) 执行过程: * 1.通过setnx尝试设置某个key的值,成功(当前没有这个锁)则返回,成功获得锁 * 2.锁已经存在则获取锁的到期时间,和当前时间比较,超时的话,则设置新的值 * * @return true if lock is acquired, false acquire timeouted * @throws InterruptedException * in case of thread interruption */ public static synchronized boolean lock(String lockKey) throws InterruptedException { long expires = System.currentTimeMillis() + expireMsecs + 1; String expiresStr = String.valueOf(expires); // 锁到期时间 if (jedis.setnx(lockKey, expiresStr) > 0) { // System.out.println("localKey="+lockKey+"获取锁"); return true; } String currentValueStr = jedis.get(lockKey); // redis里的时间 if (currentValueStr != null && Long.parseLong(currentValueStr) < System.currentTimeMillis()) { // 判断是否为空,不为空的情况下,如果被其他线程设置了值,则第二个条件判断是过不去的 // lock is expired String oldValueStr = jedis.getSet(lockKey, expiresStr); // 获取上一个锁到期时间,并设置现在的锁到期时间, // 只有一个线程才能获取上一个线上的设置时间,因为jedis.getSet是同步的 if (oldValueStr != null && oldValueStr.equals(currentValueStr)) { // 防止误删(覆盖,因为key是相同的)了他人的锁——这里达不到效果,这里值会被覆盖,但是因为什么相差了很少的时间,所以可以接受 // System.out.println("localKey="+lockKey+"获取锁2"); // [分布式的情况下]:如过这个时候,多个线程恰好都到了这里,但是只有一个线程的设置值和当前值相同,他才有权利获取锁 // lock acquired return true; } } /* * 延迟100 毫秒, 这里使用随机时间可能会好一点,可以防止饥饿进程的出现,即,当同时到达多个进程, * 只会有一个进程获得锁,其他的都用同样的频率进行尝试,后面有来了一些进行,也以同样的频率申请锁,这将可能导致前面来的锁得不到满足. * 使用随机的等待时间可以一定程度上保证公平性 */ Thread.sleep(DEFAULT_ACQUIRY_RESOLUTION_MILLIS); System.out.println("localKey=" + lockKey + "锁定失败"); return false; } } |
里面有个 jsonToObj
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import org.codehaus.jackson.map.ObjectMapper; /** * json转对象 */ public static <T> T jsonToObj(String json, Class<T> clazz) { ObjectMapper mapper = new ObjectMapper(); try { return mapper.readValue(json, clazz); } catch (Exception e) { return null; } } |
1 2 3 4 5 |
<dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> |
本文链接:Java调用RedisCluster(JedisCluster)封装工具类
转载声明:本站文章若无特别说明,皆为原创,转载请注明来源:破晓(http://www.code2048.net),谢谢!^^