refactor: 优化RedisUtils

This commit is contained in:
Jie Zheng 2025-01-06 15:25:10 +08:00
parent 9ce4838a68
commit 7b37a94027
6 changed files with 103 additions and 23 deletions

View File

@ -15,6 +15,7 @@
*/ */
package me.zhengjie.utils; package me.zhengjie.utils;
import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -26,6 +27,7 @@ import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.util.*; import java.util.*;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
/** /**
* @author / * @author /
@ -39,9 +41,8 @@ public class RedisUtils {
public RedisUtils(RedisTemplate<Object, Object> redisTemplate) { public RedisUtils(RedisTemplate<Object, Object> redisTemplate) {
this.redisTemplate = redisTemplate; this.redisTemplate = redisTemplate;
this.redisTemplate.setHashKeySerializer(new StringRedisSerializer());
this.redisTemplate.setKeySerializer(new StringRedisSerializer()); this.redisTemplate.setKeySerializer(new StringRedisSerializer());
this.redisTemplate.setStringSerializer(new StringRedisSerializer()); this.redisTemplate.setHashKeySerializer(new StringRedisSerializer());
} }
/** /**
@ -221,6 +222,65 @@ public class RedisUtils {
return key == null ? null : redisTemplate.opsForValue().get(key); 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,14 +302,18 @@ public class RedisUtils {
* @return true成功 false失败 * @return true成功 false失败
*/ */
public boolean set(String key, Object value) { public boolean set(String key, Object value) {
int attempt = 0;
while (attempt < 3) {
try { try {
redisTemplate.opsForValue().set(key, value); redisTemplate.opsForValue().set(key, value);
return true; return true;
} catch (Exception e) { } catch (Exception e) {
log.error(e.getMessage(), e); attempt++;
return false; log.error("Attempt {} failed: {}", attempt, e.getMessage(), e);
} }
} }
return false;
}
/** /**
* 普通缓存放入并设置时间 * 普通缓存放入并设置时间
@ -722,4 +786,24 @@ public class RedisUtils {
log.debug("缓存删除数量:" + count + ""); log.debug("缓存删除数量:" + count + "");
log.debug("--------------------------------------------"); 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

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

View File

@ -79,7 +79,7 @@ public class AuthorizationController {
// 密码解密 // 密码解密
String password = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey, authUser.getPassword()); 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()); redisUtils.del(authUser.getUuid());
if (StringUtils.isBlank(code)) { if (StringUtils.isBlank(code)) {

View File

@ -92,7 +92,7 @@ public class OnlineUserService {
Collections.reverse(keys); Collections.reverse(keys);
List<OnlineUserDto> onlineUserDtos = new ArrayList<>(); List<OnlineUserDto> onlineUserDtos = new ArrayList<>();
for (String key : keys) { 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())); onlineUserDtos.sort((o1, o2) -> o2.getLoginTime().compareTo(o1.getLoginTime()));
return onlineUserDtos; return onlineUserDtos;
@ -134,7 +134,7 @@ public class OnlineUserService {
* @return / * @return /
*/ */
public OnlineUserDto getOne(String key) { 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) { public JwtUserDto getUserCache(String userName) {
if (StringUtils.isNotEmpty(userName)) { if (StringUtils.isNotEmpty(userName)) {
// 获取数据 // 获取数据
Object obj = redisUtils.get(LoginProperties.cacheKey + userName); return redisUtils.get(LoginProperties.cacheKey + userName, JwtUserDto.class);
if(obj != null){
return (JwtUserDto)obj;
}
} }
return null; return null;
} }

View File

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