From 8e4ad31ad0153afae42dceb77ac19478c640750a Mon Sep 17 00:00:00 2001 From: zhongzb <972627721@qq.com> Date: Tue, 25 Apr 2023 23:24:38 +0800 Subject: [PATCH] =?UTF-8?q?=E6=8A=8AredisUtil=E6=94=B9=E6=88=90=E9=9D=99?= =?UTF-8?q?=E6=80=81=E5=B7=A5=E5=85=B7=E7=B1=BB=EF=BC=8C=E5=89=A9=E4=B8=8B?= =?UTF-8?q?=E7=9A=84=E6=96=B9=E6=B3=95=E7=94=A8=E5=88=B0=E5=86=8D=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../common/aspect/FrequencyControlAspect.java | 6 +- .../common/common/utils/CursorUtils.java | 6 +- .../common/common/utils/JsonUtils.java | 30 ++++++ .../common/common/utils/RedisUtils.java | 98 +++++++++---------- .../common/user/service/cache/UserCache.java | 20 ++-- .../user/service/impl/LoginServiceImpl.java | 2 +- 6 files changed, 91 insertions(+), 71 deletions(-) create mode 100644 mallchat-common/src/main/java/com/abin/mallchat/common/common/utils/JsonUtils.java diff --git a/mallchat-common/src/main/java/com/abin/mallchat/common/common/aspect/FrequencyControlAspect.java b/mallchat-common/src/main/java/com/abin/mallchat/common/common/aspect/FrequencyControlAspect.java index 58fc660..c43624f 100644 --- a/mallchat-common/src/main/java/com/abin/mallchat/common/common/aspect/FrequencyControlAspect.java +++ b/mallchat-common/src/main/java/com/abin/mallchat/common/common/aspect/FrequencyControlAspect.java @@ -32,8 +32,6 @@ import java.util.*; @Aspect @Component public class FrequencyControlAspect { - @Autowired - private RedisUtils redisUtils; @Around("@annotation(com.abin.mallchat.common.common.annotation.FrequencyControl)||@annotation(com.abin.mallchat.common.common.annotation.FrequencyControlContainer)") public Object around(ProceedingJoinPoint joinPoint) throws Throwable { @@ -58,7 +56,7 @@ public class FrequencyControlAspect { } //批量获取redis统计的值 ArrayList keyList = new ArrayList<>(keyMap.keySet()); - List countList = redisUtils.mget(keyList, Integer.class); + List countList = RedisUtils.mget(keyList, Integer.class); for (int i = 0; i < keyList.size(); i++) { String key = keyList.get(i); Integer count = countList.get(i); @@ -73,7 +71,7 @@ public class FrequencyControlAspect { } finally { //不管成功还是失败,都增加次数 keyMap.forEach((k, v) -> { - redisUtils.inc(k,v.time(),v.unit()); + RedisUtils.inc(k,v.time(),v.unit()); }); } } diff --git a/mallchat-common/src/main/java/com/abin/mallchat/common/common/utils/CursorUtils.java b/mallchat-common/src/main/java/com/abin/mallchat/common/common/utils/CursorUtils.java index e90c803..be49bcf 100644 --- a/mallchat-common/src/main/java/com/abin/mallchat/common/common/utils/CursorUtils.java +++ b/mallchat-common/src/main/java/com/abin/mallchat/common/common/utils/CursorUtils.java @@ -35,15 +35,13 @@ import java.util.stream.Collectors; */ @Component public class CursorUtils { - @Autowired - private RedisUtils redisUtils; public CursorPageBaseResp> getCursorPageByRedis(CursorPageBaseReq cursorPageBaseReq, String redisKey, Function typeConvert) { Set> typedTuples; if (StrUtil.isBlank(cursorPageBaseReq.getCursor())) {//第一次 - typedTuples = redisUtils.zReverseRangeWithScores(redisKey, cursorPageBaseReq.getPageSize()); + typedTuples = RedisUtils.zReverseRangeWithScores(redisKey, cursorPageBaseReq.getPageSize()); } else { - typedTuples = redisUtils.zReverseRangeByScoreWithScores(redisKey, Double.parseDouble(cursorPageBaseReq.getCursor()), cursorPageBaseReq.getPageSize()); + typedTuples = RedisUtils.zReverseRangeByScoreWithScores(redisKey, Double.parseDouble(cursorPageBaseReq.getCursor()), cursorPageBaseReq.getPageSize()); } List> result = typedTuples .stream() diff --git a/mallchat-common/src/main/java/com/abin/mallchat/common/common/utils/JsonUtils.java b/mallchat-common/src/main/java/com/abin/mallchat/common/common/utils/JsonUtils.java new file mode 100644 index 0000000..dbd20f9 --- /dev/null +++ b/mallchat-common/src/main/java/com/abin/mallchat/common/common/utils/JsonUtils.java @@ -0,0 +1,30 @@ +package com.abin.mallchat.common.common.utils; + +import cn.hutool.json.JSONUtil; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * Description: + * Author: abin + * Date: 2023-04-25 + */ +public class JsonUtils { + private static final ObjectMapper jsonMapper = new ObjectMapper(); + + public static T toObj(String str, Class clz) { + try { + return jsonMapper.readValue(str, clz); + } catch (JsonProcessingException e) { + throw new UnsupportedOperationException(e); + } + } + + public static String toStr(Object t) { + try { + return jsonMapper.writeValueAsString(t); + } catch (Exception e) { + throw new UnsupportedOperationException(e); + } + } +} diff --git a/mallchat-common/src/main/java/com/abin/mallchat/common/common/utils/RedisUtils.java b/mallchat-common/src/main/java/com/abin/mallchat/common/common/utils/RedisUtils.java index bd86f03..5d1ce11 100644 --- a/mallchat-common/src/main/java/com/abin/mallchat/common/common/utils/RedisUtils.java +++ b/mallchat-common/src/main/java/com/abin/mallchat/common/common/utils/RedisUtils.java @@ -1,5 +1,6 @@ package com.abin.mallchat.common.common.utils; +import cn.hutool.extra.spring.SpringUtil; import cn.hutool.json.JSONUtil; import com.fasterxml.jackson.databind.ObjectMapper; import net.sf.json.util.JSONUtils; @@ -12,6 +13,7 @@ import org.springframework.data.redis.core.script.DefaultRedisScript; import org.springframework.data.redis.core.script.RedisScript; import org.springframework.stereotype.Component; +import javax.annotation.PostConstruct; import java.security.Key; import java.util.*; import java.util.concurrent.TimeUnit; @@ -24,11 +26,11 @@ public class RedisUtils { private static final ObjectMapper jsonMapper = new ObjectMapper(); public RedisTemplate redisTemplate; - public StringRedisTemplate stringRedisTemplate; + private static StringRedisTemplate stringRedisTemplate; - public RedisUtils(RedisTemplate redisTemplate, StringRedisTemplate stringRedisTemplate) { - this.redisTemplate = redisTemplate; - this.stringRedisTemplate = stringRedisTemplate; + @PostConstruct + public void init() { + this.stringRedisTemplate = SpringUtil.getBean(StringRedisTemplate.class); } private static final String LUA_INCR_EXPIRE = @@ -41,9 +43,9 @@ public class RedisUtils { " return tonumber(redis.call('INCR',key)) \n" + "end "; - public Long inc(String key, int time, TimeUnit unit) { + public static Long inc(String key, int time, TimeUnit unit) { RedisScript redisScript = new DefaultRedisScript<>(LUA_INCR_EXPIRE, Long.class); - return (Long) redisTemplate.execute(redisScript, Collections.singletonList(key), unit.toSeconds(time)); + return stringRedisTemplate.execute(redisScript, Collections.singletonList(key), unit.toSeconds(time)); } /** @@ -52,10 +54,10 @@ public class RedisUtils { * @param key 键 * @param time 时间(秒) */ - public boolean expire(String key, long time) { + public static boolean expire(String key, long time) { try { if (time > 0) { - redisTemplate.expire(key, time, TimeUnit.SECONDS); + stringRedisTemplate.expire(key, time, TimeUnit.SECONDS); } } catch (Exception e) { log.error(e.getMessage(), e); @@ -89,8 +91,8 @@ public class RedisUtils { * @param key 键 不能为null * @return 时间(秒) 返回0代表为永久有效 */ - public long getExpire(Object key) { - return redisTemplate.getExpire(key, TimeUnit.SECONDS); + public static long getExpire(String key) { + return stringRedisTemplate.getExpire(key, TimeUnit.SECONDS); } /** @@ -99,8 +101,8 @@ public class RedisUtils { * @param key 键 不能为null * @return 时间(秒) 返回0代表为永久有效 */ - public long getExpire(Object key, TimeUnit timeUnit) { - return redisTemplate.getExpire(key, timeUnit); + public static long getExpire(String key, TimeUnit timeUnit) { + return stringRedisTemplate.getExpire(key, timeUnit); } /** @@ -185,19 +187,19 @@ public class RedisUtils { * * @param keys */ - public void del(String... keys) { + public static void del(String... keys) { if (keys != null && keys.length > 0) { if (keys.length == 1) { - boolean result = redisTemplate.delete(keys[0]); + boolean result = stringRedisTemplate.delete(keys[0]); log.debug("--------------------------------------------"); log.debug(new StringBuilder("删除缓存:").append(keys[0]).append(",结果:").append(result).toString()); log.debug("--------------------------------------------"); } else { - Set keySet = new HashSet<>(); + Set keySet = new HashSet<>(); for (String key : keys) { - keySet.addAll(redisTemplate.keys(key)); + keySet.addAll(stringRedisTemplate.keys(key)); } - long count = redisTemplate.delete(keySet); + long count = stringRedisTemplate.delete(keySet); log.debug("--------------------------------------------"); log.debug("成功删除缓存:" + keySet.toString()); log.debug("缓存删除数量:" + count + "个"); @@ -214,34 +216,28 @@ public class RedisUtils { * @param key 键 * @return 值 */ - public Object get(String key) { - return key == null ? null : redisTemplate.opsForValue().get(key); + public static String get(String key) { + return key == null ? null : stringRedisTemplate.opsForValue().get(key); } - public String getStr(String key) { + public static String getStr(String key) { return stringRedisTemplate.opsForValue().get(key); } - public T get(String key, Class tClass) { - Object o = get(key); - return toBeanOrNull(o, tClass); + public static T get(String key, Class tClass) { + String s = get(key); + return toBeanOrNull(s, tClass); } - public List mget(Collection keys, Class tClass) { - List list = stringRedisTemplate.opsForValue().multiGet(keys); + public static List mget(Collection keys, Class tClass) { + List list = stringRedisTemplate.opsForValue().multiGet(keys); return (List) list.stream().map(o -> toBeanOrNull(o, tClass)).collect(Collectors.toList()); } - private T toBeanOrNull(Object o, Class tClass) { - return o == null ? null : toObj(o.toString(),tClass); - } - public static T toObj(String str, Class clz) { - try { - return jsonMapper.readValue(str, clz); - } catch (Exception e) { - throw new UnsupportedOperationException(e); - } + static T toBeanOrNull(String json, Class tClass) { + return json == null ? null : JsonUtils.toObj(json, tClass); } + public static String objToStr(Object o) { try { return jsonMapper.writeValueAsString(o); @@ -250,7 +246,7 @@ public class RedisUtils { } } - public void mset(Map map, long time) { + public static void mset(Map map, long time) { Map collect = map.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, (e) -> objToStr(e.getValue()))); stringRedisTemplate.opsForValue().multiSet(collect); map.forEach((key, value) -> { @@ -265,9 +261,9 @@ public class RedisUtils { * @param value 值 * @return true成功 false失败 */ - public boolean set(String key, Object value) { + public static boolean set(String key, Object value) { try { - redisTemplate.opsForValue().set(key, value); + stringRedisTemplate.opsForValue().set(key, objToStr(value)); return true; } catch (Exception e) { log.error(e.getMessage(), e); @@ -306,10 +302,10 @@ public class RedisUtils { * @param timeUnit 类型 * @return true成功 false 失败 */ - public boolean set(String key, Object value, long time, TimeUnit timeUnit) { + public static boolean set(String key, Object value, long time, TimeUnit timeUnit) { try { if (time > 0) { - redisTemplate.opsForValue().set(key, value, time, timeUnit); + stringRedisTemplate.opsForValue().set(key, objToStr(value), time, timeUnit); } else { set(key, value); } @@ -756,11 +752,11 @@ public class RedisUtils { * @param score * @return */ - public Boolean zAdd(String key, String value, double score) { - return redisTemplate.opsForZSet().add(key, value, score); + public static Boolean zAdd(String key, String value, double score) { + return stringRedisTemplate.opsForZSet().add(key, value, score); } - public Boolean zAdd(String key, Object value, double score) { + public static Boolean zAdd(String key, Object value, double score) { return zAdd(key, value.toString(), score); } @@ -782,12 +778,12 @@ public class RedisUtils { return redisTemplate.opsForZSet().remove(key, values); } - public Long zRemove(String key, Object value) { + public static Long zRemove(String key, Object value) { return zRemove(key, value.toString()); } - public Long zRemove(String key, String value) { - return redisTemplate.opsForZSet().remove(key, value); + public static Long zRemove(String key, String value) { + return stringRedisTemplate.opsForZSet().remove(key, value); } /** @@ -921,8 +917,8 @@ public class RedisUtils { * @param pageSize * @return */ - public Set> zReverseRangeWithScores(String key, - long pageSize) { + public static Set> zReverseRangeWithScores(String key, + long pageSize) { return stringRedisTemplate.opsForZSet().reverseRangeByScoreWithScores(key, Double.MIN_VALUE, Double.MAX_VALUE, 0, pageSize); } @@ -933,8 +929,8 @@ public class RedisUtils { * @param pageSize * @return */ - public Set> zReverseRangeByScoreWithScores(String key, - double max, long pageSize) { + public static Set> zReverseRangeByScoreWithScores(String key, + double max, long pageSize) { return stringRedisTemplate.opsForZSet().reverseRangeByScoreWithScores(key, Double.MIN_VALUE, max, 1, pageSize); } @@ -995,8 +991,8 @@ public class RedisUtils { * @param key * @return */ - public Long zCard(String key) { - return redisTemplate.opsForZSet().zCard(key); + public static Long zCard(String key) { + return stringRedisTemplate.opsForZSet().zCard(key); } /** diff --git a/mallchat-common/src/main/java/com/abin/mallchat/common/user/service/cache/UserCache.java b/mallchat-common/src/main/java/com/abin/mallchat/common/user/service/cache/UserCache.java index 2217af1..6724d82 100644 --- a/mallchat-common/src/main/java/com/abin/mallchat/common/user/service/cache/UserCache.java +++ b/mallchat-common/src/main/java/com/abin/mallchat/common/user/service/cache/UserCache.java @@ -28,8 +28,6 @@ import java.util.stream.Stream; @Component public class UserCache { - @Autowired - private RedisUtils redisUtils; @Autowired private CursorUtils cursorUtils; @Autowired @@ -37,12 +35,12 @@ public class UserCache { public Long getOnlineNum() { String onlineKey = RedisKey.getKey(RedisKey.ONLINE_UID_ZET); - return redisUtils.zCard(onlineKey); + return RedisUtils.zCard(onlineKey); } public Long getOfflineNum() { String offlineKey = RedisKey.getKey(RedisKey.OFFLINE_UID_ZET); - return redisUtils.zCard(offlineKey); + return RedisUtils.zCard(offlineKey); } //用户上线 @@ -50,9 +48,9 @@ public class UserCache { String onlineKey = RedisKey.getKey(RedisKey.ONLINE_UID_ZET); String offlineKey = RedisKey.getKey(RedisKey.OFFLINE_UID_ZET); //移除离线表 - redisUtils.zRemove(offlineKey, uid); + RedisUtils.zRemove(offlineKey, uid); //更新上线表 - redisUtils.zAdd(onlineKey, uid, optTime.getTime()); + RedisUtils.zAdd(onlineKey, uid, optTime.getTime()); } //用户下线 @@ -60,9 +58,9 @@ public class UserCache { String onlineKey = RedisKey.getKey(RedisKey.ONLINE_UID_ZET); String offlineKey = RedisKey.getKey(RedisKey.OFFLINE_UID_ZET); //移除上线线表 - redisUtils.zRemove(onlineKey, uid); + RedisUtils.zRemove(onlineKey, uid); //更新上线表 - redisUtils.zAdd(offlineKey, uid, optTime.getTime()); + RedisUtils.zAdd(offlineKey, uid, optTime.getTime()); } public CursorPageBaseResp> getOnlineCursorPage(CursorPageBaseReq pageBaseReq) { @@ -91,14 +89,14 @@ public class UserCache { */ public Map getUserInfoBatch(Set uids) { List keys = uids.stream().map(a -> RedisKey.getKey(RedisKey.USER_INFO_STRING, a)).collect(Collectors.toList()); - List mget = redisUtils.mget(keys, User.class); + List mget = RedisUtils.mget(keys, User.class); Map map = mget.stream().filter(Objects::nonNull).collect(Collectors.toMap(User::getId, Function.identity())); //还需要load更新的uid List needLoadUidList = uids.stream().filter(a -> !map.containsKey(a)).collect(Collectors.toList()); if (CollUtil.isNotEmpty(needLoadUidList)) { List needLoadUserList = userDao.listByIds(needLoadUidList); Map redisMap = needLoadUserList.stream().collect(Collectors.toMap(a -> RedisKey.getKey(RedisKey.USER_INFO_STRING, a.getId()), Function.identity())); - redisUtils.mset(redisMap, 5 * 60); + RedisUtils.mset(redisMap, 5 * 60); map.putAll(needLoadUserList.stream().collect(Collectors.toMap(User::getId, Function.identity()))); } return map; @@ -106,7 +104,7 @@ public class UserCache { public void delUserInfo(Long uid) { String key = RedisKey.getKey(RedisKey.USER_INFO_STRING, uid); - redisUtils.del(key); + RedisUtils.del(key); } } diff --git a/mallchat-custom-server/src/main/java/com/abin/mallchat/custom/user/service/impl/LoginServiceImpl.java b/mallchat-custom-server/src/main/java/com/abin/mallchat/custom/user/service/impl/LoginServiceImpl.java index 2bf3035..5182533 100644 --- a/mallchat-custom-server/src/main/java/com/abin/mallchat/custom/user/service/impl/LoginServiceImpl.java +++ b/mallchat-custom-server/src/main/java/com/abin/mallchat/custom/user/service/impl/LoginServiceImpl.java @@ -45,7 +45,7 @@ public class LoginServiceImpl implements LoginService { return false; } String key = RedisKey.getKey(RedisKey.USER_TOKEN_STRING, uid); - String realToken = redisUtils.getStr(key); + String realToken = redisUtils.get(key); return token.equals(realToken);//有可能token失效了,需要校验是不是和最新token一致 }