refactor: 优化RedisUtils,增强缓存获取功能

pull/872/head
Jie Zheng 2025-01-15 15:04:38 +08:00
parent c62ac4c383
commit 09585d3f0b
6 changed files with 105 additions and 29 deletions

View File

@ -15,6 +15,7 @@
*/
package me.zhengjie.utils;
import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.slf4j.Logger;
@ -24,14 +25,16 @@ import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
/**
* @author /
*/
@Component
@SuppressWarnings({"unchecked", "all"})
@SuppressWarnings({"all"})
public class RedisUtils {
private static final Logger log = LoggerFactory.getLogger(RedisUtils.class);
@ -39,9 +42,8 @@ public class RedisUtils {
public RedisUtils(RedisTemplate<Object, Object> redisTemplate) {
this.redisTemplate = redisTemplate;
this.redisTemplate.setHashKeySerializer(new StringRedisSerializer());
this.redisTemplate.setKeySerializer(new StringRedisSerializer());
this.redisTemplate.setStringSerializer(new StringRedisSerializer());
this.redisTemplate.setHashKeySerializer(new StringRedisSerializer());
}
/**
@ -221,6 +223,65 @@ public class RedisUtils {
return key == null ? null : redisTemplate.opsForValue().get(key);
}
/**
*
*
* @param key
* @return
*/
public <T> T get(String key, Class<T> clazz) {
Object value = key == null ? null : redisTemplate.opsForValue().get(key);
if (value == null) {
return null;
}
if (clazz.isInstance(value)) {
return clazz.cast(value);
} else {
return null;
}
}
/**
*
*
* @param key
* @param clazz
* @return
*/
public <T> List<T> getList(String key, Class<T> clazz) {
Object value = key == null ? null : redisTemplate.opsForValue().get(key);
if (value == null) {
return null;
}
if (value instanceof List<?>) {
List<?> list = (List<?>) value;
// 检查每个元素是否为指定类型
if (list.stream().allMatch(clazz::isInstance)) {
return list.stream().map(clazz::cast).collect(Collectors.toList());
}
}
return null;
}
/**
*
*
* @param key
* @return
*/
public String getStr(String key) {
if(StrUtil.isBlank(key)){
return null;
}
Object value = redisTemplate.opsForValue().get(key);
if (value == null) {
return null;
} else {
return String.valueOf(value);
}
}
/**
*
*
@ -242,13 +303,17 @@ public class RedisUtils {
* @return true false
*/
public boolean set(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
log.error(e.getMessage(), e);
return false;
int attempt = 0;
while (attempt < 3) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
attempt++;
log.error("Attempt {} failed: {}", attempt, e.getMessage(), e);
}
}
return false;
}
/**
@ -716,10 +781,25 @@ public class RedisUtils {
keys.addAll(redisTemplate.keys(new StringBuffer(prefix).append(id).toString()));
}
long count = redisTemplate.delete(keys);
// 此处提示可自行删除
log.debug("--------------------------------------------");
log.debug("成功删除缓存:" + keys.toString());
log.debug("缓存删除数量:" + count + "个");
log.debug("--------------------------------------------");
}
// ============================incr=============================
/**
*
* @param key
* @return
*/
public Long increment(String key) {
return redisTemplate.opsForValue().increment(key);
}
/**
*
* @param key
* @return
*/
public Long decrement(String key) {
return redisTemplate.opsForValue().decrement(key);
}
}

View File

@ -145,11 +145,11 @@ public class QuartzJobServiceImpl implements QuartzJobService {
// 执行任务
execution(quartzJob);
// 获取执行状态,如果执行失败则停止后面的子任务执行
Boolean result = (Boolean) redisUtils.get(uuid);
Boolean result = redisUtils.get(uuid, Boolean.class);
while (result == null) {
// 休眠5秒再次获取子任务执行情况
Thread.sleep(5000);
result = (Boolean) redisUtils.get(uuid);
result = redisUtils.get(uuid, Boolean.class);
}
if(!result){
redisUtils.del(uuid);

View File

@ -79,7 +79,7 @@ public class AuthorizationController {
// 密码解密
String password = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey, authUser.getPassword());
// 查询验证码
String code = (String) redisUtils.get(authUser.getUuid());
String code = redisUtils.get(authUser.getUuid(), String.class);
// 清除验证码
redisUtils.del(authUser.getUuid());
if (StringUtils.isBlank(code)) {

View File

@ -92,7 +92,7 @@ public class OnlineUserService {
Collections.reverse(keys);
List<OnlineUserDto> onlineUserDtos = new ArrayList<>();
for (String key : keys) {
onlineUserDtos.add((OnlineUserDto) redisUtils.get(key));
onlineUserDtos.add(redisUtils.get(key, OnlineUserDto.class));
}
onlineUserDtos.sort((o1, o2) -> o2.getLoginTime().compareTo(o1.getLoginTime()));
return onlineUserDtos;
@ -134,7 +134,7 @@ public class OnlineUserService {
* @return /
*/
public OnlineUserDto getOne(String key) {
return (OnlineUserDto)redisUtils.get(key);
return redisUtils.get(key, OnlineUserDto.class);
}
/**

View File

@ -46,10 +46,7 @@ public class UserCacheManager {
public JwtUserDto getUserCache(String userName) {
if (StringUtils.isNotEmpty(userName)) {
// 获取数据
Object obj = redisUtils.get(LoginProperties.cacheKey + userName);
if(obj != null){
return (JwtUserDto)obj;
}
return redisUtils.get(LoginProperties.cacheKey + userName, JwtUserDto.class);
}
return null;
}

View File

@ -52,7 +52,7 @@ public class VerifyServiceImpl implements VerifyService {
// 如果不存在有效的验证码,就创建一个新的
TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig("template", TemplateConfig.ResourceMode.CLASSPATH));
Template template = engine.getTemplate("email.ftl");
Object oldCode = redisUtils.get(redisKey);
String oldCode = redisUtils.get(redisKey, String.class);
if(oldCode == null){
String code = RandomUtil.randomNumbers (6);
// 存入缓存
@ -60,19 +60,18 @@ public class VerifyServiceImpl implements VerifyService {
throw new BadRequestException("服务异常,请联系网站负责人");
}
content = template.render(Dict.create().set("code",code));
emailVo = new EmailVo(Collections.singletonList(email),"ELADMIN后台管理系统",content);
// 存在就再次发送原来的验证码
// 存在就再次发送原来的验证码
} else {
content = template.render(Dict.create().set("code",oldCode));
emailVo = new EmailVo(Collections.singletonList(email),"ELADMIN后台管理系统",content);
}
emailVo = new EmailVo(Collections.singletonList(email),"ELADMIN后台管理系统",content);
return emailVo;
}
@Override
public void validated(String key, String code) {
Object value = redisUtils.get(key);
if(value == null || !value.toString().equals(code)){
String value = redisUtils.get(key, String.class);
if(!code.equals(value)){
throw new BadRequestException("无效验证码");
} else {
redisUtils.del(key);