diff --git a/pom.xml b/pom.xml index 7f94f04..da62685 100644 --- a/pom.xml +++ b/pom.xml @@ -39,32 +39,11 @@ + + + - - - src/main/resources - - **/*.properties - **/*.xml - **/*.xsd - **/*.yml - - true - - - - src/main/java - - **/*.properties - **/*.xml - - true - - - - - @@ -628,7 +607,13 @@ httpcore 4.4 - + + jdk.tools + jdk.tools + 1.7 + system + ${JAVA_HOME}/lib/tools.jar + org.apache.httpcomponents httpclient diff --git a/src/main/java/com/nis/util/JedisUtils.java b/src/main/java/com/nis/util/JedisUtils.java new file mode 100644 index 0000000..d6f1bb5 --- /dev/null +++ b/src/main/java/com/nis/util/JedisUtils.java @@ -0,0 +1,845 @@ +package com.nis.util; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import com.google.common.collect.Sets; +import com.nis.web.service.SpringContextHolder; + +import redis.clients.jedis.Jedis; +import redis.clients.jedis.JedisPool; +import redis.clients.jedis.exceptions.JedisException; + +public class JedisUtils { + private static Logger logger = LoggerFactory.getLogger(JedisUtils.class); + + private static JedisPool jedisPool = SpringContextHolder.getBean(JedisPool.class); + + /** + * 获取缓存 + * @param key 键 + * @return 值 + */ + public static String get(String key, int redisDb) { + String value = null; + Jedis jedis = null; + try { + jedis = getResource(redisDb); + + if (jedis.exists(key)) { + value = jedis.get(key); + value = StringUtils.isNotBlank(value) && !"nil".equalsIgnoreCase(value) ? value : null; + logger.debug("get {} = {}", key, value); + } + } catch (Exception e) { + logger.warn("get {} = {}", key, value, e); + } finally { + returnResource(jedis); + } + return value; + } + + /** + * 获取缓存 + * @param key 键 + * @return 值 + */ + public static Object getObject(String key, int redisDb) { + Object value = null; + Jedis jedis = null; + try { + jedis = getResource(redisDb); + if (jedis.exists(getBytesKey(key))) { + value = toObject(jedis.get(getBytesKey(key))); + logger.debug("getObject {} = {}", key, value); + } + } catch (Exception e) { + logger.warn("getObject {} = {}", key, value, e); + } finally { + returnResource(jedis); + } + return value; + } + + /** + * 可以作为获取唯一id的方法
+ * 将key对应的value加上指定的值,只有value可以转为数字时该方法才可用 + * + * @param String + * key + * @param long number 要减去的值 + * @return long 相加后的值 + * */ + public static long incrBy(String key, long number,int redisDb) { + Jedis jedis = getResource(redisDb); + long len = jedis.incrBy(key, number); + returnResource(jedis); + return len; + } + + /** + * 设置缓存 + * @param key 键 + * @param value 值 + * @param cacheSeconds 超时时间,0为不超时 + * @return + */ + public static String set(String key, String value, int cacheSeconds, int redisDb) { + String result = null; + Jedis jedis = null; + try { + jedis = getResource(redisDb); + result = jedis.set(key, value); + if (cacheSeconds != 0) { + jedis.expire(key, cacheSeconds); + } + logger.debug("set {} = {}", key, value); + } catch (Exception e) { + logger.warn("set {} = {}", key, value, e); + } finally { + returnResource(jedis); + } + return result; + } + + /** + * 设置缓存 + * @param key 键 + * @param value 值 + * @param cacheSeconds 超时时间,0为不超时 + * @return + */ + public static String setObject(String key, Object value, int cacheSeconds, int redisDb) { + String result = null; + Jedis jedis = null; + try { + jedis = getResource(redisDb); + result = jedis.set(getBytesKey(key), toBytes(value)); + if (cacheSeconds != 0) { + jedis.expire(key, cacheSeconds); + } + logger.debug("setObject {} = {}", key, value); + } catch (Exception e) { + logger.warn("setObject {} = {}", key, value, e); + } finally { + returnResource(jedis); + } + return result; + } + + /** + * 获取List缓存 + * @param key 键 + * @return 值 + */ + public static List getList(String key, int redisDb) { + List value = null; + Jedis jedis = null; + try { + jedis = getResource(redisDb); + if (jedis.exists(key)) { + value = jedis.lrange(key, 0, -1); + logger.debug("getList {} = {}", key, value); + } + } catch (Exception e) { + logger.warn("getList {} = {}", key, value, e); + } finally { + returnResource(jedis); + } + return value; + } + + /** + * 获取List缓存 + * @param key 键 + * @return 值 + */ + public static List getObjectList(String key, int redisDb) { + List value = null; + Jedis jedis = null; + try { + jedis = getResource(redisDb); + if (jedis.exists(getBytesKey(key))) { + List list = jedis.lrange(getBytesKey(key), 0, -1); + value = Lists.newArrayList(); + for (byte[] bs : list) { + value.add(toObject(bs)); + } + logger.debug("getObjectList {} = {}", key, value); + } + } catch (Exception e) { + logger.warn("getObjectList {} = {}", key, value, e); + } finally { + returnResource(jedis); + } + return value; + } + + /** + * 设置List缓存 + * @param key 键 + * @param value 值 + * @param cacheSeconds 超时时间,0为不超时 + * @return + */ + public static long setList(String key, List value, int cacheSeconds, int redisDb) { + long result = 0; + Jedis jedis = null; + try { + jedis = getResource(redisDb); + if (jedis.exists(key)) { + jedis.del(key); + } + result = jedis.rpush(key, (String[]) value.toArray()); + if (cacheSeconds != 0) { + jedis.expire(key, cacheSeconds); + } + logger.debug("setList {} = {}", key, value); + } catch (Exception e) { + logger.warn("setList {} = {}", key, value, e); + } finally { + returnResource(jedis); + } + return result; + } + + /** + * 设置List缓存 + * @param key 键 + * @param value 值 + * @param cacheSeconds 超时时间,0为不超时 + * @return + */ + public static long setObjectList(String key, List value, int cacheSeconds, int redisDb) { + long result = 0; + Jedis jedis = null; + try { + jedis = getResource(redisDb); + if (jedis.exists(getBytesKey(key))) { + jedis.del(key); + } + List list = Lists.newArrayList(); + for (Object o : value) { + list.add(toBytes(o)); + } + result = jedis.rpush(getBytesKey(key), (byte[][]) list.toArray()); + if (cacheSeconds != 0) { + jedis.expire(key, cacheSeconds); + } + logger.debug("setObjectList {} = {}", key, value); + } catch (Exception e) { + logger.warn("setObjectList {} = {}", key, value, e); + } finally { + returnResource(jedis); + } + return result; + } + + /** + * 向List缓存中添加值 + * @param key 键 + * @param value 值 + * @return + */ + public static long listAdd(String key, int redisDb, String... value) { + long result = 0; + Jedis jedis = null; + try { + jedis = getResource(redisDb); + result = jedis.rpush(key, value); + logger.debug("listAdd {} = {}", key, value); + } catch (Exception e) { + logger.warn("listAdd {} = {}", key, value, e); + } finally { + returnResource(jedis); + } + return result; + } + + /** + * 向List缓存中添加值 + * @param key 键 + * @param value 值 + * @return + */ + public static long listObjectAdd(String key, int redisDb, Object... value) { + long result = 0; + Jedis jedis = null; + try { + jedis = getResource(redisDb); + List list = Lists.newArrayList(); + for (Object o : value) { + list.add(toBytes(o)); + } + result = jedis.rpush(getBytesKey(key), (byte[][]) list.toArray()); + logger.debug("listObjectAdd {} = {}", key, value); + } catch (Exception e) { + logger.warn("listObjectAdd {} = {}", key, value, e); + } finally { + returnResource(jedis); + } + return result; + } + + /** + * 获取缓存 + * @param key 键 + * @return 值 + */ + public static Set getSet(String key, int redisDb) { + Set value = null; + Jedis jedis = null; + try { + jedis = getResource(redisDb); + if (jedis.exists(key)) { + value = jedis.smembers(key); + logger.debug("getSet {} = {}", key, value); + } + } catch (Exception e) { + logger.warn("getSet {} = {}", key, value, e); + } finally { + returnResource(jedis); + } + return value; + } + + /** + * 获取缓存 + * @param key 键 + * @return 值 + */ + public static Set getObjectSet(String key, int redisDb) { + Set value = null; + Jedis jedis = null; + try { + jedis = getResource(redisDb); + if (jedis.exists(getBytesKey(key))) { + value = Sets.newHashSet(); + Set set = jedis.smembers(getBytesKey(key)); + for (byte[] bs : set) { + value.add(toObject(bs)); + } + logger.debug("getObjectSet {} = {}", key, value); + } + } catch (Exception e) { + logger.warn("getObjectSet {} = {}", key, value, e); + } finally { + returnResource(jedis); + } + return value; + } + + /** + * 设置Set缓存 + * @param key 键 + * @param value 值 + * @param cacheSeconds 超时时间,0为不超时 + * @return + */ + public static long setSet(String key, Set value, int cacheSeconds, int redisDb) { + long result = 0; + Jedis jedis = null; + try { + jedis = getResource(redisDb); + if (jedis.exists(key)) { + jedis.del(key); + } + result = jedis.sadd(key, (String[]) value.toArray()); + if (cacheSeconds != 0) { + jedis.expire(key, cacheSeconds); + } + logger.debug("setSet {} = {}", key, value); + } catch (Exception e) { + logger.warn("setSet {} = {}", key, value, e); + } finally { + returnResource(jedis); + } + return result; + } + + /** + * 设置Set缓存 + * @param key 键 + * @param value 值 + * @param cacheSeconds 超时时间,0为不超时 + * @return + */ + public static long setObjectSet(String key, Set value, int cacheSeconds, int redisDb) { + long result = 0; + Jedis jedis = null; + try { + jedis = getResource(redisDb); + if (jedis.exists(getBytesKey(key))) { + jedis.del(key); + } + Set set = Sets.newHashSet(); + for (Object o : value) { + set.add(toBytes(o)); + } + result = jedis.sadd(getBytesKey(key), (byte[][]) set.toArray()); + if (cacheSeconds != 0) { + jedis.expire(key, cacheSeconds); + } + logger.debug("setObjectSet {} = {}", key, value); + } catch (Exception e) { + logger.warn("setObjectSet {} = {}", key, value, e); + } finally { + returnResource(jedis); + } + return result; + } + + /** + * 向Set缓存中添加值 + * @param key 键 + * @param value 值 + * @return + */ + public static long setSetAdd(String key, int redisDb, String... value) { + long result = 0; + Jedis jedis = null; + try { + jedis = getResource(redisDb); + result = jedis.sadd(key, value); + logger.debug("setSetAdd {} = {}", key, value); + } catch (Exception e) { + logger.warn("setSetAdd {} = {}", key, value, e); + } finally { + returnResource(jedis); + } + return result; + } + + /** + * 向Set缓存中添加值 + * @param key 键 + * @param value 值 + * @return + */ + public static long setSetObjectAdd(String key, int redisDb, Object... value) { + long result = 0; + Jedis jedis = null; + try { + jedis = getResource(redisDb); + Set set = Sets.newHashSet(); + for (Object o : value) { + set.add(toBytes(o)); + } + result = jedis.rpush(getBytesKey(key), (byte[][]) set.toArray()); + logger.debug("setSetObjectAdd {} = {}", key, value); + } catch (Exception e) { + logger.warn("setSetObjectAdd {} = {}", key, value, e); + } finally { + returnResource(jedis); + } + return result; + } + + /** + * 获取Map缓存 + * @param key 键 + * @return 值 + */ + public static Map getMap(String key, int redisDb) { + Map value = null; + Jedis jedis = null; + try { + jedis = getResource(redisDb); + if (jedis.exists(key)) { + value = jedis.hgetAll(key); + logger.debug("getMap {} = {}", key, value); + } + } catch (Exception e) { + logger.warn("getMap {} = {}", key, value, e); + } finally { + returnResource(jedis); + } + return value; + } + + /** + * 获取Map缓存 + * @param key 键 + * @return 值 + */ + public static Map getObjectMap(String key, int redisDb) { + Map value = null; + Jedis jedis = null; + try { + jedis = getResource(redisDb); + if (jedis.exists(getBytesKey(key))) { + value = Maps.newHashMap(); + Map map = jedis.hgetAll(getBytesKey(key)); + for (Map.Entry e : map.entrySet()) { + value.put(StringUtils.toString(e.getKey()), toObject(e.getValue())); + } + logger.debug("getObjectMap {} = {}", key, value); + } + } catch (Exception e) { + logger.warn("getObjectMap {} = {}", key, value, e); + } finally { + returnResource(jedis); + } + return value; + } + + /** + * 设置Map缓存 + * @param key 键 + * @param value 值 + * @param cacheSeconds 超时时间,0为不超时 + * @return + */ + public static String setMap(String key, Map value, int cacheSeconds, int redisDb) { + String result = null; + Jedis jedis = null; + try { + jedis = getResource(redisDb); + if (jedis.exists(key)) { + jedis.del(key); + } + result = jedis.hmset(key, value); + if (cacheSeconds != 0) { + jedis.expire(key, cacheSeconds); + } + logger.debug("setMap {} = {}", key, value); + } catch (Exception e) { + logger.warn("setMap {} = {}", key, value, e); + } finally { + returnResource(jedis); + } + return result; + } + + /** + * 设置Map缓存 + * @param key 键 + * @param value 值 + * @param cacheSeconds 超时时间,0为不超时 + * @return + */ + public static String setObjectMap(String key, Map value, int cacheSeconds, int redisDb) { + String result = null; + Jedis jedis = null; + try { + jedis = getResource(redisDb); + if (jedis.exists(getBytesKey(key))) { + jedis.del(key); + } + Map map = Maps.newHashMap(); + for (Map.Entry e : value.entrySet()) { + map.put(getBytesKey(e.getKey()), toBytes(e.getValue())); + } + result = jedis.hmset(getBytesKey(key), (Map) map); + if (cacheSeconds != 0) { + jedis.expire(key, cacheSeconds); + } + logger.debug("setObjectMap {} = {}", key, value); + } catch (Exception e) { + logger.warn("setObjectMap {} = {}", key, value, e); + } finally { + returnResource(jedis); + } + return result; + } + + /** + * 向Map缓存中添加值 + * @param key 键 + * @param value 值 + * @return + */ + public static String mapPut(String key, Map value, int redisDb) { + String result = null; + Jedis jedis = null; + try { + jedis = getResource(redisDb); + result = jedis.hmset(key, value); + logger.debug("mapPut {} = {}", key, value); + } catch (Exception e) { + logger.warn("mapPut {} = {}", key, value, e); + } finally { + returnResource(jedis); + } + return result; + } + + /** + * 向Map缓存中添加值 + * @param key 键 + * @param value 值 + * @return + */ + public static String mapObjectPut(String key, Map value, int redisDb) { + String result = null; + Jedis jedis = null; + try { + jedis = getResource(redisDb); + Map map = Maps.newHashMap(); + for (Map.Entry e : value.entrySet()) { + map.put(getBytesKey(e.getKey()), toBytes(e.getValue())); + } + result = jedis.hmset(getBytesKey(key), (Map) map); + logger.debug("mapObjectPut {} = {}", key, value); + } catch (Exception e) { + logger.warn("mapObjectPut {} = {}", key, value, e); + } finally { + returnResource(jedis); + } + return result; + } + + /** + * 移除Map缓存中的值 + * @param key 键 + * @param value 值 + * @return + */ + public static long mapRemove(String key, String mapKey, int redisDb) { + long result = 0; + Jedis jedis = null; + try { + jedis = getResource(redisDb); + result = jedis.hdel(key, mapKey); + logger.debug("mapRemove {} {}", key, mapKey); + } catch (Exception e) { + logger.warn("mapRemove {} {}", key, mapKey, e); + } finally { + returnResource(jedis); + } + return result; + } + + /** + * 移除Map缓存中的值 + * @param key 键 + * @param value 值 + * @return + */ + public static long mapObjectRemove(String key, String mapKey, int redisDb) { + long result = 0; + Jedis jedis = null; + try { + jedis = getResource(redisDb); + result = jedis.hdel(getBytesKey(key), getBytesKey(mapKey)); + logger.debug("mapObjectRemove {} {}", key, mapKey); + } catch (Exception e) { + logger.warn("mapObjectRemove {} {}", key, mapKey, e); + } finally { + returnResource(jedis); + } + return result; + } + + /** + * 判断Map缓存中的Key是否存在 + * @param key 键 + * @param value 值 + * @return + */ + public static boolean mapExists(String key, String mapKey, int redisDb) { + boolean result = false; + Jedis jedis = null; + try { + jedis = getResource(redisDb); + result = jedis.hexists(key, mapKey); + logger.debug("mapExists {} {}", key, mapKey); + } catch (Exception e) { + logger.warn("mapExists {} {}", key, mapKey, e); + } finally { + returnResource(jedis); + } + return result; + } + + /** + * 判断Map缓存中的Key是否存在 + * @param key 键 + * @param value 值 + * @return + */ + public static boolean mapObjectExists(String key, String mapKey, int redisDb) { + boolean result = false; + Jedis jedis = null; + try { + jedis = getResource(redisDb); + result = jedis.hexists(getBytesKey(key), getBytesKey(mapKey)); + logger.debug("mapObjectExists {} {}", key, mapKey); + } catch (Exception e) { + logger.warn("mapObjectExists {} {}", key, mapKey, e); + } finally { + returnResource(jedis); + } + return result; + } + + /** + * 删除缓存 + * @param key 键 + * @return + */ + public static long del(String key, int redisDb) { + long result = 0; + Jedis jedis = null; + try { + jedis = getResource(redisDb); + if (jedis.exists(key)) { + result = jedis.del(key); + logger.debug("del {}", key); + } else { + logger.debug("del {} not exists", key); + } + } catch (Exception e) { + logger.warn("del {}", key, e); + } finally { + returnResource(jedis); + } + return result; + } + + /** + * 删除缓存 + * @param key 键 + * @return + */ + public static long delObject(String key, int redisDb) { + long result = 0; + Jedis jedis = null; + try { + jedis = getResource(redisDb); + if (jedis.exists(getBytesKey(key))) { + result = jedis.del(getBytesKey(key)); + logger.debug("delObject {}", key); + } else { + logger.debug("delObject {} not exists", key); + } + } catch (Exception e) { + logger.warn("delObject {}", key, e); + } finally { + returnResource(jedis); + } + return result; + } + + /** + * 缓存是否存在 + * @param key 键 + * @return + */ + public static boolean exists(String key, int redisDb) { + boolean result = false; + Jedis jedis = null; + try { + jedis = getResource(redisDb); + result = jedis.exists(key); + logger.debug("exists {}", key); + } catch (Exception e) { + logger.warn("exists {}", key, e); + } finally { + returnResource(jedis); + } + return result; + } + + /** + * 缓存是否存在 + * @param key 键 + * @return + */ + public static boolean existsObject(String key, int redisDb) { + boolean result = false; + Jedis jedis = null; + try { + jedis = getResource(redisDb); + result = jedis.exists(getBytesKey(key)); + logger.debug("existsObject {}", key); + } catch (Exception e) { + logger.warn("existsObject {}", key, e); + } finally { + returnResource(jedis); + } + return result; + } + + /** + * 获取资源 + * @return + * @throws JedisException + */ + public static Jedis getResource(int redisDb) throws JedisException { + Jedis jedis = null; + if (jedisPool == null) { + throw new RuntimeException("后台错误:redis连接池为空,请联系管理员检查程序"); + } + try { + jedis = jedisPool.getResource(); + jedis.select(redisDb); + } catch (JedisException e) { + returnBrokenResource(jedis); + throw new RuntimeException("后台错误:获取redis连接失败,请联系管理员检查程序", e); + } + return jedis; + + } + + /** + * 归还资源 + * @param jedis + * @param isBroken + */ + public static void returnBrokenResource(Jedis jedis) { + if (jedis != null) { + // jedisPool.returnBrokenResource(jedis); + jedis.close(); + } + } + + /** + * 释放资源 + * @param jedis + * @param isBroken + */ + public static void returnResource(Jedis jedis) { + if (jedis != null) { + jedis.close(); + } + } + + /** + * 获取byte[]类型Key + * @param key + * @return + */ + public static byte[] getBytesKey(Object object) { + if (object instanceof String) { + return StringUtils.getBytes((String) object); + } else { + return ObjectUtils.serialize(object); + } + } + + /** + * Object转换byte[]类型 + * @param key + * @return + */ + public static byte[] toBytes(Object object) { + return ObjectUtils.serialize(object); + } + + /** + * byte[]型转换Object + * @param key + * @return + */ + public static Object toObject(byte[] bytes) { + return ObjectUtils.unserialize(bytes); + } + +} diff --git a/src/main/java/com/nis/util/JedisUtils2.java b/src/main/java/com/nis/util/JedisUtils2.java new file mode 100644 index 0000000..bba7725 --- /dev/null +++ b/src/main/java/com/nis/util/JedisUtils2.java @@ -0,0 +1,1422 @@ +package com.nis.util; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +import redis.clients.jedis.BinaryClient.LIST_POSITION; +import redis.clients.jedis.Jedis; +import redis.clients.jedis.JedisPool; +import redis.clients.jedis.JedisPoolConfig; +import redis.clients.jedis.JedisSentinelPool; +import redis.clients.jedis.Response; +import redis.clients.jedis.SortingParams; +import redis.clients.jedis.Transaction; +import redis.clients.util.SafeEncoder; + +public class JedisUtils2 { + + /* 缓存生存时间 */ + private int expire = 60000; + + /* 对key的操作方法 */ + private static JedisPool jedisPool = null; + + public static void main(String[] args) { + + JedisPoolConfig config = new JedisPoolConfig(); + config.setMaxTotal(25); + config.setMaxIdle(5); + config.setMaxWaitMillis(100000); + // 在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的 + config.setTestOnBorrow(true); + jedisPool = new JedisPool(config, "10.0.6.249", 6381); + + Jedis resource = jedisPool.getResource(); + resource.watch("version"); + Transaction multi = resource.multi(); + + multi.incrBy("version", 1); + multi.set("cgh", "任凯歌"); + String version = new JedisUtils2().get("version"); + multi.select(2); + multi.set("rkg", "陈桂华"); + List exec = multi.exec(); + for (Object object : exec) { + System.out.println(object); + } + System.out.println("ok"); + } + + public JedisPool getPool() { + return jedisPool; + } + + /* 从jedispool中获取jedis对象 */ + public Jedis getJedis() { + if (jedisPool == null) { + throw new NullPointerException(); + } + return jedisPool.getResource(); + } + + public static JedisPool getJedisPool() { + return jedisPool; + } + + public static void setJedisPool(JedisPool jedisPool) { + JedisUtils2.jedisPool = jedisPool; + } + + /* + * 在finaally中回收jedis + */ + public void returnJedis(Jedis jedis) { + if (null != jedis && null != jedisPool) { + // jedisPool.returnResource(jedis); + jedis.close(); + } + } + + /* + * 销毁链接(放入catch + */ + public static void returnBrokenResource(Jedis jedis) { + if (null != jedis && null != jedisPool) { + // jedisPool.returnResource(jedis); + jedis.close(); + } + } + + /* + * 设置过期时间 + */ + public void expire(String key, int seconds) { + if (seconds < 0) { + return; + } + Jedis jedis = getJedis(); + jedis.expire(key, seconds); + returnJedis(jedis); + } + + /* + * 设置默认过期时间 + */ + public void expire(String key) { + expire(key, expire); + } + + /* + * 清空所有key + */ + public String flushAll() { + Jedis jedis = getJedis(); + String stata = jedis.flushAll(); + returnJedis(jedis); + return stata; + } + + /* + * 更改key 返回值是状态吗 + */ + + public String rename(String oldkey, String newkey) { + return rename(SafeEncoder.encode(oldkey), SafeEncoder.encode(newkey)); + } + + /* + * 更改key,仅当新key不存在时才执行 + */ + public long renamenx(String oldkey, String newkey) { + Jedis jedis = getJedis(); + long status = jedis.renamenx(oldkey, newkey); + returnJedis(jedis); + return status; + + } + + /* + * 更改key + */ + public String rename(byte[] oldkey, byte[] newkey) { + Jedis jedis = getJedis(); + String status = jedis.rename(oldkey, newkey); + returnJedis(jedis); + return status; + } + + /* + * 设置key的过期时间,以秒为单位 返回值是影响的记录数 + */ + public long expired(String key, int seconds) { + Jedis jedis = getJedis(); + long count = jedis.expire(key, seconds); + returnJedis(jedis); + return count; + } + + /* + * 设置key的过期时间,它是距历元(即格林威治标准时间 1970年1月1日的00:00:00,格里高利历)的偏移量 + */ + public long expireAt(String key, long timestamp) { + Jedis jedis = getJedis(); + long count = jedis.expireAt(key, timestamp); + returnJedis(jedis); + return count; + } + + /* + * 查询key的过期时间 以秒为单位的时间表示返回的是指定key的剩余的生存时间 + */ + public long ttl(String key) { + Jedis sjedis = getJedis(); + long len = sjedis.ttl(key); + returnJedis(sjedis); + return len; + + } + + /* + * 取消对key过期时间的设置 将带生存时间的转换成一个永不过期的key + * + * 当移除成功时返回1,key不存在或者移除不成功时返回0 + */ + public long persist(String key) { + Jedis jedis = getJedis(); + long count = jedis.persist(key); + returnJedis(jedis); + return count; + } + + /* + * 删除keys对应的记录,可以是多个key + * + * 返回值是被删除的数量 + */ + public long del(String... keys) { + Jedis jedis = getJedis(); + long count = jedis.del(keys); + returnJedis(jedis); + return count; + } + + /* + * 删除keys对应的记录,可以是多个key + */ + public long del(byte[]... keys) { + Jedis jedis = getJedis(); + long count = jedis.del(keys); + returnJedis(jedis); + return count; + } + + /* + * 判断key是否存在 + */ + public boolean exists(String key) { + Jedis jedis = getJedis(); + boolean exists = jedis.exists(key); + returnJedis(jedis); + return exists; + } + + /* + * 对List,set,SortSet 进行排序,如果集合数据较大应避免使用这个方法 + * + * 返回排序后的结果,默认升序 sort key Desc为降序 + */ + public List sort(String key) { + Jedis jedis = getJedis(); + List list = jedis.sort(key); + + returnJedis(jedis); + return list; + } + + /* + * 对List,set,SortSet 进行排序,如果集合数据较大应避免使用这个方法 + * + * 返回排序后的结果,默认升序 sort key Desc为降序 + */ + public List sort(String key, SortingParams parame) { + Jedis jedis = getJedis(); + List list = jedis.sort(key, parame); + returnJedis(jedis); + return list; + } + /* + * 返回指定key的存储类型 + */ + + public String type(String key) { + Jedis jedis = getJedis(); + String type = jedis.type(key); + returnJedis(jedis); + return type; + } + + /* + * 查找所有匹配模式的键 + * + * key的查询表达式 *代表任意多个 ?代表一个 + */ + public Set Keys(String pattern) { + Jedis jedis = getJedis(); + Set set = jedis.keys(pattern); + + returnJedis(jedis); + return set; + } + + /*************************set部分*******************************/ + /* + * 向set添加一条记录,如果member已经存在则返回0,否则返回1 + */ + public long sadd(String key, String member) { + Jedis jedis = getJedis(); + + Long s = jedis.sadd(key, member); + returnJedis(jedis); + return s; + } + + public long sadd(byte[] key, byte[] member) { + Jedis jedis = getJedis(); + Long s = jedis.sadd(key, member); + returnJedis(jedis); + return s; + } + + /* + * 获取给定key中元素个数 + * + * @return 元素个数 + */ + public long scard(String key) { + Jedis jedis = getJedis(); + Long count = jedis.scard(key); + returnJedis(jedis); + return count; + } + + /* + * 返回从第一组和所有的给定集合之间的有差异的成员 + * + * @return 有差异成员的集合 + */ + public Set sdiff(String... keys) { + Jedis jedis = getJedis(); + Set set = jedis.sdiff(keys); + returnJedis(jedis); + return set; + } + + /* + * 这个命令的作用和 SDIFF 类似,但它将结果保存到 destination 集合,而不是简单地返回结果集,如果目标已存在,则覆盖 + * + * @return 新集合的记录数 + */ + public long sdiffstore(String newkey, String... keys) { + Jedis jedis = getJedis(); + Long count = jedis.sdiffstore(newkey, keys); + returnJedis(jedis); + return count; + } + + /* + * sinter 返回给定集合交集成员,如果其中一个集合为不存在或为空,则返回空set + * + * @return 交集成员的集合 + */ + public Set sinter(String... keys) { + Jedis jedis = getJedis(); + Set set = jedis.sinter(keys); + returnJedis(jedis); + return set; + } + + /* + * sinterstore 这个命令类似于 SINTER 命令,但它将结果保存到 destination 集合,而不是简单地返回结果集。 如果 + * destination 集合已经存在,则将其覆盖。destination 可以是 key 本身 + * + * @return 新集合的记录数 + */ + public long sinterstore(String dstkey, String... keys) { + Jedis jedis = getJedis(); + long count = jedis.sinterstore(dstkey, keys); + returnJedis(jedis); + return count; + } + + /* + * sismember 确定一个给定的值是否存在 + * + * @param String member 要判断的值 + * + * @return 存在返回1,不存在返回0 + */ + public boolean sismember(String key, String member) { + Jedis jedis = getJedis(); + Boolean s = jedis.sismember(key, member); + returnJedis(jedis); + return s; + } + /* + * smembers 返回集合中的所有成员 + * + * @return 成员集合 + */ + + public Set smembers(String key) { + Jedis jedis = getJedis(); + Set set = jedis.smembers(key); + returnJedis(jedis); + return set; + } + + public Set smembers(byte[] key) { + Jedis jedis = getJedis(); + Set set = jedis.smembers(key); + returnJedis(jedis); + return set; + } + + /* + * smove 将成员从源集合移除放入目标集合
如果源集合不存在或不包含指定成员,不进行任何操作,返回0
+ * 否则该成员从源集合上删除,并添加到目标集合,如果目标集合成员以存在,则只在源集合进行删除 + * + * @param srckey 源集合 dstkey目标集合 member源集合中的成员 + * + * @return 状态码 1成功 0失败 + */ + public long smove(String srckey, String dstkey, String member) { + Jedis jedis = getJedis(); + Long s = jedis.smove(srckey, dstkey, member); + returnJedis(jedis); + return s; + } + + /* + * spop 从集合中删除成员 移除并返回集合中的一个随机元素。 + * + * @return 被删除的随机成员 + */ + public String spop(String key) { + Jedis jedis = getJedis(); + String s = jedis.spop(key); // s 被移除的随机成员 + returnJedis(jedis); + return s; + } + + /* + * 从集合中删除指定成员 移除集合 key 中的一个或多个 member 元素,不存在的 member 元素会被忽略。当 key 不是集合类型,返回一个错误。 + * + * @param key member要删除的成员 + * + * @return 状态码 成功返回1,成员不存在返回0 + */ + public long srem(String key, String member) { + Jedis jedis = getJedis(); + Long s = jedis.srem(key, member); + returnJedis(jedis); + return s; + } + + /* + * sunion 合并多个集合并将合并后的结果集保存在指定的新集合中,如果新集合已经存在则覆盖 + */ + public Set sunion(String... keys) { + Jedis jedis = getJedis(); + Set set = jedis.sunion(keys); + returnJedis(jedis); + return set; + } + + /* + * 这个命令类似于 SUNION 命令,但它将结果保存到 destination 集合,而不是简单地返回结果集。 如果 destination + * 已经存在,则将其覆盖。 destination 可以是 key 本身 + */ + public long sunionstore(String dstkey, String... keys) { + Jedis jedis = getJedis(); + Long s = jedis.sunionstore(dstkey, keys); + returnJedis(jedis); + return s; + } + + /******************************SortSet******************************/ + + /* + * zadd 向集合中增加一条记录,如果这个值已经存在,这个值对应的权重将被置为新的权重 + * + * @param double score 权重 member要加入的值 + * + * @return 状态码 1成功 0已经存在member值 + */ + + public long zadd(String key, double score, String member) { + Jedis jedis = getJedis(); + long s = jedis.zadd(key, score, member); + returnJedis(jedis); + return s; + } + + /* + * 获取集合中元素的数量 + * + * @param String key + * + * @return 当 key 存在且是有序集类型时,返回有序集的基数。 当 key 不存在时,返回 0 。 + */ + public long zcard(String key) { + Jedis jedis = getJedis(); + long count = jedis.zcard(key); + returnJedis(jedis); + return count; + } + + /* + * zcount 获取指定权重区间内的集合数量 + * + * @param double min最小排序位置 max最大排序位置 + */ + public long zcount(String key, double min, double max) { + Jedis jedis = getJedis(); + long count = jedis.zcount(key, min, max); + returnJedis(jedis); + return count; + } + + /* + * zrange 返回有序集合key中,指定区间的成员0,-1指的是整个区间的成员 + */ + public Set zrange(String key, int start, int end) { + + Jedis jedis = getJedis(); + Set set = jedis.zrange(key, 0, -1); + returnJedis(jedis); + return set; + } + + /* + * zrevrange 返回有序集 key 中,指定区间内的成员。其中成员的位置按 score 值递减(从大到小)来排列 + */ + public Set zrevrange(String key, int start, int end) { + // ShardedJedis sjedis = getShardedJedis(); + Jedis sjedis = getJedis(); + Set set = sjedis.zrevrange(key, start, end); + returnJedis(sjedis); + return set; + } + + /* + * zrangeByScore 根据上下权重查询集合 + */ + public Set zrangeByScore(String key, double min, double max) { + Jedis jedis = getJedis(); + Set set = jedis.zrangeByScore(key, min, max); + returnJedis(jedis); + return set; + } + + /* + * 接上面方法,获取有序集合长度 + */ + public long zlength(String key) { + long len = 0; + Set set = zrange(key, 0, -1); + len = set.size(); + return len; + } + + /* + * zincrby 为有序集 key 的成员 member 的 score 值加上增量 increment + * + * @return member 成员的新 score 值,以字符串形式表示 + */ + + public double zincrby(String key, double score, String member) { + Jedis jedis = getJedis(); + double s = jedis.zincrby(key, score, member); + returnJedis(jedis); + return s; + } + /* + * zrank 返回有序集 key 中成员 member 的排名。其中有序集成员按 score 值递增(从小到大)顺序排列 + */ + + public long zrank(String key, String member) { + Jedis jedis = getJedis(); + long index = jedis.zrank(key, member); + returnJedis(jedis); + return index; + } + + /* + * zrevrank 返回有序集 key 中成员 member 的排名。其中有序集成员按 score 值递减(从大到小)排序。 + */ + public long zrevrank(String key, String member) { + Jedis jedis = getJedis(); + long index = jedis.zrevrank(key, member); + returnJedis(jedis); + return index; + } + + /* + * zrem 移除有序集 key 中的一个或多个成员,不存在的成员将被忽略。当 key 存在但不是有序集类型时,返回一个错误。在 Redis 2.4 + * 版本以前, ZREM 每次只能删除一个元素。 + * + * @return 被成功移除的成员的数量,不包括被忽略的成员 + */ + public long zrem(String key, String member) { + Jedis jedis = getJedis(); + long count = jedis.zrem(key, member); + returnJedis(jedis); + return count; + + } + + /* + * zremrangebyrank 移除有序集 key 中,指定排名(rank)区间内的所有成员。 + * + * @return 被移除成员的数量 + */ + public long zremrangeByRank(String key, int start, int end) { + Jedis jedis = getJedis(); + long count = jedis.zremrangeByRank(key, start, end); + returnJedis(jedis); + return count; + + } + + /* + * zremrangeByScore 删除指定权重区间的元素 + */ + public long zremrangeByScore(String key, double min, double max) { + Jedis jedis = getJedis(); + long count = jedis.zremrangeByScore(key, min, max); + returnJedis(jedis); + return count; + } + + /* + * 获取给定值在集合中的权重 + */ + public double zscore(String key, String member) { + Jedis jedis = getJedis(); + Double score = jedis.zscore(key, member); + returnJedis(jedis); + if (score != null) { + return score; + } + return 0; + } + + /*******************************hash***********************************/ + /** + * 从hash中删除指定的存储 + * + * @param String + * key + * @param String + * fieid 存储的名字 + * @return 状态码,1成功,0失败 + * */ + public long hdel(String key, String fieid) { + Jedis jedis = getJedis(); + long s = jedis.hdel(key, fieid); + returnJedis(jedis); + return s; + } + + public long hdel(String key) { + Jedis jedis = getJedis(); + long s = jedis.del(key); + returnJedis(jedis); + return s; + } + + /** + * 测试hash中指定的存储是否存在 + * + * @param String + * key + * @param String + * fieid 存储的名字 + * @return 1存在,0不存在 + * */ + public boolean hexists(String key, String fieid) { + // ShardedJedis sjedis = getShardedJedis(); + Jedis sjedis = getJedis(); + boolean s = sjedis.hexists(key, fieid); + returnJedis(sjedis); + return s; + } + + /** + * 返回hash中指定存储位置的值 + * + * @param String + * key + * @param String + * fieid 存储的名字 + * @return 存储对应的值 + * */ + public String hget(String key, String fieid) { + // ShardedJedis sjedis = getShardedJedis(); + Jedis sjedis = getJedis(); + String s = sjedis.hget(key, fieid); + returnJedis(sjedis); + return s; + } + + public byte[] hget(byte[] key, byte[] fieid) { + // ShardedJedis sjedis = getShardedJedis(); + Jedis sjedis = getJedis(); + byte[] s = sjedis.hget(key, fieid); + returnJedis(sjedis); + return s; + } + + /** + * 以Map的形式返回hash中的存储和值 + * + * @param String + * key + * @return Map + * */ + public Map hgetAll(String key) { + // ShardedJedis sjedis = getShardedJedis(); + Jedis sjedis = getJedis(); + Map map = sjedis.hgetAll(key); + returnJedis(sjedis); + return map; + } + + /** + * 添加一个对应关系 + * + * @param String + * key + * @param String + * fieid + * @param String + * value + * @return 状态码 1成功,0失败,fieid已存在将更新,也返回0 + * **/ + public long hset(String key, String fieid, String value) { + Jedis jedis = getJedis(); + long s = jedis.hset(key, fieid, value); + returnJedis(jedis); + return s; + } + + public long hset(String key, String fieid, byte[] value) { + Jedis jedis = getJedis(); + long s = jedis.hset(key.getBytes(), fieid.getBytes(), value); + returnJedis(jedis); + return s; + } + + /** + * 添加对应关系,只有在fieid不存在时才执行 + * + * @param String + * key + * @param String + * fieid + * @param String + * value + * @return 状态码 1成功,0失败fieid已存 + * **/ + public long hsetnx(String key, String fieid, String value) { + Jedis jedis = getJedis(); + long s = jedis.hsetnx(key, fieid, value); + returnJedis(jedis); + return s; + } + + /** + * 获取hash中value的集合 + * + * @param String + * key + * @return List + * */ + public List hvals(String key) { + // ShardedJedis sjedis = getShardedJedis(); + Jedis sjedis = getJedis(); + List list = sjedis.hvals(key); + returnJedis(sjedis); + return list; + } + + /** + * 在指定的存储位置加上指定的数字,存储位置的值必须可转为数字类型 + * + * @param String + * key + * @param String + * fieid 存储位置 + * @param String + * long value 要增加的值,可以是负数 + * @return 增加指定数字后,存储位置的值 + * */ + public long hincrby(String key, String fieid, long value) { + Jedis jedis = getJedis(); + long s = jedis.hincrBy(key, fieid, value); + returnJedis(jedis); + return s; + } + + /** + * 返回指定hash中的所有存储名字,类似Map中的keySet方法 + * + * @param String + * key + * @return Set 存储名称的集合 + * */ + public Set hkeys(String key) { + // ShardedJedis sjedis = getShardedJedis(); + Jedis sjedis = getJedis(); + Set set = sjedis.hkeys(key); + returnJedis(sjedis); + return set; + } + + /** + * 获取hash中存储的个数,类似Map中size方法 + * + * @param String + * key + * @return long 存储的个数 + * */ + public long hlen(String key) { + // ShardedJedis sjedis = getShardedJedis(); + Jedis sjedis = getJedis(); + long len = sjedis.hlen(key); + returnJedis(sjedis); + return len; + } + + /** + * 根据多个key,获取对应的value,返回List,如果指定的key不存在,List对应位置为null + * + * @param String + * key + * @param String + * ... fieids 存储位置 + * @return List + * */ + public List hmget(String key, String... fieids) { + // ShardedJedis sjedis = getShardedJedis(); + Jedis sjedis = getJedis(); + List list = sjedis.hmget(key, fieids); + returnJedis(sjedis); + return list; + } + + public List hmget(byte[] key, byte[]... fieids) { + // ShardedJedis sjedis = getShardedJedis(); + Jedis sjedis = getJedis(); + List list = sjedis.hmget(key, fieids); + returnJedis(sjedis); + return list; + } + + /** + * 添加对应关系,如果对应关系已存在,则覆盖 + * + * @param Strin + * key + * @param Map + * 对应关系 + * @return 状态,成功返回OK + * */ + public String hmset(String key, Map map) { + Jedis jedis = getJedis(); + String s = jedis.hmset(key, map); + returnJedis(jedis); + return s; + } + + /** + * 添加对应关系,如果对应关系已存在,则覆盖 + * + * @param Strin + * key + * @param Map + * 对应关系 + * @return 状态,成功返回OK + * */ + public String hmset(byte[] key, Map map) { + Jedis jedis = getJedis(); + String s = jedis.hmset(key, map); + returnJedis(jedis); + return s; + } + + // *******************************************Strings*******************************************// + /** + * 根据key获取记录 + * + * @param String + * key + * @return 值 + * */ + public String get(String key) { + // ShardedJedis sjedis = getShardedJedis(); + Jedis sjedis = getJedis(); + String value = sjedis.get(key); + returnJedis(sjedis); + return value; + } + + /** + * 根据key获取记录 + * + * @param byte[] key + * @return 值 + * */ + public byte[] get(byte[] key) { + // ShardedJedis sjedis = getShardedJedis(); + Jedis sjedis = getJedis(); + byte[] value = sjedis.get(key); + returnJedis(sjedis); + return value; + } + + /** + * 添加有过期时间的记录 + * + * @param String + * key + * @param int seconds 过期时间,以秒为单位 + * @param String + * value + * @return String 操作状态 + * */ + public String setEx(String key, int seconds, String value) { + Jedis jedis = getJedis(); + String str = jedis.setex(key, seconds, value); + returnJedis(jedis); + return str; + } + + /** + * 添加有过期时间的记录 + * + * @param String + * key + * @param int seconds 过期时间,以秒为单位 + * @param String + * value + * @return String 操作状态 + * */ + public String setEx(byte[] key, int seconds, byte[] value) { + Jedis jedis = getJedis(); + String str = jedis.setex(key, seconds, value); + returnJedis(jedis); + return str; + } + + /** + * 添加一条记录,仅当给定的key不存在时才插入 + * + * @param String + * key + * @param String + * value + * @return long 状态码,1插入成功且key不存在,0未插入,key存在 + * */ + public long setnx(String key, String value) { + Jedis jedis = getJedis(); + long str = jedis.setnx(key, value); + returnJedis(jedis); + return str; + } + + /** + * 添加记录,如果记录已存在将覆盖原有的value + * + * @param String + * key + * @param String + * value + * @return 状态码 + * */ + public String set(String key, String value) { + return set(SafeEncoder.encode(key), SafeEncoder.encode(value)); + } + + /** + * 添加记录,如果记录已存在将覆盖原有的value + * + * @param String + * key + * @param String + * value + * @return 状态码 + * */ + public String set(String key, byte[] value) { + return set(SafeEncoder.encode(key), value); + } + + /** + * 添加记录,如果记录已存在将覆盖原有的value + * + * @param byte[] key + * @param byte[] value + * @return 状态码 + * */ + public String set(byte[] key, byte[] value) { + Jedis jedis = getJedis(); + String status = jedis.set(key, value); + returnJedis(jedis); + return status; + } + + /** + * 从指定位置开始插入数据,插入的数据会覆盖指定位置以后的数据
+ * 例:String str1="123456789";
+ * 对str1操作后setRange(key,4,0000),str1="123400009"; + * + * @param String + * key + * @param long offset + * @param String + * value + * @return long value的长度 + * */ + public long setRange(String key, long offset, String value) { + Jedis jedis = getJedis(); + long len = jedis.setrange(key, offset, value); + returnJedis(jedis); + return len; + } + + /** + * 在指定的key中追加value + * + * @param String + * key + * @param String + * value + * @return long 追加后value的长度 + * **/ + public long append(String key, String value) { + Jedis jedis = getJedis(); + long len = jedis.append(key, value); + returnJedis(jedis); + return len; + } + + /** + * 将key对应的value减去指定的值,只有value可以转为数字时该方法才可用 + * + * @param String + * key + * @param long number 要减去的值 + * @return long 减指定值后的值 + * */ + public long decrBy(String key, long number) { + Jedis jedis = getJedis(); + long len = jedis.decrBy(key, number); + returnJedis(jedis); + return len; + } + + /** + * 可以作为获取唯一id的方法
+ * 将key对应的value加上指定的值,只有value可以转为数字时该方法才可用 + * + * @param String + * key + * @param long number 要减去的值 + * @return long 相加后的值 + * */ + public long incrBy(String key, long number) { + Jedis jedis = getJedis(); + long len = jedis.incrBy(key, number); + returnJedis(jedis); + return len; + } + + /** + * 对指定key对应的value进行截取 + * + * @param String + * key + * @param long startOffset 开始位置(包含) + * @param long endOffset 结束位置(包含) + * @return String 截取的值 + * */ + public String getrange(String key, long startOffset, long endOffset) { + // ShardedJedis sjedis = getShardedJedis(); + Jedis sjedis = getJedis(); + String value = sjedis.getrange(key, startOffset, endOffset); + returnJedis(sjedis); + return value; + } + + /** + * 获取并设置指定key对应的value
+ * 如果key存在返回之前的value,否则返回null + * + * @param String + * key + * @param String + * value + * @return String 原始value或null + * */ + public String getSet(String key, String value) { + Jedis jedis = getJedis(); + String str = jedis.getSet(key, value); + returnJedis(jedis); + return str; + } + + /** + * 批量获取记录,如果指定的key不存在返回List的对应位置将是null + * + * @param String + * keys + * @return List 值得集合 + * */ + public List mget(String... keys) { + Jedis jedis = getJedis(); + List str = jedis.mget(keys); + returnJedis(jedis); + return str; + } + + /** + * 批量存储记录 + * + * @param String + * keysvalues 例:keysvalues="key1","value1","key2","value2"; + * @return String 状态码 + * */ + public String mset(String... keysvalues) { + Jedis jedis = getJedis(); + String str = jedis.mset(keysvalues); + returnJedis(jedis); + return str; + } + + /** + * 获取key对应的值的长度 + * + * @param String + * key + * @return value值得长度 + * */ + public long strlen(String key) { + Jedis jedis = getJedis(); + long len = jedis.strlen(key); + returnJedis(jedis); + return len; + } + + // *******************************************Lists*******************************************// + /** + * List长度 + * + * @param String + * key + * @return 长度 + * */ + public long llen(String key) { + return llen(SafeEncoder.encode(key)); + } + + /** + * List长度 + * + * @param byte[] key + * @return 长度 + * */ + public long llen(byte[] key) { + // ShardedJedis sjedis = getShardedJedis(); + Jedis sjedis = getJedis(); + long count = sjedis.llen(key); + returnJedis(sjedis); + return count; + } + + /** + * 覆盖操作,将覆盖List中指定位置的值 + * + * @param byte[] key + * @param int index 位置 + * @param byte[] value 值 + * @return 状态码 + * */ + public String lset(byte[] key, int index, byte[] value) { + Jedis jedis = getJedis(); + String status = jedis.lset(key, index, value); + returnJedis(jedis); + return status; + } + + /** + * 覆盖操作,将覆盖List中指定位置的值 + * + * @param key + * @param int index 位置 + * @param String + * value 值 + * @return 状态码 + * */ + public String lset(String key, int index, String value) { + return lset(SafeEncoder.encode(key), index, SafeEncoder.encode(value)); + } + + /** + * 在value的相对位置插入记录 + * + * @param key + * @param LIST_POSITION + * 前面插入或后面插入 + * @param String + * pivot 相对位置的内容 + * @param String + * value 插入的内容 + * @return 记录总数 + * */ + public long linsert(String key, LIST_POSITION where, String pivot, String value) { + return linsert(SafeEncoder.encode(key), where, SafeEncoder.encode(pivot), SafeEncoder.encode(value)); + } + + /** + * 在指定位置插入记录 + * + * @param String + * key + * @param LIST_POSITION + * 前面插入或后面插入 + * @param byte[] pivot 相对位置的内容 + * @param byte[] value 插入的内容 + * @return 记录总数 + * */ + public long linsert(byte[] key, LIST_POSITION where, byte[] pivot, byte[] value) { + Jedis jedis = getJedis(); + long count = jedis.linsert(key, where, pivot, value); + returnJedis(jedis); + return count; + } + + /** + * 获取List中指定位置的值 + * + * @param String + * key + * @param int index 位置 + * @return 值 + * **/ + public String lindex(String key, int index) { + return SafeEncoder.encode(lindex(SafeEncoder.encode(key), index)); + } + + /** + * 获取List中指定位置的值 + * + * @param byte[] key + * @param int index 位置 + * @return 值 + * **/ + public byte[] lindex(byte[] key, int index) { + // ShardedJedis sjedis = getShardedJedis(); + Jedis sjedis = getJedis(); + byte[] value = sjedis.lindex(key, index); + returnJedis(sjedis); + return value; + } + + /** + * 将List中的第一条记录移出List + * + * @param String + * key + * @return 移出的记录 + * */ + public String lpop(String key) { + return SafeEncoder.encode(lpop(SafeEncoder.encode(key))); + } + + /** + * 将List中的第一条记录移出List + * + * @param byte[] key + * @return 移出的记录 + * */ + public byte[] lpop(byte[] key) { + Jedis jedis = getJedis(); + byte[] value = jedis.lpop(key); + returnJedis(jedis); + return value; + } + + /** + * 将List中最后第一条记录移出List + * + * @param byte[] key + * @return 移出的记录 + * */ + public String rpop(String key) { + Jedis jedis = getJedis(); + String value = jedis.rpop(key); + returnJedis(jedis); + return value; + } + + /** + * 向List尾部追加记录 + * + * @param String + * key + * @param String + * value + * @return 记录总数 + * */ + public long lpush(String key, String value) { + return lpush(SafeEncoder.encode(key), SafeEncoder.encode(value)); + } + + /** + * 向List头部追加记录 + * + * @param String + * key + * @param String + * value + * @return 记录总数 + * */ + public long rpush(String key, String value) { + Jedis jedis = getJedis(); + long count = jedis.rpush(key, value); + returnJedis(jedis); + return count; + } + + /** + * 向List头部追加记录 + * + * @param String + * key + * @param String + * value + * @return 记录总数 + * */ + public long rpush(byte[] key, byte[] value) { + Jedis jedis = getJedis(); + long count = jedis.rpush(key, value); + returnJedis(jedis); + return count; + } + + /** + * 向List中追加记录 + * + * @param byte[] key + * @param byte[] value + * @return 记录总数 + * */ + public long lpush(byte[] key, byte[] value) { + Jedis jedis = getJedis(); + long count = jedis.lpush(key, value); + returnJedis(jedis); + return count; + } + + /** + * 获取指定范围的记录,可以做为分页使用 + * + * @param String + * key + * @param long start + * @param long end + * @return List + * */ + public List lrange(String key, long start, long end) { + // ShardedJedis sjedis = getShardedJedis(); + Jedis sjedis = getJedis(); + List list = sjedis.lrange(key, start, end); + returnJedis(sjedis); + return list; + } + + /** + * 获取指定范围的记录,可以做为分页使用 + * + * @param byte[] key + * @param int start + * @param int end 如果为负数,则尾部开始计算 + * @return List + * */ + public List lrange(byte[] key, int start, int end) { + // ShardedJedis sjedis = getShardedJedis(); + Jedis sjedis = getJedis(); + List list = sjedis.lrange(key, start, end); + returnJedis(sjedis); + return list; + } + + /** + * 删除List中c条记录,被删除的记录值为value + * + * @param byte[] key + * @param int c 要删除的数量,如果为负数则从List的尾部检查并删除符合的记录 + * @param byte[] value 要匹配的值 + * @return 删除后的List中的记录数 + * */ + public long lrem(byte[] key, int c, byte[] value) { + Jedis jedis = getJedis(); + long count = jedis.lrem(key, c, value); + returnJedis(jedis); + return count; + } + + /** + * 删除List中c条记录,被删除的记录值为value + * + * @param String + * key + * @param int c 要删除的数量,如果为负数则从List的尾部检查并删除符合的记录 + * @param String + * value 要匹配的值 + * @return 删除后的List中的记录数 + * */ + public long lrem(String key, int c, String value) { + return lrem(SafeEncoder.encode(key), c, SafeEncoder.encode(value)); + } + + /** + * 算是删除吧,只保留start与end之间的记录 + * + * @param byte[] key + * @param int start 记录的开始位置(0表示第一条记录) + * @param int end 记录的结束位置(如果为-1则表示最后一个,-2,-3以此类推) + * @return 执行状态码 + * */ + public String ltrim(byte[] key, int start, int end) { + Jedis jedis = getJedis(); + String str = jedis.ltrim(key, start, end); + returnJedis(jedis); + return str; + } + + /** + * 算是删除吧,只保留start与end之间的记录 + * + * @param String + * key + * @param int start 记录的开始位置(0表示第一条记录) + * @param int end 记录的结束位置(如果为-1则表示最后一个,-2,-3以此类推) + * @return 执行状态码 + * */ + public String ltrim(String key, int start, int end) { + return ltrim(SafeEncoder.encode(key), start, end); + } + +} diff --git a/src/main/java/com/nis/util/ServiceAndRDBIndexReal.java b/src/main/java/com/nis/util/ServiceAndRDBIndexReal.java index 08373f5..67837cb 100644 --- a/src/main/java/com/nis/util/ServiceAndRDBIndexReal.java +++ b/src/main/java/com/nis/util/ServiceAndRDBIndexReal.java @@ -2,11 +2,16 @@ package com.nis.util; import java.util.ArrayList; import java.util.HashMap; +import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.util.StringUtils; + +import com.nis.domain.MaatXmlExpr; /** * @@ -37,13 +42,13 @@ public class ServiceAndRDBIndexReal { * key是业务类型,value是业务类型对应的动作(action) */ private static Map serviceActionMap = new HashMap(); - + /** * 保存maat分发到阀门需要添加到域的属性:maat2Valve * Map> */ - private static Map> maatToValveMap = new HashMap>(); - + private static Map> maatToValveMap = new HashMap>(); + /** * 阀门保存的redis数据库Index,在seriveTable.properties中定义 */ @@ -113,33 +118,119 @@ public class ServiceAndRDBIndexReal { serviceDBIndexmap.put(Integer.parseInt(serviceDBIndex[0]), redisDbList); } } - + String maat2Valve = Configurations.getStringProperty("maat2Valve", ""); - if (maat2Valve!=null && !maat2Valve.trim().equals("")) { - String [] maat2ValveAry= maat2Valve.split(";"); + if (maat2Valve != null && !maat2Valve.trim().equals("")) { + String[] maat2ValveAry = maat2Valve.split(";"); for (String maat2ValveStr : maat2ValveAry) { - String [] serviceAndRegion = maat2ValveStr.split(":"); - if (serviceAndRegion!=null&&serviceAndRegion.length==2) { - String [] regionAndFields = serviceAndRegion[1].split("@"); - Map fieldMap = new HashMap(); - String [] fields = regionAndFields[1].split("&"); - //同一service有不同的域类型,多个之间用“|”分隔 + String[] serviceAndRegion = maat2ValveStr.split(":"); + if (serviceAndRegion != null && serviceAndRegion.length == 2) { + String[] regionAndFields = serviceAndRegion[1].split("@"); + Map fieldMap = new HashMap(); + String[] fields = regionAndFields[1].split("&"); + // 同一service有不同的域类型,多个之间用“|”分隔 if (regionAndFields[0].contains("|")) { - String [] regionTypeAry = regionAndFields[0].split("\\|"); + String[] regionTypeAry = regionAndFields[0].split("\\|"); for (String regionType : regionTypeAry) { fieldMap.put(regionType, fields); } - }else{ + } else { fieldMap.put(regionAndFields[0], fields); } - + maatToValveMap.put(Integer.parseInt(serviceAndRegion[0]), fieldMap); - + } } } } + public static void main(String[] args) { + getUnMaatTable(); + } + + public static void getUnMaatTable() { + Map typeTable = new HashMap(); + + String unMaatService = Configurations.getStringProperty("unMaatService", ""); + if (unMaatService != null && !unMaatService.trim().equals("")) { + String[] split = unMaatService.split(";"); + for (String str : split) { + String[] serviceAction = str.split(":"); + String serviceType = Configurations.getStringProperty(serviceAction[0], ""); + if (serviceType != null && !serviceType.trim().equals("")) { + String[] typeArrs = serviceType.split(";"); + for (String typeStr : typeArrs) { + String[] typeArr = typeStr.split(":"); + String tableNameArr[] = typeArr[1].split(","); + for (String tableName : tableNameArr) { + if (!typeTable.containsKey(Integer.parseInt(serviceAction[0]))) { + typeTable.put(Integer.parseInt(serviceAction[0]), tableName.toUpperCase()); + } else { + System.out.println(); + } + + unMaatSercieNameMap.put(Integer.parseInt(serviceAction[0]), tableName.toUpperCase()); + } + } + } + } + } + for (Integer service : typeTable.keySet()) { + List expressionList = ReadMaatXmlUtil.getMaatConfigByService(service).getExpressionList(); + for (MaatXmlExpr maatXmlExpr : expressionList) { + if (maatXmlExpr.getValueExpression() != null) { + String[] valSplit = maatXmlExpr.getValueExpression().split(";"); + int a=1; + for (int i = 0; i < valSplit.length; i++) { + if (valSplit[i].toLowerCase().contains("is_valid")) {// xml中是字符串的\t这里判断的时候需要转义为\\t,但是添加的时候需要添加\t不是\\t + System.out.println(service+"--"+typeTable.get(service) + "---" + a); + }else if (valSplit[i].toLowerCase().contains("[")){ + a++; + } + } + } + + } + } + + } + + public static void getMaatTable() { + Map> typeMap = new HashMap>(); + String service = Configurations.getStringProperty("service", ""); + if (service != null && !service.trim().equals("")) { + String[] split = service.split(";"); + for (String str : split) { + String[] serviceAction = str.split(":"); + serviceActionMap.put(Integer.valueOf(serviceAction[0]), Integer.valueOf(serviceAction[1])); + String type = Configurations.getStringProperty(serviceAction[0], ""); + if (type != null && !type.trim().equals("")) { + + String[] typeArrs = type.split(";"); + for (String typeStr : typeArrs) { + String[] typeArr = typeStr.split(":"); + int tableType = Integer.parseInt(typeArr[0]); + String tableNameArr[] = typeArr[1].split(","); + for (String tableName : tableNameArr) { + if (typeMap.containsKey(tableType)) { + typeMap.get(tableType).add(tableName.toUpperCase()); + } else { + Set list = new HashSet(); + list.add(tableName.toUpperCase()); + typeMap.put(tableType, list); + } + } + } + } + + } + } + for (Integer type : typeMap.keySet()) { + System.out.println(type + "----" + typeMap.get(type)); + } + } + /** * 根据业务类型获取这个 * @param service @@ -166,26 +257,27 @@ public class ServiceAndRDBIndexReal { if (tableName == null || tableName.trim().equals("")) { if (tableList.size() > 1) { logger.error("未从业务类型和表对应关系中,找到业务类型:{},配置类型:{}表名:{}对应的真实表名", service, type, tableName); - throw new RuntimeException("业务类型:"+service+",配置类型:"+type+"对应多个表,请输入具体的表名"); + throw new RuntimeException("业务类型:" + service + ",配置类型:" + type + "对应多个表,请输入具体的表名"); } else { return tableList.get(0); } } else { - //保存tableName在表名列表中的序号 + // 保存tableName在表名列表中的序号 int index = -1; for (int i = 0; i < tableList.size(); i++) { String str = tableList.get(i); if (str.toLowerCase().contains(tableName.toLowerCase())) { index = i; - } + } } - if (index!=-1&&tableList!=null) { - return tableList.get(index); + if (index != -1 && tableList != null) { + return tableList.get(index); } else { - logger.error("未从业务类型和表对应关系中,找到业务类型:{},配置类型:{}表名:{}对应的真实表名", service, type, tableName); - throw new RuntimeException("后台错误:未从业务类型和表对应关系中,找到业务类型:"+service+",配置类型:"+type+"表名:"+tableName+"对应的真实表名"); + logger.error("未从业务类型和表对应关系中,找到业务类型:{},配置类型:{}表名:{}对应的真实表名", service, type, tableName); + throw new RuntimeException( + "后台错误:未从业务类型和表对应关系中,找到业务类型:" + service + ",配置类型:" + type + "表名:" + tableName + "对应的真实表名"); } - + } } @@ -209,7 +301,6 @@ public class ServiceAndRDBIndexReal { return serviceActionMap.get(service); } - public static Map>> getSercieNameMap() { return sercieNameMap; } @@ -230,17 +321,17 @@ public class ServiceAndRDBIndexReal { return maatToValveMap; } - public static void setMaatToValveMap( - Map> maatToValveMap) { + public static void setMaatToValveMap(Map> maatToValveMap) { ServiceAndRDBIndexReal.maatToValveMap = maatToValveMap; } + /** * @param valveDBIndex the valveDBIndex to set */ public static void setValveDBIndex(Integer valveDBIndex) { ServiceAndRDBIndexReal.valveDBIndex = valveDBIndex; } - + /** * @return the valveDBIndex */ diff --git a/src/main/java/com/nis/web/service/restful/ConfigJedisServiceimpl.java b/src/main/java/com/nis/web/service/restful/ConfigJedisServiceimpl.java new file mode 100644 index 0000000..d03ae35 --- /dev/null +++ b/src/main/java/com/nis/web/service/restful/ConfigJedisServiceimpl.java @@ -0,0 +1,1328 @@ +package com.nis.web.service.restful; + +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; + +import com.nis.domain.MaatXmlConfig; +import com.nis.domain.MaatXmlExpr; +import com.nis.domain.MaatXmlSeq; +import com.nis.domain.restful.MaatConfig; +import com.nis.util.Configurations; +import com.nis.util.JedisUtils; +import com.nis.util.ReadMaatXmlUtil; +import com.nis.util.ServiceAndRDBIndexReal; + +import redis.clients.jedis.Jedis; +import redis.clients.jedis.Transaction; + +@Service() +public class ConfigJedisServiceimpl implements ConfigRedisService { + private static Logger logger = LoggerFactory.getLogger(ConfigJedisServiceimpl.class); + + public boolean saveUnMaatConfig(Map>> configMap) { + if (configMap != null && configMap.size() > 0) { + int count = 0; + Jedis resource = JedisUtils.getResource(0); + Transaction transaction = resource.multi(); + try { + for (Integer redisDBIndex : configMap.keySet()) { + if (redisDBIndex >= 0 && redisDBIndex < Configurations.getIntProperty("maxRedisDBIndex", 6)) { + transaction.select(redisDBIndex); + List> listMap = configMap.get(redisDBIndex); + if (listMap != null && listMap.size() > 0) { + String maatVersionStr = JedisUtils.get("MAAT_VERSION", redisDBIndex); + if (maatVersionStr == null) { + maatVersionStr = "0"; + } + if (maatVersionStr != null) { + Long maatVersion = Long.valueOf(maatVersionStr) + 1; + for (Map map : listMap) { + String serviceStr = map.get("service"); + int service = Integer.parseInt(serviceStr); + MaatXmlConfig maatXmlConfig = ReadMaatXmlUtil.getMaatConfigByService(service); + if (maatXmlConfig != null) { + List expressionList = maatXmlConfig.getExpressionList(); + String maatKey = null; + for (MaatXmlExpr maatXmlExpr : expressionList) { + if (0 == maatXmlExpr.getType().intValue()) { + StringBuffer keyBF = new StringBuffer(); + String[] keySplit = maatXmlExpr.getKeyExpression().split(";"); + for (String keyStr : keySplit) { + if (!StringUtils.isEmpty(keyStr) && keyStr.trim().startsWith("[")) { + keyStr = keyStr.trim().replace("[", "").replace("]", ""); + keyBF.append(map.get(keyStr)); + } else if (!StringUtils.isEmpty(keyStr) + && keyStr.trim().startsWith("{")) { + keyStr = keyStr.trim().replace("{", "").replace("}", ""); + if (keyStr.toLowerCase().contains("table_name")) { + String maatTableName = ServiceAndRDBIndexReal + .getUnMaatTableName(service); + if (maatTableName == null) { + throw new RuntimeException( + "后台错误:未从业务类型和表对应关系中,找到非maat配置业务类型:" + service + + "对应的真实表名"); + } else { + keyBF.append(maatTableName); + } + } + } else { + keyBF.append(keyStr.trim()); + } + } + StringBuffer valBF = new StringBuffer(); + String[] valSplit = maatXmlExpr.getValueExpression().split(";"); + for (String valStr : valSplit) { + if (!StringUtils.isEmpty(valStr) && valStr.trim().startsWith("[")) { + valStr = valStr.trim().replace("[", "").replace("]", ""); + valBF.append(map.get(valStr)); + } else if (valStr.equals(" ")) { + valBF.append(" "); + } else if (valStr.equals("\\t")) {// xml中是字符串的\t这里判断的时候需要转义为\\t,但是添加的时候需要添加\t不是\\t + valBF.append("\t"); + } else if (valStr.equals("\\n")) { + valBF.append("\n"); + } + } + maatKey = keyBF.toString(); + transaction.set(keyBF.toString().toUpperCase(), valBF.toString()); + logger.info("向{}号redis数据库添加了一条配置,key是{},value是{}", redisDBIndex, + keyBF.toString().toUpperCase(), valBF.toString()); + break; + } + } + for (MaatXmlExpr maatXmlExpr : expressionList) { + if (maatXmlExpr.getKeyExpression().toUpperCase() + .equals("MAAT_UPDATE_STATUS")) { + if (maatKey != null) { + String zset = maatKey.replace("EFFECTIVE_RULE:", "ADD,"); + transaction.zadd("MAAT_UPDATE_STATUS", maatVersion, zset); + logger.info("向{}号redis数据库更新了MAAT_UPDATE_STATUS,内容是{},SCORES是{}", + redisDBIndex, zset.toUpperCase(), maatVersion); + + } + } else if (maatXmlExpr.getKeyExpression().toUpperCase() + .equals("MAAT_RULE_TIMER")) { + if (maatKey != null) { + Double score = 0d;// 界面下发的配置没有超时时间所以这里设置为0 + transaction.zadd("MAAT_RULE_TIMER", score, maatKey); + logger.info("向{}号redis数据库更新了MAAT_RULE_TIMER,内容是{},SCORES是{}", + redisDBIndex, maatKey, score); + + } + } else if (maatXmlExpr.getKeyExpression().toUpperCase() + .equals("MAAT_VERSION_TIMER")) { + Long nowTime = new Date().getTime(); + nowTime = nowTime / 1000l; + Double score = nowTime.doubleValue();// 使用redis自带的time,得到当前时间的秒 + transaction.zadd("MAAT_VERSION_TIMER", score, maatVersion + ""); + logger.info("向{}号redis数据库更新了MAAT_VERSION_TIMER,内容是{},SCORES是{}", + redisDBIndex, maatVersion, score); + } + } + List seqList = maatXmlConfig.getSequenceList(); + for (MaatXmlSeq maatXmlSeq : seqList) { + String seqKey = maatXmlSeq.getSequenceKey(); + if (!seqKey.toUpperCase().equals("MAAT_VERSION")) { + Integer operation = maatXmlSeq.getOperation(); + if (operation == 1) { + transaction.incrBy(seqKey.toUpperCase(), 1l); + } + } + + } + } else { + throw new RuntimeException( + "后台错误:无法从maat.xml中获取业务类型" + service + "对应的规则,请检查业务类型是否正确"); + } + } + transaction.incrBy("MAAT_VERSION", 1l); + logger.info("向{}号redis数据库更新了MAAT_VERSION,更新后版本是{}", redisDBIndex, + Integer.valueOf(maatVersionStr) + 1); + count++; + } + } else { + throw new RuntimeException( + "后台错误:向" + redisDBIndex + "号redis库中添加配置时,未发现对应的配置信息,请检查配置参数是否正确"); + } + } else { + throw new RuntimeException("后台错误:redis数据库编号:" + redisDBIndex + "不正确,请检查数据库编号"); + } + } + if (count == configMap.size()) { + transaction.exec(); + return true; + } else { + transaction.discard(); + } + } catch (Exception e) { + transaction.discard(); + throw new RuntimeException("后台错误:保存非maat类配置发生了异常", e); + } finally { + // 释放连接到连接池 + JedisUtils.returnResource(resource); + } + } else { + throw new RuntimeException("后台错误:参数不能为空"); + } + return false; + } + + /** + * 下发配置成功后,需要更新编译,组,域等配置id的对应关系 + */ + private void addMaatRelation(Map> configMap, Transaction transaction) { + if (configMap != null && configMap.size() > 0) { + int idRelaRedisDBIndex = Configurations.getIntProperty("idRelaRedisDBIndex", 15); + transaction.select(idRelaRedisDBIndex); + for (Integer redisDBIndex : configMap.keySet()) { + if (redisDBIndex >= 0 && redisDBIndex < Configurations.getIntProperty("maxRedisDBIndex", 6)) { + List maatConfigList = configMap.get(redisDBIndex); + if (maatConfigList != null && maatConfigList.size() > 0) { + Map> compileAndGroupMap = new HashMap>(); + Map> groupAndCompileMap = new HashMap>(); + for (MaatConfig maatConfig : maatConfigList) { + String compileId = maatConfig.getCompileMap().get("compile_id"); + List> groupMapList = maatConfig.getGroupMapList(); + if (groupMapList != null && groupMapList.size() > 0) { + for (Map map : groupMapList) { + String cfgIdStr = redisDBIndex + ":COMPILEGROUP:" + map.get("compile_id"); + String groupIdStr = redisDBIndex + ":GROUPCOMPILE:" + map.get("group_id"); + // + map.get("compile_id"); + if (cfgIdStr != null && groupIdStr != null && !cfgIdStr.equals("") + && !groupIdStr.equals("")) { + if (compileAndGroupMap.containsKey(cfgIdStr.toUpperCase())) { + compileAndGroupMap.get(cfgIdStr.toUpperCase()) + .add(groupIdStr.toUpperCase()); + } else { + List list = new ArrayList(); + list.add(groupIdStr.toUpperCase()); + compileAndGroupMap.put(cfgIdStr.toUpperCase(), list); + } + if (groupAndCompileMap.containsKey(groupIdStr.toUpperCase())) { + groupAndCompileMap.get(groupIdStr.toUpperCase()) + .add(cfgIdStr.toUpperCase()); + } else { + List list = new ArrayList(); + list.add(cfgIdStr.toUpperCase()); + groupAndCompileMap.put(groupIdStr.toUpperCase(), list); + } + } + } + } + + Map> map = new HashMap>(); + int service = maatConfig.getService(); + MaatXmlConfig maatXmlConfig = ReadMaatXmlUtil.getMaatConfigByService(service); + addGroupAndRegionRelations(maatXmlConfig, service, 12, maatConfig.getIpRegionMapList(), map, + redisDBIndex, compileId); + addGroupAndRegionRelations(maatXmlConfig, service, 13, maatConfig.getNumRegionMapList(), + map, redisDBIndex, compileId); + addGroupAndRegionRelations(maatXmlConfig, service, 14, maatConfig.getStrRegionMapList(), + map, redisDBIndex, compileId); + addGroupAndRegionRelations(maatXmlConfig, service, 15, maatConfig.getStrStrRegionMapList(), + map, redisDBIndex, compileId); + addGroupAndRegionRelations(maatXmlConfig, service, 16, + maatConfig.getFileDigestRegionMapList(), map, redisDBIndex, compileId); + addGroupAndRegionRelations(maatXmlConfig, service, 17, + maatConfig.getFileLikeRegionMapList(), map, redisDBIndex, compileId); + addGroupAndRegionRelations(maatXmlConfig, service, 18, maatConfig.getIpClientRangeMapList(), + map, redisDBIndex, compileId); + + for (String groupIdStr : map.keySet()) { + List list = map.get(groupIdStr); + StringBuffer sb = new StringBuffer(); + if (list != null && list.size() > 0) { + for (String regionIdStr : list) { + sb.append(regionIdStr); + sb.append(";"); + } + } + + transaction.set(groupIdStr, sb.substring(0, sb.length() - 1));// 保存分组id和域id的关系(每个域配置,只会属于一个组) + } + + } + + for (String compile : compileAndGroupMap.keySet()) { + List list = compileAndGroupMap.get(compile); + StringBuffer sb = new StringBuffer(); + if (list != null && list.size() > 0) { + for (String groupIdStr : list) { + sb.append(groupIdStr); + sb.append(";"); + } + } + transaction.set(compile, sb.substring(0, sb.length() - 1));// 保存分组id和域id的关系(每个域配置,只会属于一个组) + } + for (String group : groupAndCompileMap.keySet()) { + List list = groupAndCompileMap.get(group); + StringBuffer sb = new StringBuffer(); + if (list != null && list.size() > 0) { + for (String compile : list) { + sb.append(compile); + sb.append(";"); + } + } + transaction.append(group, sb.substring(0, sb.length() - 1));// 保存分组id和域id的关系(每个域配置,只会属于一个组) + // redisTemplate.opsForValue().set(group, sb.substring(0, sb.length() - 1));// + // 保存分组id和域id的关系(每个域配置,只会属于一个组) + } + + } + } else { + throw new RuntimeException("后台错误:redis数据库编号:" + redisDBIndex + "不正确,请检查数据库编号"); + } + } + } else { + throw new RuntimeException("后台错误:参数不能为空"); + } + + } + + /** + * 单独找一个redis-db记录配置信息,方便实时统计程序获取所有配置的分类性质,标签等内容,(为什么实时统计不从配置库redisdb获取呢, + * 因为配置有多分发的情况,会发送到不同的redisdb,每个redisdb的配置条数不一定相同,有的配置所有的redisdb都有,有的只在某一个redisdb中有,实时统计程序不好获取配置这些配置内容, + * 最重要的是,前端机不需要这些属性,所以在配置库有可能不带分类性质,标签等属性,maat.xml如果配置了则有,没有配置则就没有这些属性.所以单独找一个reidsdb存放带分类性质,标签等属性的配置) + * @param configMap + */ + private void addStatisticsReal(Map> configMap, Transaction transaction) { + if (configMap != null && configMap.size() > 0) { + for (Integer redisDBIndex : configMap.keySet()) { + int redisStatisticsRealDBIndex = Configurations.getIntProperty("redisStatisticsRealDBIndex", 14); + if (redisStatisticsRealDBIndex >= 0 + && redisStatisticsRealDBIndex < Configurations.getIntProperty("maxRedisDBIndex", 16)) { + List list = configMap.get(redisDBIndex); + if (list != null && list.size() > 0) { + transaction.select(redisStatisticsRealDBIndex); + String redisStatisticsReal = Configurations.getStringProperty("redis-statisticsReal", + "[COMPILE_ID];\t;[SERVICE];\t;[ACTION];\t;[CONT_TYPE];\t;[ATTR_TYPE];\t;[CONT_LABEL];\t;[TASK_ID];\t;[AFFAIR_ID];\t;[DO_BLACKLIST];\t;[DO_LOG];\t;[EFFECTIVE_RANGE];\t;[START_TIME];\t;[END_TIME];\t;[USER_REGION];\t;[IS_VALID];\t;[GROUP_NUM];\t;[FATHER_CFG_ID];\t;[OP_TIME]"); + String[] redisStatisticsRealArr = redisStatisticsReal.split(";"); + + String maatVersionStr = JedisUtils.get("MAAT_VERSION", redisStatisticsRealDBIndex); + if (maatVersionStr == null) { + maatVersionStr = "0"; + } + if (maatVersionStr != null) { + Long maatVersion = Long.valueOf(maatVersionStr) + 1; + for (MaatConfig maatConfig : list) { + int service = maatConfig.getService(); + MaatXmlConfig maatXmlConfig = ReadMaatXmlUtil.getMaatConfigByService(service); + Map compileMap = maatConfig.getCompileMap(); + for (MaatXmlExpr maatXmlExpr : maatXmlConfig.getExpressionList()) { + if (10 == maatXmlExpr.getType().intValue()) { + StringBuffer keyBF = new StringBuffer(); + String[] keySplit = maatXmlExpr.getKeyExpression().split(";"); + for (String keyStr : keySplit) { + if (!StringUtils.isEmpty(keyStr) && keyStr.trim().startsWith("[")) { + keyStr = keyStr.trim().replace("[", "").replace("]", ""); + String keyVal = compileMap.get(keyStr); + if (keyVal != null && !keyVal.equals("")) { + keyBF.append(keyVal); + } else { + throw new RuntimeException( + "后台错误:未从map中获取到" + keyStr + "的值,无法拼接redisKey,请检查数据是否正确"); + } + } else if (!StringUtils.isEmpty(keyStr) && keyStr.trim().startsWith("{")) { + keyStr = keyStr.trim().replace("{", "").replace("}", ""); + if (keyStr.toLowerCase().contains("table_name")) { + String argTableName = compileMap.get("table_name"); + String maatTableName = ServiceAndRDBIndexReal.getMaatTableName( + service, 10, argTableName == null ? null : argTableName); + if (maatTableName == null) { + throw new RuntimeException("后台错误:未从业务类型和表对应关系中,找到业务类型:" + + service + ",配置类型:10,对应的真实表名"); + } else { + keyBF.append(maatTableName); + } + + } + + } else { + keyBF.append(keyStr.trim()); + } + } + StringBuffer valBF = new StringBuffer(); + for (String valStr : redisStatisticsRealArr) { + if (!StringUtils.isEmpty(valStr) && valStr.trim().startsWith("[")) { + valStr = valStr.trim().replace("[", "").replace("]", ""); + String val = compileMap.get(valStr.toLowerCase()); + if (val != null) { + valBF.append(val); + } else { + // 编译配置或分组配置 所有在maat.xml中配置的属性都不可以为空 + // if (!valStr.toLowerCase().equals("service")&&! + // valStr.toLowerCase().equals("action") + // &&!valStr.toLowerCase().equals("user_region") &&type==10) { + throw new RuntimeException( + "后台错误:未从map中获取到" + valStr + "的值,无法拼接redisValue,请检查数据是否正确"); + + } + } else if (valStr.equals("\t")) {// xml中是字符串的\t这里判断的时候需要转义为\\t,但是添加的时候需要添加\t不是\\t + valBF.append("\t"); + } else { + valBF.append(valStr.trim()); + } + } + String maatKey = keyBF.toString(); + transaction.set(maatKey.toUpperCase(), valBF.toString()); + String zset = maatKey.replace("EFFECTIVE_RULE:", "ADD,"); + transaction.zadd("MAAT_UPDATE_STATUS", maatVersion, zset); + + logger.info("向{}号redis数据库添加了一条配置,key是{},value是{}", redisDBIndex, + maatKey.toUpperCase(), valBF.toString()); + break; + } + + } + } + transaction.incrBy("MAAT_VERSION", 1l); + } + } else { + throw new RuntimeException( + "后台错误:向" + redisStatisticsRealDBIndex + "号redis库中添加配置时,未发现对应的配置信息,请检查配置参数是否正确"); + } + + } else { + throw new RuntimeException("后台错误:redis数据库编号:" + redisStatisticsRealDBIndex + "不正确,请检查数据库编号"); + } + break;// configMap中所有的value都是相同的,在记录配置新增或者取消时只记录一次即可 + } + } + } + + /** + * 封装组id与域id对应关系并添加到对象中 + * @param regionMapList + * @param compileAndGroupRelations + */ + private Map> addGroupAndRegionRelations(MaatXmlConfig maatXmlConfig, int service, int type, + List> regionMapList, Map> groupAndRegionMap, int redisDBIndex, + String compileId) { + if (regionMapList != null && regionMapList.size() > 0) { + for (Map map : regionMapList) { + List expressionList = maatXmlConfig.getExpressionList(); + String maatKey = null; + for (MaatXmlExpr maatXmlExpr : expressionList) { + if (type == maatXmlExpr.getType().intValue()) { + StringBuffer keyBF = new StringBuffer(); + String[] keySplit = maatXmlExpr.getKeyExpression().split(";"); + for (String keyStr : keySplit) { + if (!StringUtils.isEmpty(keyStr) && keyStr.trim().startsWith("[")) { + keyStr = keyStr.trim().replace("[", "").replace("]", ""); + keyBF.append(map.get(keyStr)); + } else if (!StringUtils.isEmpty(keyStr) && keyStr.trim().startsWith("{")) { + keyStr = keyStr.trim().replace("{", "").replace("}", ""); + if (keyStr.toLowerCase().contains("table_name")) { + String argTableName = map.get("table_name"); + String maatTableName = ServiceAndRDBIndexReal.getMaatTableName(service, type, + argTableName == null ? null : argTableName); + if (maatTableName == null) { + throw new RuntimeException( + "后台错误:未从业务类型和表对应关系中,找到业务类型:" + service + ",配置类型:" + type + ",对应的真实表名"); + } else { + keyBF.append(maatTableName); + } + } + + } else { + keyBF.append(keyStr.trim()); + } + } + maatKey = keyBF.toString(); + break; + } + } + // String groupIdStr = redisDBIndex + ":GROUPREGION:" + map.get("group_id") + + // compileId; + String groupIdStr = redisDBIndex + ":GROUPREGION:" + map.get("group_id"); + if (groupAndRegionMap.containsKey(groupIdStr.toUpperCase())) { + groupAndRegionMap.get(groupIdStr.toUpperCase()).add(redisDBIndex + ":" + maatKey.toUpperCase()); + } else { + List list = new ArrayList(); + list.add(redisDBIndex + ":" + maatKey.toUpperCase()); + groupAndRegionMap.put(groupIdStr.toUpperCase(), list); + } + } + } + return groupAndRegionMap; + + } + + @Override + public boolean saveMaatConfig(Map> configMap) { + if (configMap != null && configMap.size() > 0) { + int count = 0; + Jedis resource = JedisUtils.getResource(0); + Transaction transaction = resource.multi(); + try { + for (Integer redisDBIndex : configMap.keySet()) { + if (redisDBIndex >= 0 && redisDBIndex < Configurations.getIntProperty("maxRedisDBIndex", 6)) { + transaction.select(redisDBIndex); + String maatVersionStr = JedisUtils.get("MAAT_VERSION", redisDBIndex); + if (maatVersionStr == null) { + maatVersionStr = "0"; + } + if (maatVersionStr != null) { + Long maatVersion = Long.valueOf(maatVersionStr) + 1; + List maatConfigList = configMap.get(redisDBIndex); + if (maatConfigList != null && maatConfigList.size() > 0) { + for (MaatConfig maatConfig : maatConfigList) { + int service = maatConfig.getService(); + MaatXmlConfig maatXmlConfig = ReadMaatXmlUtil.getMaatConfigByService(service); + setConfig(maatConfig, maatXmlConfig, maatVersion, service, transaction, + redisDBIndex); + } + transaction.incrBy("MAAT_VERSION", 1l); + logger.info("向{}号redis数据库更新了MAAT_VERSION,更新后版本是{}", redisDBIndex, + Integer.valueOf(maatVersionStr) + 1); + count++; + } else { + throw new RuntimeException( + "后台错误:向" + redisDBIndex + "号redis库中添加配置时,未发现对应的配置信息,请检查配置参数是否正确"); + } + } + } else { + throw new RuntimeException("后台错误:redis数据库编号:" + redisDBIndex + "不正确,请检查数据库编号"); + } + } + if (count == configMap.size()) { + addMaatRelation(configMap, transaction); + addStatisticsReal(configMap, transaction); + transaction.exec(); + return true; + }else { + transaction.exec(); + } + } catch (Exception e) { + transaction.discard(); + throw new RuntimeException("后台错误:保存maat类配置发生了异常", e); + } finally { + // 释放连接到连接池 + JedisUtils.returnResource(resource); + } + } else { + throw new RuntimeException("后台错误:参数不能为空"); + } + return false; + + } + + /** + * 将编译,分组,域等配置拆开分别添加到redis中 + * @param maatConfig + * @param maatXmlConfig + * @param maatVersion + * @param service + * @param redisTemplate + * @param redisDBIndex + */ + public void setConfig(MaatConfig maatConfig, MaatXmlConfig maatXmlConfig, Long maatVersion, int service, + Transaction transaction, Integer redisDBIndex) { + Map compileMap = maatConfig.getCompileMap(); + String compileId = compileMap.get("compile_id"); + if (compileMap != null && compileMap.size() > 0) { + setCommonConfig(maatXmlConfig, compileMap, 10, maatVersion.doubleValue(), service, transaction, + redisDBIndex, null);// 10代表是编译配置 + } else { + throw new RuntimeException( + "后台错误:无法从参数中获取" + redisDBIndex + "号redis库,业务类型为:" + service + "的编译配置信息,请检查配置参数是否正确"); + } + + List> groupMapList = maatConfig.getGroupMapList(); + if (groupMapList != null && groupMapList.size() > 0) { + for (Map map : groupMapList) { + setCommonConfig(maatXmlConfig, map, 11, maatVersion.doubleValue(), service, transaction, redisDBIndex, + compileId);// 11代表是分组配置 + } + } else { + throw new RuntimeException( + "后台错误:无法从参数中获取" + redisDBIndex + "号redis库,业务类型为:" + service + "的分组配置信息,请检查配置参数是否正确"); + } + + List> ipRegionMapList = maatConfig.getIpRegionMapList(); + if (ipRegionMapList != null && ipRegionMapList.size() > 0) { + for (Map map : ipRegionMapList) { + setCommonConfig(maatXmlConfig, map, 12, maatVersion.doubleValue(), service, transaction, redisDBIndex, + null);// 12代表是ip类域配置 + } + } + List> numRegionMapList = maatConfig.getNumRegionMapList(); + if (numRegionMapList != null && numRegionMapList.size() > 0) { + for (Map map : numRegionMapList) { + setCommonConfig(maatXmlConfig, map, 13, maatVersion.doubleValue(), service, transaction, redisDBIndex, + null);// 13代表是数值类配置 + } + } + List> strRegionMapList = maatConfig.getStrRegionMapList(); + if (strRegionMapList != null && strRegionMapList.size() > 0) { + for (Map map : strRegionMapList) { + setCommonConfig(maatXmlConfig, map, 14, maatVersion.doubleValue(), service, transaction, redisDBIndex, + null);// 14代表是字符串类域配置 + } + } + List> strStrRegionMapList = maatConfig.getStrStrRegionMapList(); + if (strStrRegionMapList != null && strStrRegionMapList.size() > 0) { + for (Map map : strStrRegionMapList) { + setCommonConfig(maatXmlConfig, map, 15, maatVersion.doubleValue(), service, transaction, redisDBIndex, + null);// 15代表是增强字符串类域配置 + } + } + List> fileDigestRegionMapList = maatConfig.getFileDigestRegionMapList(); + if (fileDigestRegionMapList != null && fileDigestRegionMapList.size() > 0) { + for (Map map : fileDigestRegionMapList) { + setCommonConfig(maatXmlConfig, map, 16, maatVersion.doubleValue(), service, transaction, redisDBIndex, + null);// 16代表是文件摘要类域配置 + } + } + List> fileLikeRegionMapList = maatConfig.getFileLikeRegionMapList(); + if (fileLikeRegionMapList != null && fileLikeRegionMapList.size() > 0) { + for (Map map : fileLikeRegionMapList) { + setCommonConfig(maatXmlConfig, map, 17, maatVersion.doubleValue(), service, transaction, redisDBIndex, + null);// 17代表是文本相似性域配置 + } + } + + List> ipclientList = maatConfig.getIpClientRangeMapList(); + if (ipclientList != null && ipclientList.size() > 0) { + for (Map map : ipclientList) { + setCommonConfig(maatXmlConfig, map, 18, maatVersion.doubleValue(), service, transaction, redisDBIndex, + null);// 18代表是区域ip域配置 + } + } + + // updateCommonKey(maatXmlConfig); + } + + /** + * 将整理好的数据添加到redis中 + * @param maatXmlConfig + * @param map + * @param type + * @param maatVersion + * @param service + * @param redisTemplate + * @param redisDBIndex + */ + public void setCommonConfig(MaatXmlConfig maatXmlConfig, Map map, int type, Double maatVersion, + int service, Transaction transaction, Integer redisDBIndex, String compileId) { + if (maatXmlConfig != null && map != null && map.size() > 0) { + List expressionList = maatXmlConfig.getExpressionList(); + String maatKey = null; + for (MaatXmlExpr maatXmlExpr : expressionList) { + if (type == maatXmlExpr.getType().intValue()) { + StringBuffer keyBF = new StringBuffer(); + String[] keySplit = maatXmlExpr.getKeyExpression().split(";"); + for (String keyStr : keySplit) { + if (!StringUtils.isEmpty(keyStr) && keyStr.trim().startsWith("[")) { + keyStr = keyStr.trim().replace("[", "").replace("]", ""); + String keyVal = map.get(keyStr); + if (keyVal != null && !keyVal.equals("")) { + keyBF.append(keyVal); + } else { + throw new RuntimeException("后台错误:未从map中获取到" + keyStr + "的值,无法拼接redisKey,请检查数据是否正确"); + } + if (type == 11 && keyStr.toLowerCase().equals("group_id")) { + keyBF.append(compileId); + } + } else if (!StringUtils.isEmpty(keyStr) && keyStr.trim().startsWith("{")) { + keyStr = keyStr.trim().replace("{", "").replace("}", ""); + if (keyStr.toLowerCase().contains("table_name")) { + String argTableName = map.get("table_name"); + String maatTableName = ServiceAndRDBIndexReal.getMaatTableName(service, type, + argTableName == null ? null : argTableName); + if (maatTableName == null) { + throw new RuntimeException( + "后台错误:未从业务类型和表对应关系中,找到业务类型:" + service + ",配置类型:" + type + ",对应的真实表名"); + } else { + keyBF.append(maatTableName); + } + + } + + } else { + keyBF.append(keyStr.trim()); + } + } + StringBuffer valBF = new StringBuffer(); + String[] valSplit = maatXmlExpr.getValueExpression().split(";"); + for (String valStr : valSplit) { + if (!StringUtils.isEmpty(valStr) && valStr.trim().startsWith("[")) { + valStr = valStr.trim().replace("[", "").replace("]", ""); + String val = map.get(valStr); + if (val != null) { + valBF.append(val); + } else { + if (type != 10 && type != 11) {// 域配置 + if (valStr.toLowerCase().equals("service") || valStr.toLowerCase().equals("action") + || valStr.toLowerCase().equals("user_region")) {// 域配置中只有这三个可以为空 + // 删除前面的\t + } else {// 其他不可以为空 + throw new RuntimeException( + "后台错误:未从map中获取到" + valStr + "的值,无法拼接redisValue,请检查数据是否正确"); + } + } else {// 编译配置或分组配置 所有在maat.xml中配置的属性都不可以为空 + // if (!valStr.toLowerCase().equals("service")&&! + // valStr.toLowerCase().equals("action") + // &&!valStr.toLowerCase().equals("user_region") &&type==10) { + throw new RuntimeException( + "后台错误:未从map中获取到" + valStr + "的值,无法拼接redisValue,请检查数据是否正确"); + } + } + } else if (valStr.equals(" ")) { + valBF.append(" "); + } else if (valStr.equals("\\t")) {// xml中是字符串的\t这里判断的时候需要转义为\\t,但是添加的时候需要添加\t不是\\t + valBF.append("\t"); + } else if (valStr.equals("\\n")) { + valBF.append("\n"); + } else { + valBF.append(valStr.trim()); + } + } + maatKey = keyBF.toString(); + transaction.set(maatKey.toUpperCase(), valBF.toString()); + logger.info("向{}号redis数据库添加了一条配置,key是{},value是{}", redisDBIndex, maatKey.toUpperCase(), + valBF.toString()); + break; + } + + } + for (MaatXmlExpr maatXmlExpr : expressionList) { + if (maatXmlExpr.getKeyExpression().toUpperCase().equals("MAAT_UPDATE_STATUS")) { + if (maatKey != null) { + String zset = maatKey.replace("EFFECTIVE_RULE:", "ADD,"); + transaction.zadd("MAAT_UPDATE_STATUS", maatVersion, zset); + logger.info("向{}号redis数据库更新了MAAT_UPDATE_STATUS,内容是{},SCORES是{}", redisDBIndex, + zset.toUpperCase(), maatVersion); + } + } else if (maatXmlExpr.getKeyExpression().toUpperCase().equals("MAAT_RULE_TIMER")) { + if (maatKey != null) { + Double score = 0d;// 界面下发的配置没有超时时间所以这里设置为0 + transaction.zadd("MAAT_RULE_TIMER", score, maatKey); + logger.info("向{}号redis数据库更新了MAAT_RULE_TIMER,内容是{},SCORES是{}", redisDBIndex, maatKey, score); + + } + } else if (maatXmlExpr.getKeyExpression().toUpperCase().equals("MAAT_VERSION_TIMER")) { + Long nowTime = new Date().getTime(); + nowTime = nowTime / 1000l; + Double score = nowTime.doubleValue();// 使用redis自带的time,得到当前时间的秒 + transaction.zadd("MAAT_VERSION_TIMER", score, maatVersion + ""); + logger.info("向{}号redis数据库更新了MAAT_VERSION_TIMER,内容是{},SCORES是{}", redisDBIndex, maatVersion, score); + } + } + } else { + if (maatXmlConfig == null) { + throw new RuntimeException("后台错误:无法获取业务类型" + service + "对应的maat规则,请检查maat.xml"); + } else { + throw new RuntimeException("后台错误:后台组装的配置信息有误,请联系管理员检查"); + } + } + } + + public Long getIncrId(String key) { + Long id = JedisUtils.incrBy(key, 1l, 0); + logger.info("从0号redis数据库获取{}成功,自增后的值是{}", key, id); + return id; + } + + @Override + public boolean delUnMaatConfig(Map>> idMap) { + if (idMap != null && idMap.size() > 0) { + int count = 0; + Jedis resource = JedisUtils.getResource(0); + Transaction transaction = resource.multi(); + try { + for (Integer redisDBIndex : idMap.keySet()) { + transaction.select(redisDBIndex); + Map> serviceConfigMap = idMap.get(redisDBIndex); + if (serviceConfigMap != null && serviceConfigMap.size() > 0) { + + String maatVersionStr = JedisUtils.get("MAAT_VERSION", redisDBIndex); + if (maatVersionStr == null) { + throw new RuntimeException("后台错误:从" + redisDBIndex + + "号redis库中获取MAAT_VERSION的值为null,redis中不存在该值,请联系开发人员检查删除逻辑是否正确或redis数据是否出现了异常"); + } + if (maatVersionStr != null) { + Long maatVersion = Long.valueOf(maatVersionStr) + 1; + for (Integer service : serviceConfigMap.keySet()) { + List compileIdList = serviceConfigMap.get(service); + if (compileIdList != null && compileIdList.size() > 0) { + for (Long id : compileIdList) { + MaatXmlConfig maatXmlConfig = ReadMaatXmlUtil.getMaatConfigByService(service); + if (maatXmlConfig != null) { + List expressionList = maatXmlConfig.getExpressionList(); + String maatKey = null; + for (MaatXmlExpr maatXmlExpr : expressionList) { + if (0 == maatXmlExpr.getType().intValue()) { + StringBuffer keyBF = new StringBuffer(); + String[] keySplit = maatXmlExpr.getKeyExpression().split(";"); + for (String keyStr : keySplit) { + if (!StringUtils.isEmpty(keyStr) + && keyStr.toUpperCase().equals("EFFECTIVE_RULE")) { + keyStr = "OBSOLETE_RULE"; + keyBF.append(keyStr.trim()); + } else if (!StringUtils.isEmpty(keyStr) + && keyStr.trim().startsWith("[")) { + // keyStr = keyStr.trim().replace("[", "").replace("]", ""); + keyBF.append(id); + } else if (!StringUtils.isEmpty(keyStr) + && keyStr.trim().startsWith("{")) { + keyStr = keyStr.trim().replace("{", "").replace("}", ""); + if (keyStr.toLowerCase().contains("table_name")) { + String maatTableName = ServiceAndRDBIndexReal + .getUnMaatTableName(service); + if (maatTableName == null) { + throw new RuntimeException( + "后台错误:未从业务类型和表对应关系中,找到非maat配置业务类型:" + + service + "对应的真实表名"); + } else { + keyBF.append(maatTableName); + } + } + } else { + keyBF.append(keyStr.trim()); + } + } + maatKey = keyBF.toString(); + String oldKey = maatKey.replace("OBSOLETE_RULE", "EFFECTIVE_RULE"); + if (JedisUtils.exists(oldKey.toString().toUpperCase(), + redisDBIndex)) { + transaction.rename(oldKey.toString().toUpperCase(), + keyBF.toString().toUpperCase()); + logger.info("向{}号redis数据库修改了一条配置,修改前key是{},修改后key是{}", + redisDBIndex, oldKey.toString().toUpperCase(), + keyBF.toString().toUpperCase()); + break; + } else { + throw new RuntimeException("后台错误:" + redisDBIndex + + "号redis库中不存在key=" + oldKey + "请检查id映射关系是否正确"); + } + } + } + for (MaatXmlExpr maatXmlExpr : expressionList) { + if (maatXmlExpr.getKeyExpression().toUpperCase() + .equals("MAAT_UPDATE_STATUS")) { + if (maatKey != null) { + String zset = maatKey.replace("OBSOLETE_RULE:", "DEL,"); + transaction.zadd("MAAT_UPDATE_STATUS", maatVersion, zset); + logger.info("向{}号redis数据库更新了MAAT_UPDATE_STATUS,内容是{},SCORES是{}", + redisDBIndex, zset.toUpperCase(), maatVersion); + } + } else if (maatXmlExpr.getKeyExpression().toUpperCase() + .equals("MAAT_RULE_TIMER")) { + if (maatKey != null) { + Double score = 0d;// 界面下发的配置没有超时时间所以这里设置为0 + transaction.zadd("MAAT_RULE_TIMER", score, maatKey); + logger.info("向{}号redis数据库更新了MAAT_RULE_TIMER,内容是{},SCORES是{}", + redisDBIndex, maatKey, score); + } + } else if (maatXmlExpr.getKeyExpression().toUpperCase() + .equals("MAAT_VERSION_TIMER")) { + Long nowTime = new Date().getTime(); + nowTime = nowTime / 1000l; + Double score = nowTime.doubleValue();// 使用redis自带的time,得到当前时间的秒 + transaction.zadd("MAAT_VERSION_TIMER", score, maatVersion + ""); + logger.info("向{}号redis数据库更新了MAAT_VERSION_TIMER,内容是{},SCORES是{}", + redisDBIndex, maatVersion, score); + } + } + List seqList = maatXmlConfig.getSequenceList(); + for (MaatXmlSeq maatXmlSeq : seqList) { + // setRedisDataBase(maatXmlSeq.getRedisDB(), + // redisTemplate); + String seqKey = maatXmlSeq.getSequenceKey(); + if (!seqKey.toUpperCase().equals("MAAT_VERSION")) { + Integer operation = maatXmlSeq.getOperation(); + if (operation == 1) { + transaction.incrBy(seqKey.toUpperCase(), 1l); + // redisTemplate.boundValueOps(seqKey.toUpperCase()).increment(1l); + } + } + + } + } else { + throw new RuntimeException( + "后台错误:无法从maat.xml中获取业务类型" + service + "对应的规则,请检查业务类型是否正确"); + } + } + transaction.incrBy("MAAT_VERSION", 1l); + // redisTemplate.boundValueOps("MAAT_VERSION").increment(1l); + logger.info("向{}号redis数据库更新了MAAT_VERSION,更新后版本是{}", redisDBIndex, + Integer.valueOf(maatVersionStr) + 1); + count++; + } else { + throw new RuntimeException("后台错误:无法从参数中获取" + redisDBIndex + "号redis库,业务类型为:" + + service + "的配置id信息,请检查配置参数是否正确"); + } + } + + } + } else { + throw new RuntimeException("后台错误:向" + redisDBIndex + "号redis库中添加配置时,未发现对应的配置信息,请检查配置参数是否正确"); + } + + } + if (count == idMap.size()) { + transaction.exec(); + return true; + } else { + transaction.discard(); + } + } catch (Exception e) { + transaction.discard(); + throw new RuntimeException("后台错误:删除非maat类配置发生了异常", e); + } finally { + // 释放连接到连接池 + JedisUtils.returnResource(resource); + } + } else { + throw new RuntimeException("后台错误:参数信息有误,请检查!"); + } + return false; + } + + @Override + public boolean delMaatConfig(Map>> idMap) { + if (idMap != null && idMap.size() > 0) { + int count = 0; + Jedis resource = JedisUtils.getResource(0); + Transaction transaction = resource.multi(); + try { + int idRelaRedisDBIndex = Configurations.getIntProperty("idRelaRedisDBIndex", 15); + for (Integer redisDBIndex : idMap.keySet()) { + transaction.select(redisDBIndex); + Map> serviceConfigMap = idMap.get(redisDBIndex); + if (serviceConfigMap != null && serviceConfigMap.size() > 0) { + String maatVersionStr = JedisUtils.get("MAAT_VERSION", redisDBIndex); + if (maatVersionStr == null) { + throw new RuntimeException("后台错误:从" + redisDBIndex + + "号redis库中获取MAAT_VERSION的值为null,redis中不存在该值,请联系开发人员检查删除逻辑是否正确或redis数据是否出现了异常"); + } + if (maatVersionStr != null) { + Long maatVersion = Long.valueOf(maatVersionStr) + 1; + for (Integer service : serviceConfigMap.keySet()) { + MaatXmlConfig maatXmlConfig = ReadMaatXmlUtil.getMaatConfigByService(service); + removeConfig(serviceConfigMap.get(service), maatXmlConfig, maatVersion, service, + transaction, redisDBIndex, idRelaRedisDBIndex); + + } + transaction.incrBy("MAAT_VERSION", 1l); + logger.info("向{}号redis数据库更新了MAAT_VERSION,更新后版本是{}", redisDBIndex, + Integer.valueOf(maatVersionStr) + 1); + count++; + } + } else { + throw new RuntimeException("后台错误:向" + redisDBIndex + "号redis库中添加配置时,未发现对应的配置信息,请检查配置参数是否正确"); + } + } + if (count == idMap.size()) { + delMaatRelation(idMap, transaction); + delStatisticsReal(idMap, transaction); + transaction.exec(); + return true; + } else { + transaction.discard(); + } + + } catch (Exception e) { + transaction.discard(); + throw new RuntimeException("后台错误:删除maat类配置发生了异常", e); + } finally { + // 释放连接到连接池 + JedisUtils.returnResource(resource); + } + } else { + throw new RuntimeException("后台错误:参数信息有误,请检查!"); + } + return false; + } + + /** + * 删除maat类配置 + * @param idList 配置id集合 + * @param maatXmlConfig maat.xml中关于当前业务类型的key和value写法的对象 + * @param maatVersion 版本号 + * @param service 业务类型 + * @param redisTemplate + * @param maatRelation id对应关系对象 + */ + private void removeConfig(List idList, MaatXmlConfig maatXmlConfig, Long maatVersion, int service, + Transaction transaction, int redisDBIndex, int idRelaRedisDBIndex) { + + if (idList != null && idList.size() > 0 && maatXmlConfig != null) { + for (Long id : idList) { + removeCompileAndGroupConfig(maatXmlConfig, id + "", 10, maatVersion.doubleValue(), service, transaction, + redisDBIndex, null);// 10代表是编译配置 + String compileStr = redisDBIndex + ":COMPILEGROUP:" + id; + // 获取当前编译下所有的分组id + String groupCompileStrs = JedisUtils.get(compileStr, idRelaRedisDBIndex); + if (groupCompileStrs != null && !groupCompileStrs.trim().equals("")) { + String[] split = groupCompileStrs.split(";"); + for (String groupId : split) { + String compileGroupStr = JedisUtils.get(groupId, idRelaRedisDBIndex); + if (compileGroupStr != null && !compileGroupStr.trim().equals("")) { + String[] compileGroupArr = compileGroupStr.split(";");// 获取组对应的编译id + if (compileGroupArr != null && compileGroupArr.length == 1) {// 如果只有一个编译id且与上面的编译id相同则说明未被分组复用,可以将其下的所有域置失效,否则不处理域配置,只把编译,分组关系置为无效 + for (String compileId : compileGroupArr) { + if (compileId.equals(compileStr)) {// + String groupRegionKey = groupId.replace("GROUPCOMPILE", "GROUPREGION"); + String regionStr = JedisUtils.get(groupRegionKey, idRelaRedisDBIndex); + if (regionStr != null && !regionStr.trim().equals("")) { + String[] regionKeyArr = regionStr.split(";"); + if (regionKeyArr != null && regionKeyArr.length > 0) { + removeRegionConfig(maatXmlConfig, regionKeyArr, + maatVersion.doubleValue(), service, transaction, redisDBIndex); + } + } else { + throw new RuntimeException( + "后台错误:从" + idRelaRedisDBIndex + "号redis库中获取" + groupRegionKey + + "的值为null,redis中不存在该值,请联系开发人员检查删除逻辑是否正确或redis数据是否出现了异常"); + + } + } + } + } + removeCompileAndGroupConfig(maatXmlConfig, + groupId.replace(redisDBIndex + ":GROUPCOMPILE:", ""), 11, maatVersion.doubleValue(), + service, transaction, redisDBIndex, id + "");// 11代表是分组配置 + } else { + throw new RuntimeException("后台错误:从" + idRelaRedisDBIndex + "号redis库中获取" + groupId + + "的值为null,redis中不存在该值,请联系开发人员检查删除逻辑是否正确或redis数据是否出现了异常"); + + } + } + } else { + throw new RuntimeException("后台错误:从" + idRelaRedisDBIndex + "号redis库中获取" + compileStr + + "的值为null,redis中不存在该值,请联系开发人员检查删除逻辑是否正确或redis数据是否出现了异常"); + } + } + } else { + throw new RuntimeException("后台错误:无法获取内存中记录的id映射关系,无法获取业务类型" + service + "对应的maat规则或传入的配置id有误,请检查!"); + } + } + + /** + * 删除maat配置时,对redis进行相关操作,主要是重命名key和记录相关状态 + * @param maatXmlConfig + * @param idList + * @param type + * @param maatVersion + * @param service + * @param redisTemplate + */ + private void removeCompileAndGroupConfig(MaatXmlConfig maatXmlConfig, String id, int type, Double maatVersion, + int service, Transaction transaction, int redisDBIndex, String compileId) { + if (maatXmlConfig != null) { + List expressionList = maatXmlConfig.getExpressionList(); + String maatKey = null; + for (MaatXmlExpr maatXmlExpr : expressionList) { + if (type == maatXmlExpr.getType().intValue()) { + StringBuffer keyBF = new StringBuffer(); + String[] keySplit = maatXmlExpr.getKeyExpression().split(";"); + for (String keyStr : keySplit) { + if (!StringUtils.isEmpty(keyStr) && keyStr.trim().startsWith("[")) { + keyStr = keyStr.trim().replace("[", "").replace("]", ""); + keyBF.append(id); + } else if (!StringUtils.isEmpty(keyStr) && keyStr.trim().startsWith("{")) { + keyStr = keyStr.trim().replace("{", "").replace("}", ""); + if (keyStr.toLowerCase().contains("table_name")) { + String maatTableName = ServiceAndRDBIndexReal.getMaatTableName(service, type, null); + if (maatTableName == null) { + throw new RuntimeException( + "后台错误:未从业务类型和表对应关系中,找到业务类型:" + service + ",配置类型:" + type + ",对应的真实表名"); + } else { + keyBF.append(maatTableName); + } + } + + } else { + keyBF.append(keyStr.trim()); + } + } + String oldKey = keyBF.toString().toUpperCase(); + if (compileId != null) { + oldKey += compileId; + } + maatKey = oldKey.replace("EFFECTIVE_RULE", "OBSOLETE_RULE"); + if (JedisUtils.exists(oldKey, redisDBIndex)) { + transaction.rename(oldKey, maatKey.toUpperCase()); + logger.info("向{}号redis数据库修改了一条配置,修改前key是{},修改后key是{}", redisDBIndex, oldKey, + maatKey.toUpperCase()); + break; + } else { + throw new RuntimeException("后台错误:" + redisDBIndex + "号redis库中不存在key=" + oldKey + + "请检查id映射关系是否正确,或该配置已经被取消,已经被取消的配置不可再次取消,否则将抛出异常"); + } + } + } + for (MaatXmlExpr maatXmlExpr : expressionList) { + if (maatXmlExpr.getKeyExpression().toUpperCase().equals("MAAT_UPDATE_STATUS")) { + if (maatKey != null) { + String zset = maatKey.replace("OBSOLETE_RULE:", "DEL,"); + + transaction.zadd("MAAT_UPDATE_STATUS", maatVersion, zset); + + logger.info("向{}号redis数据库更新了MAAT_UPDATE_STATUS,内容是{},SCORES是{}", redisDBIndex, + zset.toUpperCase(), maatVersion); + + } + + } else if (maatXmlExpr.getKeyExpression().toUpperCase().equals("MAAT_RULE_TIMER")) { + if (maatKey != null) { + Double score = 0d;// 界面下发的配置没有超时时间所以这里设置为0 + transaction.zadd("MAAT_RULE_TIMER", score, maatKey); + logger.info("向{}号redis数据库更新了MAAT_RULE_TIMER,内容是{},SCORES是{}", redisDBIndex, maatKey, score); + + } + } else if (maatXmlExpr.getKeyExpression().toUpperCase().equals("MAAT_VERSION_TIMER")) { + Long nowTime = new Date().getTime(); + nowTime = nowTime / 1000l; + Double score = nowTime.doubleValue();// 使用redis自带的time,得到当前时间的秒 + transaction.zadd("MAAT_VERSION_TIMER", score, maatVersion + ""); + logger.info("向{}号redis数据库更新了MAAT_VERSION_TIMER,内容是{},SCORES是{}", redisDBIndex, maatVersion, score); + + } + } + } else { + throw new RuntimeException("后台错误:无法获取业务类型" + service + "对应的maat规则,请检查!"); + } + } + + /** + * 删除域配置,重名key,记录相关信息MAAT_UPDATE_STATUS,MAAT_RULE_TIMER等 + * @param maatXmlConfig + * @param regionArr + * @param maatVersion + * @param service + * @param redisTemplate + * @param redisDBIndex + */ + private void removeRegionConfig(MaatXmlConfig maatXmlConfig, String[] regionArr, Double maatVersion, int service, + Transaction transaction, int redisDBIndex) { + if (maatXmlConfig != null && regionArr != null && regionArr.length > 0) { + List expressionList = maatXmlConfig.getExpressionList(); + String maatKey = null; + for (String oldKey : regionArr) { + oldKey = oldKey.replace(redisDBIndex + ":", ""); + maatKey = oldKey.replace("EFFECTIVE_RULE", "OBSOLETE_RULE"); + if (JedisUtils.exists(oldKey, redisDBIndex)) { + transaction.rename(oldKey, maatKey.toUpperCase()); + logger.info("向{}号redis数据库修改了一条配置,修改前key是{},修改后key是{}", redisDBIndex, oldKey, maatKey.toUpperCase()); + } else { + throw new RuntimeException("后台错误:" + redisDBIndex + "号redis库中不存在key=" + oldKey + "请检查id映射关系是否正确"); + } + + for (MaatXmlExpr maatXmlExpr : expressionList) { + if (maatXmlExpr.getKeyExpression().toUpperCase().equals("MAAT_UPDATE_STATUS")) { + if (maatKey != null) { + String zset = maatKey.replace("OBSOLETE_RULE:", "DEL,"); + transaction.zadd("MAAT_UPDATE_STATUS", maatVersion, zset); + logger.info("向{}号redis数据库更新了MAAT_UPDATE_STATUS,内容是{},SCORES是{}", redisDBIndex, + zset.toUpperCase(), maatVersion); + + } + + } else if (maatXmlExpr.getKeyExpression().toUpperCase().equals("MAAT_RULE_TIMER")) { + if (maatKey != null) { + Double score = 0d;// 界面下发的配置没有超时时间所以这里设置为0 + transaction.zadd("MAAT_RULE_TIMER", score, maatKey); + logger.info("向{}号redis数据库更新了MAAT_RULE_TIMER,内容是{},SCORES是{}", redisDBIndex, maatKey, score); + + } + } else if (maatXmlExpr.getKeyExpression().toUpperCase().equals("MAAT_VERSION_TIMER")) { + Long nowTime = new Date().getTime(); + nowTime = nowTime / 1000l; + Double score = nowTime.doubleValue();// 使用redis自带的time,得到当前时间的秒 + transaction.zadd("MAAT_VERSION_TIMER", score, maatVersion + ""); + logger.info("向{}号redis数据库更新了MAAT_VERSION_TIMER,内容是{},SCORES是{}", redisDBIndex, maatVersion, + score); + + } + } + } + } else { + if (maatXmlConfig == null) { + throw new RuntimeException("后台错误:无法获取业务类型" + service + "对应的maat规则,请检查maat.xml"); + } else { + int idRelaRedisDBIndex = Configurations.getIntProperty("idRelaRedisDBIndex", 15); + throw new RuntimeException("后台错误:" + idRelaRedisDBIndex + "号redis库中存储的分组和域关系有误,请联系管理员检查数据"); + } + + } + } + + /** + * 取消分类性质,标签等信息 + */ + private void delStatisticsReal(Map>> idMap, Transaction transaction) { + if (idMap != null && idMap.size() > 0) { + int redisStatisticsRealDBIndex = Configurations.getIntProperty("redisStatisticsRealDBIndex", 14); + transaction.select(redisStatisticsRealDBIndex); + String maatVersionStr = JedisUtils.get("MAAT_VERSION", redisStatisticsRealDBIndex); + if (maatVersionStr == null) { + throw new RuntimeException("后台错误:从" + redisStatisticsRealDBIndex + + "号redis库中获取MAAT_VERSION的值为null,redis中不存在该值,请联系开发人员检查删除逻辑是否正确或redis数据是否出现了异常"); + } + double maatVersion = Double.valueOf(maatVersionStr) + 1D; + for (Integer redisDBIndex : idMap.keySet()) { + if (redisStatisticsRealDBIndex >= 0 + && redisStatisticsRealDBIndex < Configurations.getIntProperty("maxRedisDBIndex", 16)) { + Map> map = idMap.get(redisDBIndex); + if (map != null && map.size() > 0) { + for (Integer service : map.keySet()) { + String maatTableName = ServiceAndRDBIndexReal.getMaatTableName(service, 10, null); + List idList = map.get(service); + if (idList != null && idList.size() > 0) { + for (Long compileId : idList) { + String effectiveRuleKey = "EFFECTIVE_RULE:" + maatTableName + "," + compileId; + if (JedisUtils.exists(effectiveRuleKey.toUpperCase(), redisStatisticsRealDBIndex)) { + transaction.rename(effectiveRuleKey.toUpperCase(), effectiveRuleKey + .toUpperCase().replace("EFFECTIVE_RULE", "OBSOLETE_RULE")); + logger.info("向{}号redis数据库修改了一条配置,修改前key是{},修改后key是:{}", + redisStatisticsRealDBIndex, effectiveRuleKey.toUpperCase(), + effectiveRuleKey.toUpperCase().replace("EFFECTIVE_RULE", + "OBSOLETE_RULE")); + + String zset = effectiveRuleKey.replace("EFFECTIVE_RULE:", "DEL,"); + transaction.zadd("MAAT_UPDATE_STATUS", maatVersion, zset); + logger.info("向{}号redis数据库更新了MAAT_UPDATE_STATUS,内容是{},SCORES是{}", + redisStatisticsRealDBIndex, zset.toUpperCase(), maatVersion); + } else { + throw new RuntimeException("后台错误:从" + redisStatisticsRealDBIndex + "号redis库中判断" + + effectiveRuleKey.toUpperCase() + + "组和域关系时不存在,请联系开发人员检查删除逻辑是否正确或redis数据是否出现了异常"); + + } + + } + } else { + throw new RuntimeException("后台错误:删除配置时,配置id不能为空,请联系开发人员检查删除逻辑是否正确"); + } + + } + transaction.incrBy("MAAT_VERSION", 1l); + logger.info("向{}号redis数据库更新了MAAT_VERSION,更新后版本是{}", redisStatisticsRealDBIndex, + Integer.valueOf(maatVersionStr) + 1); + + } else { + throw new RuntimeException("后台错误:删除配置时,配置id不能为空,请联系开发人员检查删除逻辑是否正确"); + } + + } else { + throw new RuntimeException("后台错误:redis数据库编号:" + redisStatisticsRealDBIndex + "不正确,请检查数据库编号"); + } + break;// 因为所有的value都是相同的所以只取消一次就可以了 + } + + } + + } + + /** + * 删除配置成功后,需要更新编译,组,域等配置id的对应关系 + * @param idMap + */ + private void delMaatRelation(Map>> idMap, Transaction transaction) { + if (idMap != null && idMap.size() > 0) { + int idRelaRedisDBIndex = Configurations.getIntProperty("idRelaRedisDBIndex", 15); + transaction.select(idRelaRedisDBIndex); + for (Integer redisDBIndex : idMap.keySet()) { + if (redisDBIndex >= 0 && redisDBIndex < Configurations.getIntProperty("maxRedisDBIndex", 6)) { + Map> map = idMap.get(redisDBIndex); + if (map != null && map.size() > 0) { + for (Integer service : map.keySet()) { + List idList = map.get(service); + if (idList != null && idList.size() > 0) { + for (Long compileId : idList) { + String compileStr = redisDBIndex + ":COMPILEGROUP:" + compileId; + String groupCompileStr = JedisUtils.get(compileStr, idRelaRedisDBIndex);// 根据编译id获取该编译下的分组关系 + if (groupCompileStr != null && !groupCompileStr.equals("")) { + String[] groupCompileStrSplit = groupCompileStr.split(";");// 得到分组关系 + for (String groupCompile : groupCompileStrSplit) {// 遍历所有分组关系 + // String compileGroupStr = redisTemplate.opsForValue() + // .get(groupCompile.toUpperCase());// 获取当前分组关系对应的编译信息 + + String compileGroupStr = JedisUtils.get(groupCompile.toUpperCase(), + idRelaRedisDBIndex);// 获取当前分组关系对应的编译信息 + + if (compileGroupStr != null && !compileGroupStr.equals("")) { + String[] compileGroupStrSplit = compileGroupStr.split(";"); + if (compileGroupStrSplit != null && compileGroupStrSplit.length == 1 + && compileGroupStr.equals(compileStr.toUpperCase())) {// 当前的分组关系只属于当前的compileid,说明没有被分组复用,需要将编译配置,分组关系,域配置,置无效 + if (compileGroupStrSplit[0].toUpperCase() + .equals(compileStr.toUpperCase())) { + String groupRegion = groupCompile.replaceAll("GROUPCOMPILE", + "GROUPREGION"); + if (JedisUtils.exists(groupRegion, idRelaRedisDBIndex)) { + transaction.del(groupRegion);// 删除组对应的域 + } else { + throw new RuntimeException("后台错误:从" + idRelaRedisDBIndex + + "号redis库中判断" + groupRegion + + "组和域关系时不存在,请联系开发人员检查删除逻辑是否正确或redis数据是否出现了异常"); + + } + + if (JedisUtils.exists(groupCompile.toUpperCase(), + idRelaRedisDBIndex)) { + transaction.del(groupCompile.toUpperCase());// 删除当前组所对应的编译 + } else { + throw new RuntimeException("后台错误:从" + idRelaRedisDBIndex + + "号redis库中判断" + groupCompile.toUpperCase() + + "组和域关系时不存在,请联系开发人员检查删除逻辑是否正确或redis数据是否出现了异常"); + + } + + } + } else {// 当前的分组被复用了,属于多个编译,需要将当前的分组关系置为无效 + Set groupCompileSet = new HashSet(); + for (String compileGroup : compileGroupStrSplit) { + if (!compileGroup.equals(compileStr.toUpperCase())) { + groupCompileSet.add(compileGroup); + } + } + StringBuffer sb = new StringBuffer(); + // 更新组对应的编译 + for (String str : groupCompileSet) { + sb.append(str); + sb.append(";"); + } + transaction.set(groupCompile, sb.substring(0, sb.length() - 1)); + } + } else { + throw new RuntimeException("后台错误:从" + idRelaRedisDBIndex + "号redis库中获取" + + groupCompile.toUpperCase() + + "的值为null,redis中不存在该值,请联系开发人员检查删除逻辑是否正确或redis数据是否出现了异常"); + + } + } + if (JedisUtils.exists(compileStr.toUpperCase(), idRelaRedisDBIndex)) { + transaction.del(compileStr.toUpperCase());// 删除编译下面所有的组 + } + + } else { + throw new RuntimeException("后台错误:从" + idRelaRedisDBIndex + "号redis库中获取" + + compileStr + "的值为null,redis中不存在该值,请联系开发人员检查删除逻辑是否正确或redis数据是否出现了异常"); + + } + } + } + } + } + } else { + throw new RuntimeException("后台错误:redis数据库编号:" + redisDBIndex + "不正确,请检查数据库编号"); + } + } + } else { + throw new RuntimeException("后台错误:参数不能为空"); + } + } +} diff --git a/src/main/java/com/nis/web/service/restful/ConfigRedisServiceimpl.java b/src/main/java/com/nis/web/service/restful/ConfigRedisServiceimpl.java index 9956e47..dfc173e 100644 --- a/src/main/java/com/nis/web/service/restful/ConfigRedisServiceimpl.java +++ b/src/main/java/com/nis/web/service/restful/ConfigRedisServiceimpl.java @@ -26,7 +26,7 @@ import com.nis.web.dao.impl.BaseRedisDao; import com.nis.web.service.SpringContextHolder; @Service() -public class ConfigRedisServiceimpl implements ConfigRedisService { +public class ConfigRedisServiceimpl {// implements ConfigRedisService private static Logger logger = LoggerFactory.getLogger(ConfigRedisServiceimpl.class); @Transactional @@ -452,7 +452,6 @@ public class ConfigRedisServiceimpl implements ConfigRedisService { } - @Override @Transactional public boolean saveMaatConfig(Map> configMap) { if (configMap != null && configMap.size() > 0) { @@ -707,9 +706,9 @@ public class ConfigRedisServiceimpl implements ConfigRedisService { } } } else { - if(maatXmlConfig==null) { + if (maatXmlConfig == null) { throw new RuntimeException("后台错误:无法获取业务类型" + service + "对应的maat规则,请检查maat.xml"); - }else { + } else { throw new RuntimeException("后台错误:后台组装的配置信息有误,请联系管理员检查"); } } @@ -734,7 +733,6 @@ public class ConfigRedisServiceimpl implements ConfigRedisService { return id; } - @Override @Transactional public boolean delUnMaatConfig(Map>> idMap) { if (idMap != null && idMap.size() > 0) { @@ -881,7 +879,6 @@ public class ConfigRedisServiceimpl implements ConfigRedisService { return false; } - @Override @Transactional public boolean delMaatConfig(Map>> idMap) { if (idMap != null && idMap.size() > 0) { @@ -1136,13 +1133,13 @@ public class ConfigRedisServiceimpl implements ConfigRedisService { } } } else { - if(maatXmlConfig==null) { + if (maatXmlConfig == null) { throw new RuntimeException("后台错误:无法获取业务类型" + service + "对应的maat规则,请检查maat.xml"); - }else { + } else { int idRelaRedisDBIndex = Configurations.getIntProperty("idRelaRedisDBIndex", 15); - throw new RuntimeException("后台错误:"+idRelaRedisDBIndex+"号redis库中存储的分组和域关系有误,请联系管理员检查数据"); + throw new RuntimeException("后台错误:" + idRelaRedisDBIndex + "号redis库中存储的分组和域关系有误,请联系管理员检查数据"); } - + } } @@ -1176,9 +1173,10 @@ public class ConfigRedisServiceimpl implements ConfigRedisService { redisTemplate.rename(effectiveRuleKey.toUpperCase(), effectiveRuleKey .toUpperCase().replace("EFFECTIVE_RULE", "OBSOLETE_RULE")); logger.info("向{}号redis数据库修改了一条配置,修改前key是{},修改后key是:{}", - redisStatisticsRealDBIndex, effectiveRuleKey.toUpperCase(), effectiveRuleKey - .toUpperCase().replace("EFFECTIVE_RULE", "OBSOLETE_RULE")); - + redisStatisticsRealDBIndex, effectiveRuleKey.toUpperCase(), + effectiveRuleKey.toUpperCase().replace("EFFECTIVE_RULE", + "OBSOLETE_RULE")); + String zset = effectiveRuleKey.replace("EFFECTIVE_RULE:", "DEL,"); redisTemplate.boundZSetOps("MAAT_UPDATE_STATUS").add(zset, maatVersion); logger.info("向{}号redis数据库更新了MAAT_UPDATE_STATUS,内容是{},SCORES是{}", diff --git a/src/main/resources/applicationContext-redis.xml b/src/main/resources/applicationContext-redis.xml index b0bb91d..8d1d7c5 100644 --- a/src/main/resources/applicationContext-redis.xml +++ b/src/main/resources/applicationContext-redis.xml @@ -25,6 +25,15 @@ + + + + + + + + +