把redisUtil改成静态工具类,剩下的方法用到再改

This commit is contained in:
zhongzb
2023-04-25 23:24:38 +08:00
parent 1c58a17cbc
commit 8e4ad31ad0
6 changed files with 91 additions and 71 deletions

View File

@@ -32,8 +32,6 @@ import java.util.*;
@Aspect @Aspect
@Component @Component
public class FrequencyControlAspect { public class FrequencyControlAspect {
@Autowired
private RedisUtils redisUtils;
@Around("@annotation(com.abin.mallchat.common.common.annotation.FrequencyControl)||@annotation(com.abin.mallchat.common.common.annotation.FrequencyControlContainer)") @Around("@annotation(com.abin.mallchat.common.common.annotation.FrequencyControl)||@annotation(com.abin.mallchat.common.common.annotation.FrequencyControlContainer)")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable { public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
@@ -58,7 +56,7 @@ public class FrequencyControlAspect {
} }
//批量获取redis统计的值 //批量获取redis统计的值
ArrayList<String> keyList = new ArrayList<>(keyMap.keySet()); ArrayList<String> keyList = new ArrayList<>(keyMap.keySet());
List<Integer> countList = redisUtils.mget(keyList, Integer.class); List<Integer> countList = RedisUtils.mget(keyList, Integer.class);
for (int i = 0; i < keyList.size(); i++) { for (int i = 0; i < keyList.size(); i++) {
String key = keyList.get(i); String key = keyList.get(i);
Integer count = countList.get(i); Integer count = countList.get(i);
@@ -73,7 +71,7 @@ public class FrequencyControlAspect {
} finally { } finally {
//不管成功还是失败,都增加次数 //不管成功还是失败,都增加次数
keyMap.forEach((k, v) -> { keyMap.forEach((k, v) -> {
redisUtils.inc(k,v.time(),v.unit()); RedisUtils.inc(k,v.time(),v.unit());
}); });
} }
} }

View File

@@ -35,15 +35,13 @@ import java.util.stream.Collectors;
*/ */
@Component @Component
public class CursorUtils { public class CursorUtils {
@Autowired
private RedisUtils redisUtils;
public <T> CursorPageBaseResp<Pair<T, Double>> getCursorPageByRedis(CursorPageBaseReq cursorPageBaseReq, String redisKey, Function<String, T> typeConvert) { public <T> CursorPageBaseResp<Pair<T, Double>> getCursorPageByRedis(CursorPageBaseReq cursorPageBaseReq, String redisKey, Function<String, T> typeConvert) {
Set<ZSetOperations.TypedTuple<String>> typedTuples; Set<ZSetOperations.TypedTuple<String>> typedTuples;
if (StrUtil.isBlank(cursorPageBaseReq.getCursor())) {//第一次 if (StrUtil.isBlank(cursorPageBaseReq.getCursor())) {//第一次
typedTuples = redisUtils.zReverseRangeWithScores(redisKey, cursorPageBaseReq.getPageSize()); typedTuples = RedisUtils.zReverseRangeWithScores(redisKey, cursorPageBaseReq.getPageSize());
} else { } else {
typedTuples = redisUtils.zReverseRangeByScoreWithScores(redisKey, Double.parseDouble(cursorPageBaseReq.getCursor()), cursorPageBaseReq.getPageSize()); typedTuples = RedisUtils.zReverseRangeByScoreWithScores(redisKey, Double.parseDouble(cursorPageBaseReq.getCursor()), cursorPageBaseReq.getPageSize());
} }
List<Pair<T, Double>> result = typedTuples List<Pair<T, Double>> result = typedTuples
.stream() .stream()

View File

@@ -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: <a href="https://github.com/zongzibinbin">abin</a>
* Date: 2023-04-25
*/
public class JsonUtils {
private static final ObjectMapper jsonMapper = new ObjectMapper();
public static <T> T toObj(String str, Class<T> 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);
}
}
}

View File

@@ -1,5 +1,6 @@
package com.abin.mallchat.common.common.utils; package com.abin.mallchat.common.common.utils;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONUtil; import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import net.sf.json.util.JSONUtils; 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.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.security.Key; import java.security.Key;
import java.util.*; import java.util.*;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@@ -24,11 +26,11 @@ public class RedisUtils {
private static final ObjectMapper jsonMapper = new ObjectMapper(); private static final ObjectMapper jsonMapper = new ObjectMapper();
public RedisTemplate redisTemplate; public RedisTemplate redisTemplate;
public StringRedisTemplate stringRedisTemplate; private static StringRedisTemplate stringRedisTemplate;
public RedisUtils(RedisTemplate redisTemplate, StringRedisTemplate stringRedisTemplate) { @PostConstruct
this.redisTemplate = redisTemplate; public void init() {
this.stringRedisTemplate = stringRedisTemplate; this.stringRedisTemplate = SpringUtil.getBean(StringRedisTemplate.class);
} }
private static final String LUA_INCR_EXPIRE = private static final String LUA_INCR_EXPIRE =
@@ -41,9 +43,9 @@ public class RedisUtils {
" return tonumber(redis.call('INCR',key)) \n" + " return tonumber(redis.call('INCR',key)) \n" +
"end "; "end ";
public Long inc(String key, int time, TimeUnit unit) { public static Long inc(String key, int time, TimeUnit unit) {
RedisScript<Long> redisScript = new DefaultRedisScript<>(LUA_INCR_EXPIRE, Long.class); RedisScript<Long> 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 key 键
* @param time 时间(秒) * @param time 时间(秒)
*/ */
public boolean expire(String key, long time) { public static boolean expire(String key, long time) {
try { try {
if (time > 0) { if (time > 0) {
redisTemplate.expire(key, time, TimeUnit.SECONDS); stringRedisTemplate.expire(key, time, TimeUnit.SECONDS);
} }
} catch (Exception e) { } catch (Exception e) {
log.error(e.getMessage(), e); log.error(e.getMessage(), e);
@@ -89,8 +91,8 @@ public class RedisUtils {
* @param key 键 不能为null * @param key 键 不能为null
* @return 时间(秒) 返回0代表为永久有效 * @return 时间(秒) 返回0代表为永久有效
*/ */
public long getExpire(Object key) { public static long getExpire(String key) {
return redisTemplate.getExpire(key, TimeUnit.SECONDS); return stringRedisTemplate.getExpire(key, TimeUnit.SECONDS);
} }
/** /**
@@ -99,8 +101,8 @@ public class RedisUtils {
* @param key 键 不能为null * @param key 键 不能为null
* @return 时间(秒) 返回0代表为永久有效 * @return 时间(秒) 返回0代表为永久有效
*/ */
public long getExpire(Object key, TimeUnit timeUnit) { public static long getExpire(String key, TimeUnit timeUnit) {
return redisTemplate.getExpire(key, timeUnit); return stringRedisTemplate.getExpire(key, timeUnit);
} }
/** /**
@@ -185,19 +187,19 @@ public class RedisUtils {
* *
* @param keys * @param keys
*/ */
public void del(String... keys) { public static void del(String... keys) {
if (keys != null && keys.length > 0) { if (keys != null && keys.length > 0) {
if (keys.length == 1) { if (keys.length == 1) {
boolean result = redisTemplate.delete(keys[0]); boolean result = stringRedisTemplate.delete(keys[0]);
log.debug("--------------------------------------------"); log.debug("--------------------------------------------");
log.debug(new StringBuilder("删除缓存:").append(keys[0]).append(",结果:").append(result).toString()); log.debug(new StringBuilder("删除缓存:").append(keys[0]).append(",结果:").append(result).toString());
log.debug("--------------------------------------------"); log.debug("--------------------------------------------");
} else { } else {
Set<Object> keySet = new HashSet<>(); Set<String> keySet = new HashSet<>();
for (String key : keys) { 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("--------------------------------------------");
log.debug("成功删除缓存:" + keySet.toString()); log.debug("成功删除缓存:" + keySet.toString());
log.debug("缓存删除数量:" + count + ""); log.debug("缓存删除数量:" + count + "");
@@ -214,34 +216,28 @@ public class RedisUtils {
* @param key 键 * @param key 键
* @return 值 * @return 值
*/ */
public Object get(String key) { public static String get(String key) {
return key == null ? null : redisTemplate.opsForValue().get(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); return stringRedisTemplate.opsForValue().get(key);
} }
public <T> T get(String key, Class<T> tClass) { public static <T> T get(String key, Class<T> tClass) {
Object o = get(key); String s = get(key);
return toBeanOrNull(o, tClass); return toBeanOrNull(s, tClass);
} }
public <T> List<T> mget(Collection<String> keys, Class<T> tClass) { public static <T> List<T> mget(Collection<String> keys, Class<T> tClass) {
List list = stringRedisTemplate.opsForValue().multiGet(keys); List<String> list = stringRedisTemplate.opsForValue().multiGet(keys);
return (List<T>) list.stream().map(o -> toBeanOrNull(o, tClass)).collect(Collectors.toList()); return (List<T>) list.stream().map(o -> toBeanOrNull(o, tClass)).collect(Collectors.toList());
} }
private <T> T toBeanOrNull(Object o, Class<T> tClass) { static <T> T toBeanOrNull(String json, Class<T> tClass) {
return o == null ? null : toObj(o.toString(),tClass); return json == null ? null : JsonUtils.toObj(json, tClass);
}
public static <T> T toObj(String str, Class<T> clz) {
try {
return jsonMapper.readValue(str, clz);
} catch (Exception e) {
throw new UnsupportedOperationException(e);
}
} }
public static String objToStr(Object o) { public static String objToStr(Object o) {
try { try {
return jsonMapper.writeValueAsString(o); return jsonMapper.writeValueAsString(o);
@@ -250,7 +246,7 @@ public class RedisUtils {
} }
} }
public <T> void mset(Map<String, T> map, long time) { public static <T> void mset(Map<String, T> map, long time) {
Map<String, String> collect = map.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, (e) -> objToStr(e.getValue()))); Map<String, String> collect = map.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, (e) -> objToStr(e.getValue())));
stringRedisTemplate.opsForValue().multiSet(collect); stringRedisTemplate.opsForValue().multiSet(collect);
map.forEach((key, value) -> { map.forEach((key, value) -> {
@@ -265,9 +261,9 @@ public class RedisUtils {
* @param value 值 * @param value 值
* @return true成功 false失败 * @return true成功 false失败
*/ */
public boolean set(String key, Object value) { public static boolean set(String key, Object value) {
try { try {
redisTemplate.opsForValue().set(key, value); stringRedisTemplate.opsForValue().set(key, objToStr(value));
return true; return true;
} catch (Exception e) { } catch (Exception e) {
log.error(e.getMessage(), e); log.error(e.getMessage(), e);
@@ -306,10 +302,10 @@ public class RedisUtils {
* @param timeUnit 类型 * @param timeUnit 类型
* @return true成功 false 失败 * @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 { try {
if (time > 0) { if (time > 0) {
redisTemplate.opsForValue().set(key, value, time, timeUnit); stringRedisTemplate.opsForValue().set(key, objToStr(value), time, timeUnit);
} else { } else {
set(key, value); set(key, value);
} }
@@ -756,11 +752,11 @@ public class RedisUtils {
* @param score * @param score
* @return * @return
*/ */
public Boolean zAdd(String key, String value, double score) { public static Boolean zAdd(String key, String value, double score) {
return redisTemplate.opsForZSet().add(key, value, 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); return zAdd(key, value.toString(), score);
} }
@@ -782,12 +778,12 @@ public class RedisUtils {
return redisTemplate.opsForZSet().remove(key, values); 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()); return zRemove(key, value.toString());
} }
public Long zRemove(String key, String value) { public static Long zRemove(String key, String value) {
return redisTemplate.opsForZSet().remove(key, value); return stringRedisTemplate.opsForZSet().remove(key, value);
} }
/** /**
@@ -921,8 +917,8 @@ public class RedisUtils {
* @param pageSize * @param pageSize
* @return * @return
*/ */
public Set<TypedTuple<String>> zReverseRangeWithScores(String key, public static Set<TypedTuple<String>> zReverseRangeWithScores(String key,
long pageSize) { long pageSize) {
return stringRedisTemplate.opsForZSet().reverseRangeByScoreWithScores(key, Double.MIN_VALUE, return stringRedisTemplate.opsForZSet().reverseRangeByScoreWithScores(key, Double.MIN_VALUE,
Double.MAX_VALUE, 0, pageSize); Double.MAX_VALUE, 0, pageSize);
} }
@@ -933,8 +929,8 @@ public class RedisUtils {
* @param pageSize * @param pageSize
* @return * @return
*/ */
public Set<TypedTuple<String>> zReverseRangeByScoreWithScores(String key, public static Set<TypedTuple<String>> zReverseRangeByScoreWithScores(String key,
double max, long pageSize) { double max, long pageSize) {
return stringRedisTemplate.opsForZSet().reverseRangeByScoreWithScores(key, Double.MIN_VALUE, max, return stringRedisTemplate.opsForZSet().reverseRangeByScoreWithScores(key, Double.MIN_VALUE, max,
1, pageSize); 1, pageSize);
} }
@@ -995,8 +991,8 @@ public class RedisUtils {
* @param key * @param key
* @return * @return
*/ */
public Long zCard(String key) { public static Long zCard(String key) {
return redisTemplate.opsForZSet().zCard(key); return stringRedisTemplate.opsForZSet().zCard(key);
} }
/** /**

View File

@@ -28,8 +28,6 @@ import java.util.stream.Stream;
@Component @Component
public class UserCache { public class UserCache {
@Autowired
private RedisUtils redisUtils;
@Autowired @Autowired
private CursorUtils cursorUtils; private CursorUtils cursorUtils;
@Autowired @Autowired
@@ -37,12 +35,12 @@ public class UserCache {
public Long getOnlineNum() { public Long getOnlineNum() {
String onlineKey = RedisKey.getKey(RedisKey.ONLINE_UID_ZET); String onlineKey = RedisKey.getKey(RedisKey.ONLINE_UID_ZET);
return redisUtils.zCard(onlineKey); return RedisUtils.zCard(onlineKey);
} }
public Long getOfflineNum() { public Long getOfflineNum() {
String offlineKey = RedisKey.getKey(RedisKey.OFFLINE_UID_ZET); 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 onlineKey = RedisKey.getKey(RedisKey.ONLINE_UID_ZET);
String offlineKey = RedisKey.getKey(RedisKey.OFFLINE_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 onlineKey = RedisKey.getKey(RedisKey.ONLINE_UID_ZET);
String offlineKey = RedisKey.getKey(RedisKey.OFFLINE_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<Pair<Long, Double>> getOnlineCursorPage(CursorPageBaseReq pageBaseReq) { public CursorPageBaseResp<Pair<Long, Double>> getOnlineCursorPage(CursorPageBaseReq pageBaseReq) {
@@ -91,14 +89,14 @@ public class UserCache {
*/ */
public Map<Long, User> getUserInfoBatch(Set<Long> uids) { public Map<Long, User> getUserInfoBatch(Set<Long> uids) {
List<String> keys = uids.stream().map(a -> RedisKey.getKey(RedisKey.USER_INFO_STRING, a)).collect(Collectors.toList()); List<String> keys = uids.stream().map(a -> RedisKey.getKey(RedisKey.USER_INFO_STRING, a)).collect(Collectors.toList());
List<User> mget = redisUtils.mget(keys, User.class); List<User> mget = RedisUtils.mget(keys, User.class);
Map<Long, User> map = mget.stream().filter(Objects::nonNull).collect(Collectors.toMap(User::getId, Function.identity())); Map<Long, User> map = mget.stream().filter(Objects::nonNull).collect(Collectors.toMap(User::getId, Function.identity()));
//还需要load更新的uid //还需要load更新的uid
List<Long> needLoadUidList = uids.stream().filter(a -> !map.containsKey(a)).collect(Collectors.toList()); List<Long> needLoadUidList = uids.stream().filter(a -> !map.containsKey(a)).collect(Collectors.toList());
if (CollUtil.isNotEmpty(needLoadUidList)) { if (CollUtil.isNotEmpty(needLoadUidList)) {
List<User> needLoadUserList = userDao.listByIds(needLoadUidList); List<User> needLoadUserList = userDao.listByIds(needLoadUidList);
Map<String, User> redisMap = needLoadUserList.stream().collect(Collectors.toMap(a -> RedisKey.getKey(RedisKey.USER_INFO_STRING, a.getId()), Function.identity())); Map<String, User> 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()))); map.putAll(needLoadUserList.stream().collect(Collectors.toMap(User::getId, Function.identity())));
} }
return map; return map;
@@ -106,7 +104,7 @@ public class UserCache {
public void delUserInfo(Long uid) { public void delUserInfo(Long uid) {
String key = RedisKey.getKey(RedisKey.USER_INFO_STRING, uid); String key = RedisKey.getKey(RedisKey.USER_INFO_STRING, uid);
redisUtils.del(key); RedisUtils.del(key);
} }
} }

View File

@@ -45,7 +45,7 @@ public class LoginServiceImpl implements LoginService {
return false; return false;
} }
String key = RedisKey.getKey(RedisKey.USER_TOKEN_STRING, uid); 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一致 return token.equals(realToken);//有可能token失效了需要校验是不是和最新token一致
} }