From 7664ba49025a6c549885fc6019e4d3c1886f45a6 Mon Sep 17 00:00:00 2001
From: dangsn <dangsn@chicecm.com>
Date: 星期五, 07 六月 2024 14:26:16 +0800
Subject: [PATCH] 调整项目BUG

---
 Source/plt-web/plt-web-parent/plt-web/src/main/java/com/vci/web/redis/RedisService.java |  361 +++++++++++++++++++++++++++++++++++++-------------
 1 files changed, 264 insertions(+), 97 deletions(-)

diff --git a/Source/plt-web/plt-web-parent/plt-web/src/main/java/com/vci/web/redis/RedisService.java b/Source/plt-web/plt-web-parent/plt-web/src/main/java/com/vci/web/redis/RedisService.java
index e7a5a8e..ed55283 100644
--- a/Source/plt-web/plt-web-parent/plt-web/src/main/java/com/vci/web/redis/RedisService.java
+++ b/Source/plt-web/plt-web-parent/plt-web/src/main/java/com/vci/web/redis/RedisService.java
@@ -1,25 +1,28 @@
 package com.vci.web.redis;
 
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.TimeUnit;
+import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.data.redis.core.BoundSetOperations;
-import org.springframework.data.redis.core.HashOperations;
-import org.springframework.data.redis.core.RedisTemplate;
-import org.springframework.data.redis.core.ValueOperations;
+import org.springframework.data.geo.Distance;
+import org.springframework.data.geo.Metrics;
+import org.springframework.data.geo.Point;
+import org.springframework.data.redis.core.*;
+import org.springframework.data.redis.core.script.DefaultRedisScript;
+import org.springframework.data.redis.core.script.RedisScript;
+import org.springframework.data.redis.serializer.RedisSerializer;
+import org.springframework.data.redis.serializer.StringRedisSerializer;
 import org.springframework.stereotype.Component;
+
+import java.io.IOException;
+import java.util.*;
+import java.util.concurrent.TimeUnit;
 
 /**
  * spring redis 宸ュ叿绫�
- * 
- * @author wang1
+ * @author dangsn
  **/
 @SuppressWarnings(value = { "unchecked", "rawtypes" })
 @Component
+@Slf4j
 public class RedisService
 {
     @Autowired(required = false)
@@ -31,8 +34,7 @@
      * @param key 缂撳瓨鐨勯敭鍊�
      * @param value 缂撳瓨鐨勫��
      */
-    public <T> void setCacheObject(final String key, final T value)
-    {
+    public <T> void setCacheObject(final String key, final T value) {
         redisTemplate.opsForValue().set(key, value);
     }
 
@@ -44,8 +46,7 @@
      * @param timeout 鏃堕棿
      * @param timeUnit 鏃堕棿棰楃矑搴�
      */
-    public <T> void setCacheObject(final String key, final T value, final Long timeout, final TimeUnit timeUnit)
-    {
+    public <T> void setCacheObject(final String key, final T value, final Long timeout, final TimeUnit timeUnit) {
         redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
     }
 
@@ -69,8 +70,7 @@
      * @param unit 鏃堕棿鍗曚綅
      * @return true=璁剧疆鎴愬姛锛沠alse=璁剧疆澶辫触
      */
-    public boolean expire(final String key, final long timeout, final TimeUnit unit)
-    {
+    public boolean expire(final String key, final long timeout, final TimeUnit unit) {
         return redisTemplate.expire(key, timeout, unit);
     }
 
@@ -91,8 +91,7 @@
      * @param key 閿�
      * @return true 瀛樺湪 false涓嶅瓨鍦�
      */
-    public Boolean hasKey(String key)
-    {
+    public Boolean hasKey(String key) {
         return redisTemplate.hasKey(key);
     }
 
@@ -102,8 +101,7 @@
      * @param key 缂撳瓨閿��
      * @return 缂撳瓨閿�煎搴旂殑鏁版嵁
      */
-    public <T> T getCacheObject(final String key)
-    {
+    public <T> T getCacheObject(final String key) {
         ValueOperations<String, T> operation = redisTemplate.opsForValue();
         return operation.get(key);
     }
@@ -111,7 +109,8 @@
     /**
      * 鍒犻櫎鍗曚釜瀵硅薄
      *
-     * @param key
+     * @param key 鍙互
+     * @return  鍒犻櫎鏄惁鎴愬姛
      */
     public boolean deleteObject(final String key)
     {
@@ -122,7 +121,7 @@
      * 鍒犻櫎闆嗗悎瀵硅薄
      *
      * @param collection 澶氫釜瀵硅薄
-     * @return
+     * @return 鍒犻櫎鐨勪釜鏁�
      */
     public long deleteObject(final Collection collection)
     {
@@ -130,50 +129,14 @@
     }
 
     /**
-     * list鐨勯暱搴�
-     *
-     * @param key 缂撳瓨鐨勯敭鍊�
-     * @return 缂撳瓨鐨勫璞�
-     */
-    public <T> Long listSize(final String key)
-    {
-        return redisTemplate.opsForList().size(key);
-    }
-
-    /**
-     * 浠庡乏杈瑰彇鍑轰竴涓猯ist鍏冪礌
-     *
-     * @param key 缂撳瓨鐨勯敭鍊�
-     * @return 缂撳瓨鐨勫璞�
-     */
-    public <T> Object leftPop(final String key)
-    {
-        return redisTemplate.opsForList().leftPop(key);
-    }
-
-    /**
-     * 浠庡彸杈圭紦瀛楲ist鏁版嵁
+     * 缂撳瓨List鏁版嵁
      *
      * @param key 缂撳瓨鐨勯敭鍊�
      * @param dataList 寰呯紦瀛樼殑List鏁版嵁
      * @return 缂撳瓨鐨勫璞�
      */
-    public <T> long setCacheList(final String key, final List<T> dataList)
-    {
+    public <T> long setCacheList(final String key, final List<T> dataList) {
         Long count = redisTemplate.opsForList().rightPushAll(key, dataList);
-        return count == null ? 0 : count;
-    }
-
-    /**
-     * 鍒犻櫎list涓厓绱爒alue
-     * @param key
-     * @param value
-     * @param <T>
-     * @return
-     */
-    public <T> long deleteCacheListByKeyAndValue(final String key, final T value)
-    {
-        Long count = redisTemplate.opsForList().remove(key,0,value);
         return count == null ? 0 : count;
     }
 
@@ -188,8 +151,6 @@
         return redisTemplate.opsForList().range(key, 0, -1);
     }
 
-
-
     /**
      * 缂撳瓨Set
      *
@@ -197,36 +158,21 @@
      * @param dataSet 缂撳瓨鐨勬暟鎹�
      * @return 缂撳瓨鏁版嵁鐨勫璞�
      */
-    public <T> BoundSetOperations<String, T> setCacheSet(final String key, final Set<T> dataSet)
-    {
+    public <T> BoundSetOperations<String, T> setCacheSet(final String key, final Set<T> dataSet) {
         BoundSetOperations<String, T> setOperation = redisTemplate.boundSetOps(key);
         Iterator<T> it = dataSet.iterator();
         while (it.hasNext())
         {
             setOperation.add(it.next());
         }
-        String i = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
-                "<Datas>\n" +
-                "\t<Data code=\"A1100012\" deptLevel=\"寮�鍙戦儴闂�#娴嬭瘯閮ㄩ棬\">\n" +
-                "\t\t<prop sName=\"渚涘簲鍟嗗悕绉癨" tName =\"渚涘簲鍟嗗悕绉�1\" >\n" +
-                "\t\t\t鍖椾含瀹忓崥杩滆揪绉戞妧鏈夐檺鍏徃2\n" +
-                "\t\t</prop>\n" +
-                "\t\t<prop sName=\"鎴峰ご\" tName =\"鎴峰ご1\">\n" +
-                "\t\t\t1111100012\n" +
-                "\t\t</prop>\n" +
-                "\t\t<prop sName=\"鑱旂郴浜篭" tName=\"鑱旂郴浜�1\">\n" +
-                "\t\t\t璋㈠啗2\n" +
-                "\t\t</prop>\n" +
-                "\t</Data>\n" +
-                "</Datas>";
         return setOperation;
     }
 
     /**
      * 鑾峰緱缂撳瓨鐨剆et
      *
-     * @param key
-     * @return
+     * @param key key
+     * @return 闆嗗悎鐨勫唴瀹�
      */
     public <T> Set<T> getCacheSet(final String key)
     {
@@ -236,11 +182,10 @@
     /**
      * 缂撳瓨Map
      *
-     * @param key
-     * @param dataMap
+     * @param key key
+     * @param dataMap 鏁版嵁鏄犲皠
      */
-    public <T> void setCacheMap(final String key, final Map<String, T> dataMap)
-    {
+    public <T> void setCacheMap(final String key, final Map<String, T> dataMap) {
         if (dataMap != null) {
             redisTemplate.opsForHash().putAll(key, dataMap);
         }
@@ -249,8 +194,8 @@
     /**
      * 鑾峰緱缂撳瓨鐨凪ap
      *
-     * @param key
-     * @return
+     * @param key key
+     * @return 鏄犲皠
      */
     public <T> Map<String, T> getCacheMap(final String key)
     {
@@ -264,8 +209,7 @@
      * @param hKey Hash閿�
      * @param value 鍊�
      */
-    public <T> void setCacheMapValue(final String key, final String hKey, final T value)
-    {
+    public <T> void setCacheMapValue(final String key, final String hKey, final T value) {
         redisTemplate.opsForHash().put(key, hKey, value);
     }
 
@@ -276,8 +220,7 @@
      * @param hKey Hash閿�
      * @return Hash涓殑瀵硅薄
      */
-    public <T> T getCacheMapValue(final String key, final String hKey)
-    {
+    public <T> T getCacheMapValue(final String key, final String hKey) {
         HashOperations<String, String, T> opsForHash = redisTemplate.opsForHash();
         return opsForHash.get(key, hKey);
     }
@@ -289,19 +232,243 @@
      * @param hKeys Hash閿泦鍚�
      * @return Hash瀵硅薄闆嗗悎
      */
-    public <T> List<T> getMultiCacheMapValue(final String key, final Collection<Object> hKeys)
-    {
+    public <T> List<T> getMultiCacheMapValue(final String key, final Collection<Object> hKeys) {
         return redisTemplate.opsForHash().multiGet(key, hKeys);
     }
 
     /**
      * 鑾峰緱缂撳瓨鐨勫熀鏈璞″垪琛�
-     * 
+     *
      * @param pattern 瀛楃涓插墠缂�
      * @return 瀵硅薄鍒楄〃
      */
-    public Collection<String> keys(final String pattern)
-    {
+    public Collection<String> keys(final String pattern) {
         return redisTemplate.keys(pattern);
     }
+
+    /**
+     * 璁剧疆鍒嗗竷寮忛攣
+     * @param key 閿佺殑key
+     * @param value 鍊�
+     * @return true琛ㄧず瀛樺湪锛宖alse琛ㄧず涓嶅瓨鍦�
+     */
+    public synchronized Boolean setNX(final String key, final String value) throws Exception{
+        Object obj = null;
+        try {
+            obj = redisTemplate.execute((RedisCallback<Object>) connection -> {
+                StringRedisSerializer serializer = new StringRedisSerializer();
+                Boolean success = connection.setNX(serializer.serialize(key), serializer.serialize(value));
+                connection.close();
+                return success;
+            });
+        } catch (Exception e) {
+            log.error("setNX redis error, key : {} - {}", key,e);
+            throw e;
+        }
+        return obj != null ? (Boolean) obj : false;
+    }
+
+    /**
+     * 璁剧疆鍒嗗竷寮忛攣锛岃秴鏃堕棿鍗曚綅绉�
+     * @param key 閿佺殑key
+     * @param value 鍊�
+     * @param timeOut 瓒呮椂鏃堕棿
+     * @return true琛ㄧず瀛樺湪锛宖alse琛ㄧず涓嶅瓨鍦�
+     */
+    public synchronized Boolean setNX(final String key, final String value,long timeOut) throws Exception {
+        boolean b = this.setNX(key,value);
+        redisTemplate.expire(key,timeOut,TimeUnit.SECONDS);
+        return b;
+    }
+
+    /**
+     * 鍒犻櫎閿�
+     * @param key 閿佺殑key
+     */
+    public void unlock(final String key) {
+        redisTemplate.delete(key);
+    }
+
+    /**
+     * 鑷噺 澶т簬绛変簬0
+     * @param key 閿佺殑key
+     * @return Boolean
+     */
+    public Boolean decrement(final String key) {
+        return redisTemplate.opsForValue().decrement(key) >= 0;
+    }
+    public Boolean decrement(final String key, long count) {
+        return redisTemplate.opsForValue().decrement(key,count) >= 0;
+    }
+
+    /**
+     * 鑷噺
+     * @param key 閿佺殑key
+     * @return Boolean
+     */
+    public Long decrementLong(final String key) {
+        return redisTemplate.opsForValue().decrement(key);
+    }
+    /**
+     * 鑷
+     * @param key 閿佺殑key
+     * @return Boolean
+     */
+    public Long increment(final String key) {
+        return redisTemplate.opsForValue().increment(key);
+    }
+    public Long increment(final String key, long count) {
+        return redisTemplate.opsForValue().increment(key,count);
+    }
+
+    /**
+     * 鍓嶇紑鍖归厤鍒犻櫎
+     * @param keyPrefix key鍓嶇紑
+     */
+    public Boolean deleteByPrefix(final String keyPrefix) {
+
+        List<String> list = new LinkedList<>();
+        ScanOptions build = ScanOptions.scanOptions().match(keyPrefix+":*").count(5000).build();
+        RedisSerializer<String> redisSerializer = redisTemplate.getKeySerializer();
+        Cursor cursor = (Cursor) redisTemplate.executeWithStickyConnection(redis -> new ConvertingCursor<>(redis.scan(build), redisSerializer::deserialize));
+
+        if (cursor != null){
+            try {
+                while ( cursor.hasNext()) {
+                    list.add(cursor.next().toString());
+                }
+                try {
+                    cursor.close();
+                } catch (IOException e) {
+                    e.printStackTrace();
+                    log.error("redis涓殑Cursor鍏抽棴澶辫触锛�");
+                }
+            } finally {
+                try {
+                    cursor.close();
+                } catch (IOException e) {
+                    e.printStackTrace();
+                }
+            }
+            Long delete = redisTemplate.delete(list);
+            log.info("鍒犻櫎鑿滃崟key: "+delete+"涓�俓n 璇︽儏:"+list.toString());
+            return delete > 0L;
+        }
+        return false;
+    }
+
+    /**
+     * 鍓嶇紑鍖归厤
+     * @param keyPrefix key鍓嶇紑
+     *
+     */
+    public <T> List<T> findKeysByPrefix(final String keyPrefix) {
+
+        List<T> list = new ArrayList<>();
+        ScanOptions build = ScanOptions.scanOptions().match(keyPrefix+":*").count(5000).build();
+        RedisSerializer<String> redisSerializer = redisTemplate.getKeySerializer();
+        Cursor cursor = (Cursor) redisTemplate.executeWithStickyConnection(redis -> new ConvertingCursor<>(redis.scan(build), redisSerializer::deserialize));
+        if (cursor != null){
+            try {
+                while (cursor.hasNext()) {
+                    list.add(getCacheObject(cursor.next().toString()));
+                }
+                try {
+                    cursor.close();
+                } catch (IOException e) {
+                    e.printStackTrace();
+                }
+            } finally {
+                try {
+                    cursor.close();
+                } catch (IOException e) {
+                    e.printStackTrace();
+                }
+            }
+            return list;
+        }
+        return new ArrayList<>();
+    }
+
+
+    /**
+     * 鍩轰簬Lua鑴氭湰瀹炵幇鍘熷瓙鏌ヨ骞跺垹闄�
+     * @param key
+     * @return
+     */
+    public Boolean deleteLuaByKey(String key) {
+        String str2 = "if redis.call('EXISTS', KEYS[1]) == 1 then redis.call('DEL', KEYS[1]) return 1 else return 0 end";
+        RedisScript<Boolean> redisScript = new DefaultRedisScript<>(str2,Boolean.class);
+        Boolean execute = (Boolean) redisTemplate.execute(redisScript, Collections.singletonList(key));
+        return execute;
+    }
+    /**
+     * GEO 娣诲姞鏁版嵁(缁忕含搴�)
+     * @param key
+     * @return
+     */
+    public <T extends Point> void addGEO(String key, Map<String,T> map) {
+        redisTemplate.opsForGeo().add(key,map);
+    }
+
+    /**
+     * GEO 娣诲姞鏁版嵁(缁忕含搴�)
+     * @param key
+     * @return
+     */
+    public <T extends Point> void addGEO(String key, Point point, String member) {
+        redisTemplate.opsForGeo().add(key,point,member);
+    }
+
+
+    public <T extends Point> void removeGEO(String key,String... member) {
+        redisTemplate.opsForGeo().remove(key,member);
+    }
+
+
+    /**
+     * GEO 鏌ヨ璺濈
+     * @param point 闇�瑕佹煡璇㈢殑鍦板潃
+     * @param key 鍩庡競
+     * @param members 鑺傜偣
+     * @return map(鍟嗛摵,璺濈)
+     */
+    public  Map<String,String> distanceGEO(Point point,String key, List<String> members) {
+        GeoOperations geo = redisTemplate.opsForGeo();
+        long l = System.currentTimeMillis();
+        String member = "geo"+l;
+        addGEO(key,point,member);
+        Map<String,String> map = new HashMap<>();
+        members.forEach(e->{
+            Distance distance = geo.distance(key, member, e, Metrics.KILOMETERS);
+            map.put(e,String.valueOf(distance.getValue()));
+        });
+        removeGEO(key,key,member);
+        return map;
+
+    }
+
+    /**
+     * 鑾峰彇List闆嗗悎鎿嶄綔
+     * @return 鎿嶄綔
+     */
+    public ListOperations opsForList(){
+        return this.redisTemplate.opsForList();
+    }
+
+    /**
+     * 鑾峰彇Set闆嗗悎鎿嶄綔
+     * @return 鎿嶄綔
+     */
+    public SetOperations opsForSet(){
+        return this.redisTemplate.opsForSet();
+    }
+
+    /**
+     * 鑾峰彇hash鎿嶄綔
+     * @return 鎿嶄綔
+     */
+    public HashOperations opsForHash(){
+        return this.redisTemplate.opsForHash();
+    }
 }

--
Gitblit v1.9.3