refactor: 适配 ContiNew Starter Redisson 自动配置

This commit is contained in:
Charles7c 2023-11-22 21:58:30 +08:00
parent f4c0919eda
commit a40e609ea1
11 changed files with 46 additions and 281 deletions

View File

@ -23,7 +23,13 @@
<artifactId>continew-starter-api-doc</artifactId>
</dependency>
<!-- ContiNew Starter Jackson 依赖 -->
<!-- ContiNew Starter Redisson 依赖Redis 缓存) -->
<dependency>
<groupId>top.charles7c.continew</groupId>
<artifactId>continew-starter-cache-redisson</artifactId>
</dependency>
<!-- ContiNew Starter Jackson 依赖JSON -->
<dependency>
<groupId>top.charles7c.continew</groupId>
<artifactId>continew-starter-json-jackson</artifactId>
@ -114,12 +120,6 @@
<artifactId>mica-ip2region</artifactId>
</dependency>
<!-- Redisson不仅仅是一个 Redis Java 客户端) -->
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson-spring-boot-starter</artifactId>
</dependency>
<!-- Easy CaptchaJava 图形验证码,支持 gif、中文、算术等类型可用于 Java Web、JavaSE 等项目) -->
<dependency>
<groupId>com.github.whvcse</groupId>

View File

@ -21,8 +21,6 @@ import java.util.Map;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.codec.JsonJacksonCodec;
import org.redisson.spring.starter.RedissonAutoConfigurationCustomizer;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
@ -41,7 +39,7 @@ import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.json.JSONUtil;
/**
* Redis 配置
* Spring Cache 配置
*
* @author Charles7c
* @since 2022/12/28 23:17
@ -50,19 +48,10 @@ import cn.hutool.json.JSONUtil;
@EnableCaching
@Configuration
@RequiredArgsConstructor
public class RedisConfiguration extends CachingConfigurerSupport {
public class SpringCacheConfiguration extends CachingConfigurerSupport {
private final ObjectMapper objectMapper;
/**
* Redisson 自定义配置
*/
@Bean
public RedissonAutoConfigurationCustomizer redissonCustomizer() {
// 解决序列化乱码问题
return config -> config.setCodec(new JsonJacksonCodec(objectMapper));
}
/**
* 解决 Spring Cache@Cacheable缓存乱码问题
*/

View File

@ -19,7 +19,7 @@ package top.charles7c.cnadmin.common.config.justauth;
import java.time.Duration;
import top.charles7c.cnadmin.common.constant.CacheConsts;
import top.charles7c.cnadmin.common.util.RedisUtils;
import top.charles7c.continew.starter.cache.redisson.util.RedisUtils;
import me.zhyd.oauth.cache.AuthStateCache;
@ -42,7 +42,7 @@ public class JustAuthRedisStateCache implements AuthStateCache {
@Override
public void cache(String key, String value) {
// 参考 JustAuth 内置了一个基于 map state 缓存器默认缓存有效期为 3 分钟
RedisUtils.setCacheObject(RedisUtils.formatKey(CacheConsts.SOCIAL_AUTH_STATE_KEY_PREFIX, key), value,
RedisUtils.set(RedisUtils.formatKey(CacheConsts.SOCIAL_AUTH_STATE_KEY_PREFIX, key), value,
Duration.ofMinutes(3));
}
@ -58,7 +58,7 @@ public class JustAuthRedisStateCache implements AuthStateCache {
*/
@Override
public void cache(String key, String value, long timeout) {
RedisUtils.setCacheObject(RedisUtils.formatKey(CacheConsts.SOCIAL_AUTH_STATE_KEY_PREFIX, key), value,
RedisUtils.set(RedisUtils.formatKey(CacheConsts.SOCIAL_AUTH_STATE_KEY_PREFIX, key), value,
Duration.ofMillis(timeout));
}
@ -71,7 +71,7 @@ public class JustAuthRedisStateCache implements AuthStateCache {
*/
@Override
public String get(String key) {
return RedisUtils.getCacheObject(RedisUtils.formatKey(CacheConsts.SOCIAL_AUTH_STATE_KEY_PREFIX, key));
return RedisUtils.get(RedisUtils.formatKey(CacheConsts.SOCIAL_AUTH_STATE_KEY_PREFIX, key));
}
/**

View File

@ -1,221 +0,0 @@
/*
* Copyright (c) 2022-present Charles7c Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package top.charles7c.cnadmin.common.util;
import java.time.Duration;
import java.util.Collection;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import lombok.AccessLevel;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.redisson.api.*;
import org.redisson.config.Config;
import cn.hutool.extra.spring.SpringUtil;
/**
* Redis 工具类
*
* @author Lion LiRuoYi-Vue-Plus
* @author Charles7c
* @since 2022/12/11 12:00
*/
@Data
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class RedisUtils {
private static final RedissonClient REDISSON_CLIENT = SpringUtil.getBean(RedissonClient.class);
/* ################ 查询操作 ################ */
/**
* 获取缓存的基本对象列表
*
* @param keyPattern
* 缓存键表达式
* @return 基本对象列表
*/
public static Collection<String> keys(final String keyPattern) {
Stream<String> stream = REDISSON_CLIENT.getKeys().getKeysStreamByPattern(getNameMapper().map(keyPattern));
return stream.map(key -> getNameMapper().unmap(key)).collect(Collectors.toList());
}
/**
* 是否存在指定缓存
*
* @param key
* 缓存键
*/
public static Boolean hasKey(String key) {
RKeys rKeys = REDISSON_CLIENT.getKeys();
return rKeys.countExists(getNameMapper().map(key)) > 0;
}
/**
* 获取缓存剩余存活时间
*
* @param key
* 缓存键
* @return 剩余存活时间单位毫秒
*/
public static <T> long getTimeToLive(final String key) {
RBucket<T> rBucket = REDISSON_CLIENT.getBucket(key);
return rBucket.remainTimeToLive();
}
/**
* 获取缓存的基本对象
*
* @param key
* 缓存键
* @return 缓存值
*/
public static <T> T getCacheObject(final String key) {
RBucket<T> rBucket = REDISSON_CLIENT.getBucket(key);
return rBucket.get();
}
/* ################ 操作有效期 ################ */
/**
* 设置过期时间
*
* @param key
* 缓存键
* @param timeout
* 过期时间
* @return true 设置成功false 设置失败
*/
public static boolean expire(final String key, final long timeout) {
return expire(key, Duration.ofSeconds(timeout));
}
/**
* 设置过期时间
*
* @param key
* 缓存键
* @param duration
* 过期时间
* @return true 设置成功false 设置失败
*/
public static boolean expire(final String key, final Duration duration) {
RBucket rBucket = REDISSON_CLIENT.getBucket(key);
return rBucket.expire(duration);
}
/* ################ 操作基本对象 ################ */
/**
* 缓存基本对象IntegerString实体类等
*
* @param key
* 缓存键
* @param value
* 缓存值
*/
public static <T> void setCacheObject(final String key, final T value) {
setCacheObject(key, value, false);
}
/**
* 缓存基本对象保留当前对象 TTL 有效期
*
* @param key
* 缓存键
* @param value
* 缓存值
* @param isSaveTtl
* 是否保留 TTL 有效期(例如: set 之前 ttl 剩余 90set 之后还是为 90)
* @since Redis 6.X 以上使用 setAndKeepTTL 兼容 5.X 方案
*/
public static <T> void setCacheObject(final String key, final T value, final boolean isSaveTtl) {
RBucket<T> bucket = REDISSON_CLIENT.getBucket(key);
if (isSaveTtl) {
try {
bucket.setAndKeepTTL(value);
} catch (Exception e) {
long timeToLive = bucket.remainTimeToLive();
setCacheObject(key, value, Duration.ofMillis(timeToLive));
}
} else {
bucket.set(value);
}
}
/**
* 缓存基本对象IntegerString实体类等
*
* @param key
* 缓存键
* @param value
* 缓存值
* @param duration
* 时间
*/
public static <T> void setCacheObject(final String key, final T value, final Duration duration) {
RBatch batch = REDISSON_CLIENT.createBatch();
RBucketAsync<T> bucket = batch.getBucket(key);
bucket.setAsync(value);
bucket.expireAsync(duration);
batch.execute();
}
/**
* 删除缓存的基本对象
*
* @param key
* 缓存键
*/
public static boolean deleteCacheObject(final String key) {
return REDISSON_CLIENT.getBucket(key).delete();
}
/**
* 删除缓存的基本对象列表
*
* @param keyPattern
* 缓存键表达式
*/
public static void deleteKeys(final String keyPattern) {
REDISSON_CLIENT.getKeys().deleteByPattern(getNameMapper().map(keyPattern));
}
/**
* 格式化缓存键将各子键用 : 拼接起来
*
* @param subKeys
* 子键列表
* @return 缓存键
*/
public static String formatKey(String... subKeys) {
return String.join(":", subKeys);
}
/**
* 根据集群或单机配置获取名称映射器
*
* @return 名称映射器
*/
private static NameMapper getNameMapper() {
Config config = REDISSON_CLIENT.getConfig();
if (config.isClusterConfig()) {
return config.useClusterServers().getNameMapper();
}
return config.useSingleServer().getNameMapper();
}
}

View File

@ -24,7 +24,7 @@ import java.util.List;
import cn.dev33.satoken.dao.SaTokenDao;
import cn.dev33.satoken.util.SaFoxUtil;
import top.charles7c.cnadmin.common.util.RedisUtils;
import top.charles7c.continew.starter.cache.redisson.util.RedisUtils;
/**
* Sa-Token 持久层本地 Redis 适配参考Sa-Token/sa-token-plugin/sa-token-dao-redisx/SaTokenDaoOfRedis.java
@ -37,7 +37,7 @@ public class SaTokenRedisDaoImpl implements SaTokenDao {
@Override
public String get(String key) {
return RedisUtils.getCacheObject(key);
return RedisUtils.get(key);
}
@Override
@ -47,9 +47,9 @@ public class SaTokenRedisDaoImpl implements SaTokenDao {
}
// 判断是否为永不过期
if (timeout == SaTokenDao.NEVER_EXPIRE) {
RedisUtils.setCacheObject(key, value);
RedisUtils.set(key, value);
} else {
RedisUtils.setCacheObject(key, value, Duration.ofSeconds(timeout));
RedisUtils.set(key, value, Duration.ofSeconds(timeout));
}
}
@ -65,7 +65,7 @@ public class SaTokenRedisDaoImpl implements SaTokenDao {
@Override
public void delete(String key) {
RedisUtils.deleteCacheObject(key);
RedisUtils.delete(key);
}
@Override
@ -92,7 +92,7 @@ public class SaTokenRedisDaoImpl implements SaTokenDao {
@Override
public Object getObject(String key) {
return RedisUtils.getCacheObject(key);
return RedisUtils.get(key);
}
@Override
@ -102,9 +102,9 @@ public class SaTokenRedisDaoImpl implements SaTokenDao {
}
// 判断是否为永不过期
if (timeout == SaTokenDao.NEVER_EXPIRE) {
RedisUtils.setCacheObject(key, object);
RedisUtils.set(key, object);
} else {
RedisUtils.setCacheObject(key, object, Duration.ofSeconds(timeout));
RedisUtils.set(key, object, Duration.ofSeconds(timeout));
}
}
@ -120,7 +120,7 @@ public class SaTokenRedisDaoImpl implements SaTokenDao {
@Override
public void deleteObject(String key) {
RedisUtils.deleteCacheObject(key);
RedisUtils.delete(key);
}
@Override

View File

@ -41,13 +41,13 @@ import top.charles7c.cnadmin.auth.model.resp.UserInfoResp;
import top.charles7c.cnadmin.auth.service.LoginService;
import top.charles7c.cnadmin.common.constant.CacheConsts;
import top.charles7c.cnadmin.common.model.dto.LoginUser;
import top.charles7c.cnadmin.common.util.RedisUtils;
import top.charles7c.cnadmin.common.util.SecureUtils;
import top.charles7c.cnadmin.common.util.helper.LoginHelper;
import top.charles7c.cnadmin.common.util.validate.ValidationUtils;
import top.charles7c.cnadmin.monitor.annotation.Log;
import top.charles7c.cnadmin.system.model.resp.UserDetailResp;
import top.charles7c.cnadmin.system.service.UserService;
import top.charles7c.continew.starter.cache.redisson.util.RedisUtils;
import top.charles7c.continew.starter.core.util.ExceptionUtils;
/**
@ -71,9 +71,9 @@ public class AuthController {
@PostMapping("/account")
public LoginResp accountLogin(@Validated @RequestBody AccountLoginReq loginReq) {
String captchaKey = RedisUtils.formatKey(CacheConsts.CAPTCHA_KEY_PREFIX, loginReq.getUuid());
String captcha = RedisUtils.getCacheObject(captchaKey);
String captcha = RedisUtils.get(captchaKey);
ValidationUtils.throwIfBlank(captcha, "验证码已失效");
RedisUtils.deleteCacheObject(captchaKey);
RedisUtils.delete(captchaKey);
ValidationUtils.throwIfNotEqualIgnoreCase(loginReq.getCaptcha(), captcha, "验证码错误");
// 用户登录
String rawPassword = ExceptionUtils.exToNull(() -> SecureUtils.decryptByRsaPrivateKey(loginReq.getPassword()));
@ -88,10 +88,10 @@ public class AuthController {
public LoginResp emailLogin(@Validated @RequestBody EmailLoginReq loginReq) {
String email = loginReq.getEmail();
String captchaKey = RedisUtils.formatKey(CacheConsts.CAPTCHA_KEY_PREFIX, email);
String captcha = RedisUtils.getCacheObject(captchaKey);
String captcha = RedisUtils.get(captchaKey);
ValidationUtils.throwIfBlank(captcha, "验证码已失效");
ValidationUtils.throwIfNotEqualIgnoreCase(loginReq.getCaptcha(), captcha, "验证码错误");
RedisUtils.deleteCacheObject(captchaKey);
RedisUtils.delete(captchaKey);
String token = loginService.emailLogin(email);
return LoginResp.builder().token(token).build();
}
@ -102,10 +102,10 @@ public class AuthController {
public LoginResp phoneLogin(@Validated @RequestBody PhoneLoginReq loginReq) {
String phone = loginReq.getPhone();
String captchaKey = RedisUtils.formatKey(CacheConsts.CAPTCHA_KEY_PREFIX, phone);
String captcha = RedisUtils.getCacheObject(captchaKey);
String captcha = RedisUtils.get(captchaKey);
ValidationUtils.throwIfBlank(captcha, "验证码已失效");
ValidationUtils.throwIfNotEqualIgnoreCase(loginReq.getCaptcha(), captcha, "验证码错误");
RedisUtils.deleteCacheObject(captchaKey);
RedisUtils.delete(captchaKey);
String token = loginService.phoneLogin(phone);
return LoginResp.builder().token(token).build();
}

View File

@ -53,9 +53,9 @@ import top.charles7c.cnadmin.common.constant.RegexConsts;
import top.charles7c.cnadmin.common.model.resp.CaptchaResp;
import top.charles7c.cnadmin.common.model.resp.R;
import top.charles7c.cnadmin.common.util.MailUtils;
import top.charles7c.cnadmin.common.util.RedisUtils;
import top.charles7c.cnadmin.common.util.TemplateUtils;
import top.charles7c.cnadmin.common.util.validate.CheckUtils;
import top.charles7c.continew.starter.cache.redisson.util.RedisUtils;
/**
* 验证码 API
@ -83,8 +83,7 @@ public class CaptchaController {
// 保存验证码
String uuid = IdUtil.fastUUID();
String captchaKey = RedisUtils.formatKey(CacheConsts.CAPTCHA_KEY_PREFIX, uuid);
RedisUtils.setCacheObject(captchaKey, captcha.text(),
Duration.ofMinutes(captchaImage.getExpirationInMinutes()));
RedisUtils.set(captchaKey, captcha.text(), Duration.ofMinutes(captchaImage.getExpirationInMinutes()));
return CaptchaResp.builder().uuid(uuid).img(captcha.toBase64()).build();
}
@ -108,8 +107,8 @@ public class CaptchaController {
MailUtils.sendHtml(email, String.format("【%s】邮箱验证码", projectProperties.getName()), content);
// 保存验证码
String captchaKey = RedisUtils.formatKey(captchaKeyPrefix, email);
RedisUtils.setCacheObject(captchaKey, captcha, Duration.ofMinutes(expirationInMinutes));
RedisUtils.setCacheObject(limitCaptchaKey, captcha, Duration.ofSeconds(captchaMail.getLimitInSeconds()));
RedisUtils.set(captchaKey, captcha, Duration.ofMinutes(expirationInMinutes));
RedisUtils.set(limitCaptchaKey, captcha, Duration.ofSeconds(captchaMail.getLimitInSeconds()));
return R.ok(String.format("发送成功,验证码有效期 %s 分钟", expirationInMinutes));
}
@ -136,8 +135,8 @@ public class CaptchaController {
CheckUtils.throwIf(!smsResponse.isSuccess(), "验证码发送失败");
// 保存验证码
String captchaKey = RedisUtils.formatKey(captchaKeyPrefix, phone);
RedisUtils.setCacheObject(captchaKey, captcha, Duration.ofMinutes(expirationInMinutes));
RedisUtils.setCacheObject(limitCaptchaKey, captcha, Duration.ofSeconds(captchaSms.getLimitInSeconds()));
RedisUtils.set(captchaKey, captcha, Duration.ofMinutes(expirationInMinutes));
RedisUtils.set(limitCaptchaKey, captcha, Duration.ofSeconds(captchaSms.getLimitInSeconds()));
return R.ok(String.format("发送成功,验证码有效期 %s 分钟", expirationInMinutes));
}
}

View File

@ -40,7 +40,6 @@ import top.charles7c.cnadmin.common.constant.CacheConsts;
import top.charles7c.cnadmin.common.constant.RegexConsts;
import top.charles7c.cnadmin.common.enums.SocialSourceEnum;
import top.charles7c.cnadmin.common.model.resp.R;
import top.charles7c.cnadmin.common.util.RedisUtils;
import top.charles7c.cnadmin.common.util.SecureUtils;
import top.charles7c.cnadmin.common.util.helper.LoginHelper;
import top.charles7c.cnadmin.common.util.validate.ValidationUtils;
@ -53,6 +52,7 @@ import top.charles7c.cnadmin.system.model.resp.AvatarResp;
import top.charles7c.cnadmin.system.model.resp.UserSocialBindResp;
import top.charles7c.cnadmin.system.service.UserService;
import top.charles7c.cnadmin.system.service.UserSocialService;
import top.charles7c.continew.starter.cache.redisson.util.RedisUtils;
import top.charles7c.continew.starter.core.util.ExceptionUtils;
import me.zhyd.oauth.model.AuthCallback;
@ -114,10 +114,10 @@ public class UserCenterController {
ExceptionUtils.exToNull(() -> SecureUtils.decryptByRsaPrivateKey(updateReq.getCurrentPassword()));
ValidationUtils.throwIfBlank(rawCurrentPassword, "当前密码解密失败");
String captchaKey = RedisUtils.formatKey(CacheConsts.CAPTCHA_KEY_PREFIX, updateReq.getNewPhone());
String captcha = RedisUtils.getCacheObject(captchaKey);
String captcha = RedisUtils.get(captchaKey);
ValidationUtils.throwIfBlank(captcha, "验证码已失效");
ValidationUtils.throwIfNotEqualIgnoreCase(updateReq.getCaptcha(), captcha, "验证码错误");
RedisUtils.deleteCacheObject(captchaKey);
RedisUtils.delete(captchaKey);
userService.updatePhone(updateReq.getNewPhone(), rawCurrentPassword, LoginHelper.getUserId());
return R.ok("修改成功");
}
@ -129,10 +129,10 @@ public class UserCenterController {
ExceptionUtils.exToNull(() -> SecureUtils.decryptByRsaPrivateKey(updateReq.getCurrentPassword()));
ValidationUtils.throwIfBlank(rawCurrentPassword, "当前密码解密失败");
String captchaKey = RedisUtils.formatKey(CacheConsts.CAPTCHA_KEY_PREFIX, updateReq.getNewEmail());
String captcha = RedisUtils.getCacheObject(captchaKey);
String captcha = RedisUtils.get(captchaKey);
ValidationUtils.throwIfBlank(captcha, "验证码已失效");
ValidationUtils.throwIfNotEqualIgnoreCase(updateReq.getCaptcha(), captcha, "验证码错误");
RedisUtils.deleteCacheObject(captchaKey);
RedisUtils.delete(captchaKey);
userService.updateEmail(updateReq.getNewEmail(), rawCurrentPassword, LoginHelper.getUserId());
return R.ok("修改成功");
}

View File

@ -71,6 +71,9 @@ spring.data:
# 是否开启 SSL
ssl:
enabled: false
redisson:
enabled: true
mode: single
--- ### Spring Cache 配置
spring.cache:

View File

@ -73,6 +73,9 @@ spring.data:
# 是否开启 SSL
ssl:
enabled: false
redisson:
enabled: true
mode: single
--- ### Spring Cache 配置
spring.cache:

View File

@ -40,7 +40,6 @@
<justauth.version>1.16.5</justauth.version>
<easyexcel.version>3.3.2</easyexcel.version>
<ip2region.version>3.1.5.1</ip2region.version>
<redisson.version>3.24.3</redisson.version>
<easy-captcha.version>1.6.2</easy-captcha.version>
<hutool.version>5.8.22</hutool.version>
@ -138,13 +137,6 @@
<version>${ip2region.version}</version>
</dependency>
<!-- Redisson不仅仅是一个 Redis Java 客户端) -->
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson-spring-boot-starter</artifactId>
<version>${redisson.version}</version>
</dependency>
<!-- Easy CaptchaJava 图形验证码,支持 gif、中文、算术等类型可用于 Java Web、JavaSE 等项目) -->
<dependency>
<groupId>com.github.whvcse</groupId>