|
@@ -0,0 +1,94 @@
|
|
|
|
+package io.emqx.exhook.Redis;
|
|
|
|
+
|
|
|
|
+import java.util.HashMap;
|
|
|
|
+import java.util.Map;
|
|
|
|
+
|
|
|
|
+import redis.clients.jedis.Jedis;
|
|
|
|
+import redis.clients.jedis.JedisPool;
|
|
|
|
+import redis.clients.jedis.JedisPoolConfig;
|
|
|
|
+
|
|
|
|
+public class RedisUtil {
|
|
|
|
+
|
|
|
|
+ private static String IP = "localhost";
|
|
|
|
+
|
|
|
|
+ private static int PORT = 6379;
|
|
|
|
+ private RedisUtil(){}
|
|
|
|
+
|
|
|
|
+ private static class RedisUtilHolder{
|
|
|
|
+ private static final RedisUtil instance = new RedisUtil();
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ public static void set(String key ,String Value, int timeout){
|
|
|
|
+ JedisPool pool = getPool(IP,PORT);
|
|
|
|
+ Jedis jedis = pool.getResource();
|
|
|
|
+ jedis.set(key,Value);
|
|
|
|
+ jedis.expire("key", timeout);
|
|
|
|
+ jedis.close();
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ public static String get(String key){
|
|
|
|
+ JedisPool pool = getPool(IP,PORT);
|
|
|
|
+ Jedis jedis = pool.getResource();
|
|
|
|
+ String temp = jedis.get(key);
|
|
|
|
+ jedis.close();
|
|
|
|
+ return temp;
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ public static RedisUtil getInstance(){
|
|
|
|
+ return RedisUtilHolder.instance;
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ private static Map<String,JedisPool> maps = new HashMap<String,JedisPool>();
|
|
|
|
+
|
|
|
|
+ private static JedisPool getPool(String ip, int port){
|
|
|
|
+
|
|
|
|
+ String key = ip+":"+port;
|
|
|
|
+ JedisPool pool = null;
|
|
|
|
+ if(!maps.containsKey(key))
|
|
|
|
+ {
|
|
|
|
+ JedisPoolConfig config = new JedisPoolConfig();
|
|
|
|
+ config.setMaxTotal(10);
|
|
|
|
+ config.setMaxIdle(10);
|
|
|
|
+ config.setMinIdle(2);
|
|
|
|
+ config.setMaxWaitMillis(30*1000);
|
|
|
|
+ config.setTestOnBorrow(true);
|
|
|
|
+ config.setTestOnReturn(true);
|
|
|
|
+ config.setTimeBetweenEvictionRunsMillis(10*1000);
|
|
|
|
+ config.setMinEvictableIdleTimeMillis(30*1000);
|
|
|
|
+ pool = new JedisPool(config,ip,port);
|
|
|
|
+ maps.put(key, pool);
|
|
|
|
+ }
|
|
|
|
+ else
|
|
|
|
+ {
|
|
|
|
+ pool = maps.get(key);
|
|
|
|
+ }
|
|
|
|
+ return pool;
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ public Jedis getJedis(String ip, int port)
|
|
|
|
+ {
|
|
|
|
+ Jedis jedis = null;
|
|
|
|
+ int count = 0;
|
|
|
|
+ do
|
|
|
|
+ {
|
|
|
|
+ try
|
|
|
|
+ {
|
|
|
|
+ jedis = getPool(ip,port).getResource();
|
|
|
|
+ }
|
|
|
|
+ catch (Exception e)
|
|
|
|
+ {
|
|
|
|
+ getPool(ip,port).returnBrokenResource(jedis);
|
|
|
|
+ }
|
|
|
|
+ }
|
|
|
|
+ while(jedis == null && count < 5);
|
|
|
|
+ return jedis;
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ public void closeJedis(Jedis jedis, String ip, int port){
|
|
|
|
+ if(jedis != null)
|
|
|
|
+ {
|
|
|
|
+ getPool(ip,port).returnResource(jedis);
|
|
|
|
+ }
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+}
|