From 8ea4225f1e8909f9749fd080d35a5dfb2d4a3781 Mon Sep 17 00:00:00 2001 From: HueFu Date: Tue, 6 Aug 2024 17:26:54 +0800 Subject: [PATCH] =?UTF-8?q?fix(=E9=80=82=E9=85=8D=E5=8F=91=E5=B8=83?= =?UTF-8?q?=E7=B3=BB=E7=BB=9F=E9=A1=B9=E7=9B=AE=E9=9C=80=E6=B1=82)?= =?UTF-8?q?=EF=BC=9A=20=E5=8E=BB=E9=99=A4=20redis=20=E6=B7=BB=E5=8A=A0=20?= =?UTF-8?q?=E6=9C=AC=E5=9C=B0=E7=BC=93=E5=AD=98=EF=BC=9B=E6=9B=BF=E6=8D=A2?= =?UTF-8?q?=20mybatis=20=E4=B8=BAmybatisPlus?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 9 ++ pom.xml | 17 ++- .../main/java/com/ruoyi/RuoYiApplication.java | 22 +-- .../controller/common/CaptchaController.java | 60 +++----- .../controller/monitor/CacheController.java | 71 ++++++---- .../monitor/SysUserOnlineController.java | 29 ++-- .../web/controller/tool/TestController.java | 2 + .../src/main/resources/application-druid.yml | 5 +- .../src/main/resources/application.yml | 69 +++++---- ruoyi-admin/src/main/resources/logback.xml | 3 +- ruoyi-common/pom.xml | 24 ++++ .../ruoyi/common/constant/CacheConstants.java | 14 +- .../com/ruoyi/common/utils/DictUtils.java | 28 ++-- .../framework/aspectj/RateLimiterAspect.java | 19 +-- .../ruoyi/framework/config/MyBatisConfig.java | 132 ------------------ .../ruoyi/framework/config/RedisConfig.java | 39 +++++- .../impl/SameUrlDataInterceptor.java | 29 ++-- .../web/service/SysLoginService.java | 30 ++-- .../web/service/SysPasswordService.java | 36 ++--- .../web/service/SysRegisterService.java | 16 +-- .../framework/web/service/TokenService.java | 25 ++-- .../ruoyi/system/mapper/SysConfigMapper.java | 1 + .../service/impl/SysConfigServiceImpl.java | 44 +++--- 23 files changed, 313 insertions(+), 411 deletions(-) mode change 100644 => 100755 ruoyi-admin/src/main/java/com/ruoyi/web/controller/monitor/CacheController.java mode change 100644 => 100755 ruoyi-admin/src/main/java/com/ruoyi/web/controller/monitor/SysUserOnlineController.java mode change 100644 => 100755 ruoyi-common/src/main/java/com/ruoyi/common/constant/CacheConstants.java mode change 100644 => 100755 ruoyi-common/src/main/java/com/ruoyi/common/utils/DictUtils.java mode change 100644 => 100755 ruoyi-framework/src/main/java/com/ruoyi/framework/aspectj/RateLimiterAspect.java delete mode 100644 ruoyi-framework/src/main/java/com/ruoyi/framework/config/MyBatisConfig.java mode change 100644 => 100755 ruoyi-framework/src/main/java/com/ruoyi/framework/config/RedisConfig.java mode change 100644 => 100755 ruoyi-framework/src/main/java/com/ruoyi/framework/interceptor/impl/SameUrlDataInterceptor.java mode change 100644 => 100755 ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/SysLoginService.java mode change 100644 => 100755 ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/SysPasswordService.java mode change 100644 => 100755 ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/SysRegisterService.java mode change 100644 => 100755 ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/TokenService.java mode change 100644 => 100755 ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysConfigServiceImpl.java diff --git a/.gitignore b/.gitignore index 0c0da3e0..3e596494 100644 --- a/.gitignore +++ b/.gitignore @@ -35,6 +35,7 @@ nbbuild/ dist/ nbdist/ .nb-gradle/ +pnpm-lock.yaml ###################################################################### # Others @@ -45,3 +46,11 @@ nbdist/ !*/build/*.java !*/build/*.html !*/build/*.xml + +/logs +/doc +/bin +/.github + +/ry.bat +/LICENSE \ No newline at end of file diff --git a/pom.xml b/pom.xml index 05478cd6..440631d6 100644 --- a/pom.xml +++ b/pom.xml @@ -9,7 +9,6 @@ 3.8.8 ruoyi - http://www.ruoyi.vip 若依管理系统 @@ -20,6 +19,8 @@ 3.1.1 5.3.33 5.7.12 + 2.5.15 + 3.10.8 1.2.23 1.21 3.0.0 @@ -64,6 +65,20 @@ import + + + org.springframework.boot + spring-boot-starter-cache + ${spring-cache.version} + + + + + org.ehcache + ehcache + ${ehcache.version} + + com.alibaba diff --git a/ruoyi-admin/src/main/java/com/ruoyi/RuoYiApplication.java b/ruoyi-admin/src/main/java/com/ruoyi/RuoYiApplication.java index e3c56ee5..bd8a7db8 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/RuoYiApplication.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/RuoYiApplication.java @@ -3,6 +3,7 @@ package com.ruoyi; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; +import org.springframework.cache.annotation.EnableCaching; /** * 启动程序 @@ -10,21 +11,22 @@ import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; * @author ruoyi */ @SpringBootApplication(exclude = { DataSourceAutoConfiguration.class }) +@EnableCaching public class RuoYiApplication { public static void main(String[] args) { // System.setProperty("spring.devtools.restart.enabled", "false"); SpringApplication.run(RuoYiApplication.class, args); - System.out.println("(♥◠‿◠)ノ゙ 若依启动成功 ლ(´ڡ`ლ)゙ \n" + - " .-------. ____ __ \n" + - " | _ _ \\ \\ \\ / / \n" + - " | ( ' ) | \\ _. / ' \n" + - " |(_ o _) / _( )_ .' \n" + - " | (_,_).' __ ___(_ o _)' \n" + - " | |\\ \\ | || |(_,_)' \n" + - " | | \\ `' /| `-' / \n" + - " | | \\ / \\ / \n" + - " ''-' `'-' `-..-' "); +// System.out.println("(♥◠‿◠)ノ゙ 若依启动成功 ლ(´ڡ`ლ)゙ \n" + +// " .-------. ____ __ \n" + +// " | _ _ \\ \\ \\ / / \n" + +// " | ( ' ) | \\ _. / ' \n" + +// " |(_ o _) / _( )_ .' \n" + +// " | (_,_).' __ ___(_ o _)' \n" + +// " | |\\ \\ | || |(_,_)' \n" + +// " | | \\ `' /| `-' / \n" + +// " | | \\ / \\ / \n" + +// " ''-' `'-' `-..-' "); } } diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/common/CaptchaController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/common/CaptchaController.java index e1a397e6..f6f89dcf 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/common/CaptchaController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/common/CaptchaController.java @@ -1,92 +1,76 @@ package com.ruoyi.web.controller.common; -import java.awt.image.BufferedImage; -import java.io.IOException; -import java.util.concurrent.TimeUnit; -import javax.annotation.Resource; -import javax.imageio.ImageIO; -import javax.servlet.http.HttpServletResponse; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.util.FastByteArrayOutputStream; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RestController; import com.google.code.kaptcha.Producer; import com.ruoyi.common.config.RuoYiConfig; import com.ruoyi.common.constant.CacheConstants; import com.ruoyi.common.constant.Constants; import com.ruoyi.common.core.domain.AjaxResult; -import com.ruoyi.common.core.redis.RedisCache; +import com.ruoyi.common.utils.CacheUtils; import com.ruoyi.common.utils.sign.Base64; import com.ruoyi.common.utils.uuid.IdUtils; import com.ruoyi.system.service.ISysConfigService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.util.FastByteArrayOutputStream; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import javax.annotation.Resource; +import javax.imageio.ImageIO; +import javax.servlet.http.HttpServletResponse; +import java.awt.image.BufferedImage; +import java.io.IOException; +import java.util.concurrent.TimeUnit; /** * 验证码操作处理 - * + * * @author ruoyi */ @RestController -public class CaptchaController -{ +public class CaptchaController { @Resource(name = "captchaProducer") private Producer captchaProducer; @Resource(name = "captchaProducerMath") private Producer captchaProducerMath; - @Autowired - private RedisCache redisCache; - @Autowired private ISysConfigService configService; + /** * 生成验证码 */ @GetMapping("/captchaImage") - public AjaxResult getCode(HttpServletResponse response) throws IOException - { + public AjaxResult getCode(HttpServletResponse response) throws IOException { AjaxResult ajax = AjaxResult.success(); boolean captchaEnabled = configService.selectCaptchaEnabled(); ajax.put("captchaEnabled", captchaEnabled); - if (!captchaEnabled) - { + if (!captchaEnabled) { return ajax; } - // 保存验证码信息 String uuid = IdUtils.simpleUUID(); - String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid; - String capStr = null, code = null; BufferedImage image = null; - // 生成验证码 String captchaType = RuoYiConfig.getCaptchaType(); - if ("math".equals(captchaType)) - { + if ("math".equals(captchaType)) { String capText = captchaProducerMath.createText(); capStr = capText.substring(0, capText.lastIndexOf("@")); code = capText.substring(capText.lastIndexOf("@") + 1); image = captchaProducerMath.createImage(capStr); - } - else if ("char".equals(captchaType)) - { + } else if ("char".equals(captchaType)) { capStr = code = captchaProducer.createText(); image = captchaProducer.createImage(capStr); } - - redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES); + CacheUtils.put(CacheConstants.CAPTCHA_CODE_KEY, uuid, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES); // 转换流信息写出 FastByteArrayOutputStream os = new FastByteArrayOutputStream(); - try - { + try { ImageIO.write(image, "jpg", os); - } - catch (IOException e) - { + } catch (IOException e) { return AjaxResult.error(e.getMessage()); } - ajax.put("uuid", uuid); ajax.put("img", Base64.encode(os.toByteArray())); return ajax; diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/monitor/CacheController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/monitor/CacheController.java old mode 100644 new mode 100755 index 504c0fde..9619dbd6 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/monitor/CacheController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/monitor/CacheController.java @@ -1,16 +1,15 @@ package com.ruoyi.web.controller.monitor; import java.util.ArrayList; -import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.TreeSet; -import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cache.Cache.ValueWrapper; +import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.core.RedisCallback; -import org.springframework.data.redis.core.RedisTemplate; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; @@ -19,6 +18,8 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.ruoyi.common.constant.CacheConstants; import com.ruoyi.common.core.domain.AjaxResult; +import com.ruoyi.common.core.text.Convert; +import com.ruoyi.common.utils.CacheUtils; import com.ruoyi.common.utils.StringUtils; import com.ruoyi.system.domain.SysCache; @@ -31,9 +32,8 @@ import com.ruoyi.system.domain.SysCache; @RequestMapping("/monitor/cache") public class CacheController { - @Autowired - private RedisTemplate redisTemplate; - + private static String tmpCacheName = ""; + private final static List caches = new ArrayList(); { caches.add(new SysCache(CacheConstants.LOGIN_TOKEN_KEY, "用户信息")); @@ -49,23 +49,24 @@ public class CacheController @GetMapping() public AjaxResult getInfo() throws Exception { - Properties info = (Properties) redisTemplate.execute((RedisCallback) connection -> connection.info()); - Properties commandStats = (Properties) redisTemplate.execute((RedisCallback) connection -> connection.info("commandstats")); - Object dbSize = redisTemplate.execute((RedisCallback) connection -> connection.dbSize()); - Map result = new HashMap<>(3); - result.put("info", info); - result.put("dbSize", dbSize); - - List> pieList = new ArrayList<>(); - commandStats.stringPropertyNames().forEach(key -> { - Map data = new HashMap<>(2); - String property = commandStats.getProperty(key); - data.put("name", StringUtils.removeStart(key, "cmdstat_")); - data.put("value", StringUtils.substringBetween(property, "calls=", ",usec")); - pieList.add(data); - }); - result.put("commandStats", pieList); + if (CacheUtils.getCacheManager() instanceof RedisCacheManager) + { + Properties info = (Properties) CacheUtils.getRedisTemplate().execute((RedisCallback) connection -> connection.info()); + Properties commandStats = (Properties) CacheUtils.getRedisTemplate().execute((RedisCallback) connection -> connection.info("commandstats")); + Object dbSize = CacheUtils.getRedisTemplate().execute((RedisCallback) connection -> connection.dbSize()); + result.put("info", info); + result.put("dbSize", dbSize); + List> pieList = new ArrayList<>(); + commandStats.stringPropertyNames().forEach(key -> { + Map data = new HashMap<>(2); + String property = commandStats.getProperty(key); + data.put("name", StringUtils.removeStart(key, "cmdstat_")); + data.put("value", StringUtils.substringBetween(property, "calls=", ",usec")); + pieList.add(data); + }); + result.put("commandStats", pieList); + } return AjaxResult.success(result); } @@ -80,16 +81,23 @@ public class CacheController @GetMapping("/getKeys/{cacheName}") public AjaxResult getCacheKeys(@PathVariable String cacheName) { - Set cacheKeys = redisTemplate.keys(cacheName + "*"); - return AjaxResult.success(new TreeSet<>(cacheKeys)); + tmpCacheName = cacheName; + Set keyset = CacheUtils.getkeys(cacheName); + return AjaxResult.success(new TreeSet<>(keyset)); } @PreAuthorize("@ss.hasPermi('monitor:cache:list')") @GetMapping("/getValue/{cacheName}/{cacheKey}") public AjaxResult getCacheValue(@PathVariable String cacheName, @PathVariable String cacheKey) { - String cacheValue = redisTemplate.opsForValue().get(cacheKey); - SysCache sysCache = new SysCache(cacheName, cacheKey, cacheValue); + ValueWrapper valueWrapper = CacheUtils.get(cacheName, cacheKey); + SysCache sysCache = new SysCache(); + sysCache.setCacheName(cacheName); + sysCache.setCacheKey(cacheKey); + if (StringUtils.isNotNull(valueWrapper)) + { + sysCache.setCacheValue(Convert.toStr(valueWrapper.get(), "")); + } return AjaxResult.success(sysCache); } @@ -97,8 +105,7 @@ public class CacheController @DeleteMapping("/clearCacheName/{cacheName}") public AjaxResult clearCacheName(@PathVariable String cacheName) { - Collection cacheKeys = redisTemplate.keys(cacheName + "*"); - redisTemplate.delete(cacheKeys); + CacheUtils.clear(cacheName); return AjaxResult.success(); } @@ -106,7 +113,7 @@ public class CacheController @DeleteMapping("/clearCacheKey/{cacheKey}") public AjaxResult clearCacheKey(@PathVariable String cacheKey) { - redisTemplate.delete(cacheKey); + CacheUtils.removeIfPresent(tmpCacheName, cacheKey); return AjaxResult.success(); } @@ -114,8 +121,10 @@ public class CacheController @DeleteMapping("/clearCacheAll") public AjaxResult clearCacheAll() { - Collection cacheKeys = redisTemplate.keys("*"); - redisTemplate.delete(cacheKeys); + for (String cacheName : CacheUtils.getCacheManager().getCacheNames()) + { + CacheUtils.clear(cacheName); + } return AjaxResult.success(); } } diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/monitor/SysUserOnlineController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/monitor/SysUserOnlineController.java old mode 100644 new mode 100755 index 7c343e21..20b646dd --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/monitor/SysUserOnlineController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/monitor/SysUserOnlineController.java @@ -1,27 +1,23 @@ package com.ruoyi.web.controller.monitor; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.web.bind.annotation.DeleteMapping; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; import com.ruoyi.common.annotation.Log; import com.ruoyi.common.constant.CacheConstants; import com.ruoyi.common.core.controller.BaseController; import com.ruoyi.common.core.domain.AjaxResult; import com.ruoyi.common.core.domain.model.LoginUser; import com.ruoyi.common.core.page.TableDataInfo; -import com.ruoyi.common.core.redis.RedisCache; import com.ruoyi.common.enums.BusinessType; +import com.ruoyi.common.utils.CacheUtils; import com.ruoyi.common.utils.StringUtils; import com.ruoyi.system.domain.SysUserOnline; import com.ruoyi.system.service.ISysUserOnlineService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; /** * 在线用户监控 @@ -35,18 +31,15 @@ public class SysUserOnlineController extends BaseController @Autowired private ISysUserOnlineService userOnlineService; - @Autowired - private RedisCache redisCache; - @PreAuthorize("@ss.hasPermi('monitor:online:list')") @GetMapping("/list") public TableDataInfo list(String ipaddr, String userName) { - Collection keys = redisCache.keys(CacheConstants.LOGIN_TOKEN_KEY + "*"); + Collection keys = CacheUtils.getkeys(CacheConstants.LOGIN_TOKEN_KEY); List userOnlineList = new ArrayList(); for (String key : keys) { - LoginUser user = redisCache.getCacheObject(key); + LoginUser user = CacheUtils.get(CacheConstants.LOGIN_TOKEN_KEY, key, LoginUser.class); if (StringUtils.isNotEmpty(ipaddr) && StringUtils.isNotEmpty(userName)) { userOnlineList.add(userOnlineService.selectOnlineByInfo(ipaddr, userName, user)); @@ -77,7 +70,7 @@ public class SysUserOnlineController extends BaseController @DeleteMapping("/{tokenId}") public AjaxResult forceLogout(@PathVariable String tokenId) { - redisCache.deleteObject(CacheConstants.LOGIN_TOKEN_KEY + tokenId); + CacheUtils.removeIfPresent(CacheConstants.LOGIN_TOKEN_KEY, tokenId); return success(); } } diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/tool/TestController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/tool/TestController.java index c55f9749..387908a3 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/tool/TestController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/tool/TestController.java @@ -4,6 +4,8 @@ import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; + +import com.ruoyi.common.utils.CacheUtils; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; diff --git a/ruoyi-admin/src/main/resources/application-druid.yml b/ruoyi-admin/src/main/resources/application-druid.yml index bcfad3ea..8fecda1a 100644 --- a/ruoyi-admin/src/main/resources/application-druid.yml +++ b/ruoyi-admin/src/main/resources/application-druid.yml @@ -6,9 +6,10 @@ spring: druid: # 主库数据源 master: - url: jdbc:mysql://localhost:3306/ry-vue?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8 +# url: jdbc:mysql://localhost:3306/ry-vue?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8 + url: jdbc:mysql://192.168.2.137:33306/ry-vue?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8 username: root - password: password + password: 1qaz@WSX # 从库数据源 slave: # 从数据源开关/默认关闭 diff --git a/ruoyi-admin/src/main/resources/application.yml b/ruoyi-admin/src/main/resources/application.yml index c777ac14..a7c0d851 100644 --- a/ruoyi-admin/src/main/resources/application.yml +++ b/ruoyi-admin/src/main/resources/application.yml @@ -65,28 +65,38 @@ spring: restart: # 热部署开关 enabled: true - # redis 配置 - redis: - # 地址 - host: localhost - # 端口,默认为6379 - port: 6379 - # 数据库索引 - database: 0 - # 密码 - password: - # 连接超时时间 - timeout: 10s - lettuce: - pool: - # 连接池中的最小空闲连接 - min-idle: 0 - # 连接池中的最大空闲连接 - max-idle: 8 - # 连接池的最大数据库连接数 - max-active: 8 - # #连接池最大阻塞等待时间(使用负值表示没有限制) - max-wait: -1ms + cache: + # 指定缓存类型 ehcache 本地缓存 redis 缓存 + type: ehcache + ehcache: + config: classpath:ehcache.xml + redis: + # 指定存活时间(ms) + time-to-live: 86400000 + # 指定前缀 + use-key-prefix: true + # 是否缓存空值,可以防止缓存穿透 + cache-null-values: true + # 地址 + host: 192.168.2.137 + # 端口,默认为6379 + port: 26379 + # 数据库索引 + database: 0 + # 密码 + password: + # 连接超时时间 + timeout: 10s + lettuce: + pool: + # 连接池中的最小空闲连接 + min-idle: 0 + # 连接池中的最大空闲连接 + max-idle: 8 + # 连接池的最大数据库连接数 + max-active: 8 + # #连接池最大阻塞等待时间(使用负值表示没有限制) + max-wait: -1ms # token配置 token: @@ -97,8 +107,17 @@ token: # 令牌有效期(默认30分钟) expireTime: 30 -# MyBatis配置 -mybatis: +## MyBatis配置 +#mybatis: +# # 搜索指定包别名 +# typeAliasesPackage: com.ruoyi.**.domain +# # 配置mapper的扫描,找到所有的mapper.xml映射文件 +# mapperLocations: classpath*:mapper/**/*Mapper.xml +# # 加载全局的配置文件 +# configLocation: classpath:mybatis/mybatis-config.xml + +# MyBatis Plus配置 +mybatis-plus: # 搜索指定包别名 typeAliasesPackage: com.ruoyi.**.domain # 配置mapper的扫描,找到所有的mapper.xml映射文件 @@ -115,7 +134,7 @@ pagehelper: # Swagger配置 swagger: # 是否开启swagger - enabled: true + enabled: false # 请求前缀 pathMapping: /dev-api diff --git a/ruoyi-admin/src/main/resources/logback.xml b/ruoyi-admin/src/main/resources/logback.xml index d69a5720..9fb0d414 100644 --- a/ruoyi-admin/src/main/resources/logback.xml +++ b/ruoyi-admin/src/main/resources/logback.xml @@ -1,7 +1,8 @@ - + + diff --git a/ruoyi-common/pom.xml b/ruoyi-common/pom.xml index 56c3f819..5d661d52 100644 --- a/ruoyi-common/pom.xml +++ b/ruoyi-common/pom.xml @@ -119,6 +119,30 @@ javax.servlet-api + + + org.springframework.boot + spring-boot-starter-cache + + + + + net.sf.ehcache + ehcache + + + + + com.baomidou + mybatis-plus-boot-starter + 3.5.4 + + + + org.projectlombok + lombok + + \ No newline at end of file diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/constant/CacheConstants.java b/ruoyi-common/src/main/java/com/ruoyi/common/constant/CacheConstants.java old mode 100644 new mode 100755 index c89692c2..adfe20b9 --- a/ruoyi-common/src/main/java/com/ruoyi/common/constant/CacheConstants.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/constant/CacheConstants.java @@ -10,35 +10,35 @@ public class CacheConstants /** * 登录用户 redis key */ - public static final String LOGIN_TOKEN_KEY = "login_tokens:"; + public static final String LOGIN_TOKEN_KEY = "login_tokens"; /** * 验证码 redis key */ - public static final String CAPTCHA_CODE_KEY = "captcha_codes:"; + public static final String CAPTCHA_CODE_KEY = "captcha_codes"; /** * 参数管理 cache key */ - public static final String SYS_CONFIG_KEY = "sys_config:"; + public static final String SYS_CONFIG_KEY = "sys_config"; /** * 字典管理 cache key */ - public static final String SYS_DICT_KEY = "sys_dict:"; + public static final String SYS_DICT_KEY = "sys_dict"; /** * 防重提交 redis key */ - public static final String REPEAT_SUBMIT_KEY = "repeat_submit:"; + public static final String REPEAT_SUBMIT_KEY = "repeat_submit"; /** * 限流 redis key */ - public static final String RATE_LIMIT_KEY = "rate_limit:"; + public static final String RATE_LIMIT_KEY = "rate_limit"; /** * 登录账户密码错误次数 redis key */ - public static final String PWD_ERR_CNT_KEY = "pwd_err_cnt:"; + public static final String PWD_ERR_CNT_KEY = "pwd_err_cnt"; } diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/utils/DictUtils.java b/ruoyi-common/src/main/java/com/ruoyi/common/utils/DictUtils.java old mode 100644 new mode 100755 index 8204f133..9cbedaea --- a/ruoyi-common/src/main/java/com/ruoyi/common/utils/DictUtils.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/utils/DictUtils.java @@ -1,12 +1,9 @@ package com.ruoyi.common.utils; -import java.util.Collection; -import java.util.List; -import com.alibaba.fastjson2.JSONArray; import com.ruoyi.common.constant.CacheConstants; import com.ruoyi.common.core.domain.entity.SysDictData; -import com.ruoyi.common.core.redis.RedisCache; -import com.ruoyi.common.utils.spring.SpringUtils; +import org.springframework.cache.Cache; +import java.util.List; /** * 字典工具类 @@ -28,7 +25,7 @@ public class DictUtils */ public static void setDictCache(String key, List dictDatas) { - SpringUtils.getBean(RedisCache.class).setCacheObject(getCacheKey(key), dictDatas); + getDictCacheKey().put(key, dictDatas); } /** @@ -37,12 +34,13 @@ public class DictUtils * @param key 参数键 * @return dictDatas 字典数据列表 */ + @SuppressWarnings("unchecked") public static List getDictCache(String key) { - JSONArray arrayCache = SpringUtils.getBean(RedisCache.class).getCacheObject(getCacheKey(key)); + List arrayCache = (List) getDictCacheKey().get(key, List.class); if (StringUtils.isNotNull(arrayCache)) { - return arrayCache.toList(SysDictData.class); + return arrayCache; } return null; } @@ -214,7 +212,7 @@ public class DictUtils */ public static void removeDictCache(String key) { - SpringUtils.getBean(RedisCache.class).deleteObject(getCacheKey(key)); + getDictCacheKey().evict(key); } /** @@ -222,18 +220,16 @@ public class DictUtils */ public static void clearDictCache() { - Collection keys = SpringUtils.getBean(RedisCache.class).keys(CacheConstants.SYS_DICT_KEY + "*"); - SpringUtils.getBean(RedisCache.class).deleteObject(keys); + getDictCacheKey().clear(); } /** - * 设置cache key + * 获取dict缓存 * - * @param configKey 参数键 - * @return 缓存键key + * @return 缓存Cache */ - public static String getCacheKey(String configKey) + public static Cache getDictCacheKey() { - return CacheConstants.SYS_DICT_KEY + configKey; + return CacheUtils.getCache(CacheConstants.SYS_DICT_KEY); } } diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/aspectj/RateLimiterAspect.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/aspectj/RateLimiterAspect.java old mode 100644 new mode 100755 index a2015d70..7cf89c1a --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/aspectj/RateLimiterAspect.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/aspectj/RateLimiterAspect.java @@ -1,8 +1,10 @@ package com.ruoyi.framework.aspectj; -import java.lang.reflect.Method; -import java.util.Collections; -import java.util.List; +import com.ruoyi.common.annotation.RateLimiter; +import com.ruoyi.common.enums.LimitType; +import com.ruoyi.common.exception.ServiceException; +import com.ruoyi.common.utils.StringUtils; +import com.ruoyi.common.utils.ip.IpUtils; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; @@ -10,14 +12,13 @@ import org.aspectj.lang.reflect.MethodSignature; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.script.RedisScript; import org.springframework.stereotype.Component; -import com.ruoyi.common.annotation.RateLimiter; -import com.ruoyi.common.enums.LimitType; -import com.ruoyi.common.exception.ServiceException; -import com.ruoyi.common.utils.StringUtils; -import com.ruoyi.common.utils.ip.IpUtils; +import java.lang.reflect.Method; +import java.util.Collections; +import java.util.List; /** * 限流处理 @@ -26,6 +27,7 @@ import com.ruoyi.common.utils.ip.IpUtils; */ @Aspect @Component +@ConditionalOnProperty(prefix = "spring.cache", name = { "type" }, havingValue = "redis", matchIfMissing = false) public class RateLimiterAspect { private static final Logger log = LoggerFactory.getLogger(RateLimiterAspect.class); @@ -51,7 +53,6 @@ public class RateLimiterAspect { int time = rateLimiter.time(); int count = rateLimiter.count(); - String combineKey = getCombineKey(rateLimiter, point); List keys = Collections.singletonList(combineKey); try diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/config/MyBatisConfig.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/config/MyBatisConfig.java deleted file mode 100644 index e30fe74f..00000000 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/config/MyBatisConfig.java +++ /dev/null @@ -1,132 +0,0 @@ -package com.ruoyi.framework.config; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import javax.sql.DataSource; -import org.apache.ibatis.io.VFS; -import org.apache.ibatis.session.SqlSessionFactory; -import org.mybatis.spring.SqlSessionFactoryBean; -import org.mybatis.spring.boot.autoconfigure.SpringBootVFS; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.env.Environment; -import org.springframework.core.io.DefaultResourceLoader; -import org.springframework.core.io.Resource; -import org.springframework.core.io.support.PathMatchingResourcePatternResolver; -import org.springframework.core.io.support.ResourcePatternResolver; -import org.springframework.core.type.classreading.CachingMetadataReaderFactory; -import org.springframework.core.type.classreading.MetadataReader; -import org.springframework.core.type.classreading.MetadataReaderFactory; -import org.springframework.util.ClassUtils; -import com.ruoyi.common.utils.StringUtils; - -/** - * Mybatis支持*匹配扫描包 - * - * @author ruoyi - */ -@Configuration -public class MyBatisConfig -{ - @Autowired - private Environment env; - - static final String DEFAULT_RESOURCE_PATTERN = "**/*.class"; - - public static String setTypeAliasesPackage(String typeAliasesPackage) - { - ResourcePatternResolver resolver = (ResourcePatternResolver) new PathMatchingResourcePatternResolver(); - MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resolver); - List allResult = new ArrayList(); - try - { - for (String aliasesPackage : typeAliasesPackage.split(",")) - { - List result = new ArrayList(); - aliasesPackage = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX - + ClassUtils.convertClassNameToResourcePath(aliasesPackage.trim()) + "/" + DEFAULT_RESOURCE_PATTERN; - Resource[] resources = resolver.getResources(aliasesPackage); - if (resources != null && resources.length > 0) - { - MetadataReader metadataReader = null; - for (Resource resource : resources) - { - if (resource.isReadable()) - { - metadataReader = metadataReaderFactory.getMetadataReader(resource); - try - { - result.add(Class.forName(metadataReader.getClassMetadata().getClassName()).getPackage().getName()); - } - catch (ClassNotFoundException e) - { - e.printStackTrace(); - } - } - } - } - if (result.size() > 0) - { - HashSet hashResult = new HashSet(result); - allResult.addAll(hashResult); - } - } - if (allResult.size() > 0) - { - typeAliasesPackage = String.join(",", (String[]) allResult.toArray(new String[0])); - } - else - { - throw new RuntimeException("mybatis typeAliasesPackage 路径扫描错误,参数typeAliasesPackage:" + typeAliasesPackage + "未找到任何包"); - } - } - catch (IOException e) - { - e.printStackTrace(); - } - return typeAliasesPackage; - } - - public Resource[] resolveMapperLocations(String[] mapperLocations) - { - ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver(); - List resources = new ArrayList(); - if (mapperLocations != null) - { - for (String mapperLocation : mapperLocations) - { - try - { - Resource[] mappers = resourceResolver.getResources(mapperLocation); - resources.addAll(Arrays.asList(mappers)); - } - catch (IOException e) - { - // ignore - } - } - } - return resources.toArray(new Resource[resources.size()]); - } - - @Bean - public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception - { - String typeAliasesPackage = env.getProperty("mybatis.typeAliasesPackage"); - String mapperLocations = env.getProperty("mybatis.mapperLocations"); - String configLocation = env.getProperty("mybatis.configLocation"); - typeAliasesPackage = setTypeAliasesPackage(typeAliasesPackage); - VFS.addImplClass(SpringBootVFS.class); - - final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(); - sessionFactory.setDataSource(dataSource); - sessionFactory.setTypeAliasesPackage(typeAliasesPackage); - sessionFactory.setMapperLocations(resolveMapperLocations(StringUtils.split(mapperLocations, ","))); - sessionFactory.setConfigLocation(new DefaultResourceLoader().getResource(configLocation)); - return sessionFactory.getObject(); - } -} \ No newline at end of file diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/config/RedisConfig.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/config/RedisConfig.java old mode 100644 new mode 100755 index b188ac29..2551d1a4 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/config/RedisConfig.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/config/RedisConfig.java @@ -1,13 +1,19 @@ package com.ruoyi.framework.config; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.CachingConfigurerSupport; -import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; +import org.springframework.data.redis.cache.RedisCacheConfiguration; +import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.script.DefaultRedisScript; +import org.springframework.data.redis.serializer.RedisSerializationContext; import org.springframework.data.redis.serializer.StringRedisSerializer; +import java.time.Duration; /** * redis配置 @@ -15,26 +21,47 @@ import org.springframework.data.redis.serializer.StringRedisSerializer; * @author ruoyi */ @Configuration -@EnableCaching +@ConditionalOnProperty(prefix = "spring.cache", name = { "type" }, havingValue = "redis", matchIfMissing = false) public class RedisConfig extends CachingConfigurerSupport { + @Bean + @Primary + public CacheManager cacheManager(RedisConnectionFactory connectionFactory) + { + RedisCacheConfiguration config = instanceConfig(3600 * 24 * 15L); + return RedisCacheManager.builder(connectionFactory).cacheDefaults(config).transactionAware().build(); + } + + @Bean + public CacheManager cacheManager30m(RedisConnectionFactory connectionFactory) + { + RedisCacheConfiguration config = instanceConfig(1800L); + return RedisCacheManager.builder(connectionFactory).cacheDefaults(config).transactionAware().build(); + } + + @SuppressWarnings(value = { "unchecked", "rawtypes" }) + private RedisCacheConfiguration instanceConfig(Long ttl) + { + FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer(Object.class); + return RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofSeconds(ttl)).disableCachingNullValues() + .computePrefixWith(name -> name + ":") + .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer())) + .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(serializer)); + } + @Bean @SuppressWarnings(value = { "unchecked", "rawtypes" }) public RedisTemplate redisTemplate(RedisConnectionFactory connectionFactory) { RedisTemplate template = new RedisTemplate<>(); template.setConnectionFactory(connectionFactory); - FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer(Object.class); - // 使用StringRedisSerializer来序列化和反序列化redis的key值 template.setKeySerializer(new StringRedisSerializer()); template.setValueSerializer(serializer); - // Hash的key也采用StringRedisSerializer的序列化方式 template.setHashKeySerializer(new StringRedisSerializer()); template.setHashValueSerializer(serializer); - template.afterPropertiesSet(); return template; } diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/interceptor/impl/SameUrlDataInterceptor.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/interceptor/impl/SameUrlDataInterceptor.java old mode 100644 new mode 100755 index 316a370c..e3b12a97 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/interceptor/impl/SameUrlDataInterceptor.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/interceptor/impl/SameUrlDataInterceptor.java @@ -1,20 +1,19 @@ package com.ruoyi.framework.interceptor.impl; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.TimeUnit; -import javax.servlet.http.HttpServletRequest; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Component; import com.alibaba.fastjson2.JSON; import com.ruoyi.common.annotation.RepeatSubmit; import com.ruoyi.common.constant.CacheConstants; -import com.ruoyi.common.core.redis.RedisCache; import com.ruoyi.common.filter.RepeatedlyRequestWrapper; +import com.ruoyi.common.utils.CacheUtils; import com.ruoyi.common.utils.StringUtils; import com.ruoyi.common.utils.http.HttpHelper; import com.ruoyi.framework.interceptor.RepeatSubmitInterceptor; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import javax.servlet.http.HttpServletRequest; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.TimeUnit; /** * 判断请求url和数据是否和上一次相同, @@ -33,9 +32,6 @@ public class SameUrlDataInterceptor extends RepeatSubmitInterceptor @Value("${token.header}") private String header; - @Autowired - private RedisCache redisCache; - @SuppressWarnings("unchecked") @Override public boolean isRepeatSubmit(HttpServletRequest request, RepeatSubmit annotation) @@ -46,7 +42,6 @@ public class SameUrlDataInterceptor extends RepeatSubmitInterceptor RepeatedlyRequestWrapper repeatedlyRequest = (RepeatedlyRequestWrapper) request; nowParams = HttpHelper.getBodyString(repeatedlyRequest); } - // body参数为空,获取Parameter的数据 if (StringUtils.isEmpty(nowParams)) { @@ -55,17 +50,13 @@ public class SameUrlDataInterceptor extends RepeatSubmitInterceptor Map nowDataMap = new HashMap(); nowDataMap.put(REPEAT_PARAMS, nowParams); nowDataMap.put(REPEAT_TIME, System.currentTimeMillis()); - // 请求地址(作为存放cache的key值) String url = request.getRequestURI(); - // 唯一值(没有消息头则使用请求地址) String submitKey = StringUtils.trimToEmpty(request.getHeader(header)); - // 唯一标识(指定key + url + 消息头) - String cacheRepeatKey = CacheConstants.REPEAT_SUBMIT_KEY + url + submitKey; - - Object sessionObj = redisCache.getCacheObject(cacheRepeatKey); + String cacheRepeatKey = url + submitKey; + Object sessionObj = CacheUtils.get(CacheConstants.REPEAT_SUBMIT_KEY, cacheRepeatKey); if (sessionObj != null) { Map sessionMap = (Map) sessionObj; @@ -80,7 +71,7 @@ public class SameUrlDataInterceptor extends RepeatSubmitInterceptor } Map cacheMap = new HashMap(); cacheMap.put(url, nowDataMap); - redisCache.setCacheObject(cacheRepeatKey, cacheMap, annotation.interval(), TimeUnit.MILLISECONDS); + CacheUtils.put(CacheConstants.REPEAT_SUBMIT_KEY, cacheRepeatKey, cacheMap, annotation.interval(), TimeUnit.MILLISECONDS); return false; } diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/SysLoginService.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/SysLoginService.java old mode 100644 new mode 100755 index 97abcead..ef3d39ec --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/SysLoginService.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/SysLoginService.java @@ -1,24 +1,13 @@ package com.ruoyi.framework.web.service; -import javax.annotation.Resource; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.authentication.AuthenticationManager; -import org.springframework.security.authentication.BadCredentialsException; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.Authentication; -import org.springframework.stereotype.Component; import com.ruoyi.common.constant.CacheConstants; import com.ruoyi.common.constant.Constants; import com.ruoyi.common.constant.UserConstants; import com.ruoyi.common.core.domain.entity.SysUser; import com.ruoyi.common.core.domain.model.LoginUser; -import com.ruoyi.common.core.redis.RedisCache; import com.ruoyi.common.exception.ServiceException; -import com.ruoyi.common.exception.user.BlackListException; -import com.ruoyi.common.exception.user.CaptchaException; -import com.ruoyi.common.exception.user.CaptchaExpireException; -import com.ruoyi.common.exception.user.UserNotExistsException; -import com.ruoyi.common.exception.user.UserPasswordNotMatchException; +import com.ruoyi.common.exception.user.*; +import com.ruoyi.common.utils.CacheUtils; import com.ruoyi.common.utils.DateUtils; import com.ruoyi.common.utils.MessageUtils; import com.ruoyi.common.utils.StringUtils; @@ -28,6 +17,13 @@ import com.ruoyi.framework.manager.factory.AsyncFactory; import com.ruoyi.framework.security.context.AuthenticationContextHolder; import com.ruoyi.system.service.ISysConfigService; import com.ruoyi.system.service.ISysUserService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Component; +import javax.annotation.Resource; /** * 登录校验方法 @@ -43,9 +39,6 @@ public class SysLoginService @Resource private AuthenticationManager authenticationManager; - @Autowired - private RedisCache redisCache; - @Autowired private ISysUserService userService; @@ -113,14 +106,13 @@ public class SysLoginService boolean captchaEnabled = configService.selectCaptchaEnabled(); if (captchaEnabled) { - String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, ""); - String captcha = redisCache.getCacheObject(verifyKey); + String captcha = CacheUtils.get(CacheConstants.CAPTCHA_CODE_KEY, StringUtils.nvl(uuid, ""), String.class); + CacheUtils.removeIfPresent(CacheConstants.CAPTCHA_CODE_KEY, StringUtils.nvl(uuid, "")); if (captcha == null) { AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire"))); throw new CaptchaExpireException(); } - redisCache.deleteObject(verifyKey); if (!code.equalsIgnoreCase(captcha)) { AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error"))); diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/SysPasswordService.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/SysPasswordService.java old mode 100644 new mode 100755 index 7a1f93d4..07227c56 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/SysPasswordService.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/SysPasswordService.java @@ -1,17 +1,16 @@ package com.ruoyi.framework.web.service; -import java.util.concurrent.TimeUnit; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.security.core.Authentication; -import org.springframework.stereotype.Component; import com.ruoyi.common.constant.CacheConstants; import com.ruoyi.common.core.domain.entity.SysUser; -import com.ruoyi.common.core.redis.RedisCache; import com.ruoyi.common.exception.user.UserPasswordNotMatchException; import com.ruoyi.common.exception.user.UserPasswordRetryLimitExceedException; +import com.ruoyi.common.utils.CacheUtils; import com.ruoyi.common.utils.SecurityUtils; import com.ruoyi.framework.security.context.AuthenticationContextHolder; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.cache.Cache; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Component; /** * 登录密码方法 @@ -21,9 +20,6 @@ import com.ruoyi.framework.security.context.AuthenticationContextHolder; @Component public class SysPasswordService { - @Autowired - private RedisCache redisCache; - @Value(value = "${user.password.maxRetryCount}") private int maxRetryCount; @@ -32,13 +28,12 @@ public class SysPasswordService /** * 登录账户密码错误次数缓存键名 - * - * @param username 用户名 - * @return 缓存键key + * + * @return 缓存Cache */ - private String getCacheKey(String username) + private Cache getCache() { - return CacheConstants.PWD_ERR_CNT_KEY + username; + return CacheUtils.getCache(CacheConstants.PWD_ERR_CNT_KEY); } public void validate(SysUser user) @@ -46,23 +41,19 @@ public class SysPasswordService Authentication usernamePasswordAuthenticationToken = AuthenticationContextHolder.getContext(); String username = usernamePasswordAuthenticationToken.getName(); String password = usernamePasswordAuthenticationToken.getCredentials().toString(); - - Integer retryCount = redisCache.getCacheObject(getCacheKey(username)); - + Integer retryCount = getCache().get(username, Integer.class); if (retryCount == null) { retryCount = 0; } - if (retryCount >= Integer.valueOf(maxRetryCount).intValue()) { throw new UserPasswordRetryLimitExceedException(maxRetryCount, lockTime); } - if (!matches(user, password)) { retryCount = retryCount + 1; - redisCache.setCacheObject(getCacheKey(username), retryCount, lockTime, TimeUnit.MINUTES); + getCache().put(username, retryCount); throw new UserPasswordNotMatchException(); } else @@ -78,9 +69,6 @@ public class SysPasswordService public void clearLoginRecordCache(String loginName) { - if (redisCache.hasKey(getCacheKey(loginName))) - { - redisCache.deleteObject(getCacheKey(loginName)); - } + getCache().evictIfPresent(loginName); } } diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/SysRegisterService.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/SysRegisterService.java old mode 100644 new mode 100755 index 6093515a..06af94e2 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/SysRegisterService.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/SysRegisterService.java @@ -1,15 +1,13 @@ package com.ruoyi.framework.web.service; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; import com.ruoyi.common.constant.CacheConstants; import com.ruoyi.common.constant.Constants; import com.ruoyi.common.constant.UserConstants; import com.ruoyi.common.core.domain.entity.SysUser; import com.ruoyi.common.core.domain.model.RegisterBody; -import com.ruoyi.common.core.redis.RedisCache; import com.ruoyi.common.exception.user.CaptchaException; import com.ruoyi.common.exception.user.CaptchaExpireException; +import com.ruoyi.common.utils.CacheUtils; import com.ruoyi.common.utils.MessageUtils; import com.ruoyi.common.utils.SecurityUtils; import com.ruoyi.common.utils.StringUtils; @@ -17,6 +15,8 @@ import com.ruoyi.framework.manager.AsyncManager; import com.ruoyi.framework.manager.factory.AsyncFactory; import com.ruoyi.system.service.ISysConfigService; import com.ruoyi.system.service.ISysUserService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; /** * 注册校验方法 @@ -32,9 +32,6 @@ public class SysRegisterService @Autowired private ISysConfigService configService; - @Autowired - private RedisCache redisCache; - /** * 注册 */ @@ -43,14 +40,12 @@ public class SysRegisterService String msg = "", username = registerBody.getUsername(), password = registerBody.getPassword(); SysUser sysUser = new SysUser(); sysUser.setUserName(username); - // 验证码开关 boolean captchaEnabled = configService.selectCaptchaEnabled(); if (captchaEnabled) { validateCaptcha(username, registerBody.getCode(), registerBody.getUuid()); } - if (StringUtils.isEmpty(username)) { msg = "用户名不能为空"; @@ -100,9 +95,8 @@ public class SysRegisterService */ public void validateCaptcha(String username, String code, String uuid) { - String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, ""); - String captcha = redisCache.getCacheObject(verifyKey); - redisCache.deleteObject(verifyKey); + String captcha = CacheUtils.get(CacheConstants.CAPTCHA_CODE_KEY, StringUtils.nvl(uuid, ""), String.class); + CacheUtils.removeIfPresent(CacheConstants.CAPTCHA_CODE_KEY, StringUtils.nvl(uuid, "")); if (captcha == null) { throw new CaptchaExpireException(); diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/TokenService.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/TokenService.java old mode 100644 new mode 100755 index e062fafb..0b177972 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/TokenService.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/TokenService.java @@ -3,21 +3,24 @@ package com.ruoyi.framework.web.service; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; + import javax.servlet.http.HttpServletRequest; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; + import com.ruoyi.common.constant.CacheConstants; import com.ruoyi.common.constant.Constants; import com.ruoyi.common.core.domain.model.LoginUser; -import com.ruoyi.common.core.redis.RedisCache; +import com.ruoyi.common.utils.CacheUtils; import com.ruoyi.common.utils.ServletUtils; import com.ruoyi.common.utils.StringUtils; import com.ruoyi.common.utils.ip.AddressUtils; import com.ruoyi.common.utils.ip.IpUtils; import com.ruoyi.common.utils.uuid.IdUtils; + import eu.bitwalker.useragentutils.UserAgent; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; @@ -51,9 +54,6 @@ public class TokenService private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L; - @Autowired - private RedisCache redisCache; - /** * 获取用户身份信息 * @@ -70,8 +70,7 @@ public class TokenService Claims claims = parseToken(token); // 解析对应的权限以及用户信息 String uuid = (String) claims.get(Constants.LOGIN_USER_KEY); - String userKey = getTokenKey(uuid); - LoginUser user = redisCache.getCacheObject(userKey); + LoginUser user = CacheUtils.get(CacheConstants.LOGIN_TOKEN_KEY, uuid, LoginUser.class); return user; } catch (Exception e) @@ -100,8 +99,7 @@ public class TokenService { if (StringUtils.isNotEmpty(token)) { - String userKey = getTokenKey(token); - redisCache.deleteObject(userKey); + CacheUtils.removeIfPresent(CacheConstants.LOGIN_TOKEN_KEY, token); } } @@ -117,7 +115,6 @@ public class TokenService loginUser.setToken(token); setUserAgent(loginUser); refreshToken(loginUser); - Map claims = new HashMap<>(); claims.put(Constants.LOGIN_USER_KEY, token); return createToken(claims); @@ -149,8 +146,7 @@ public class TokenService loginUser.setLoginTime(System.currentTimeMillis()); loginUser.setExpireTime(loginUser.getLoginTime() + expireTime * MILLIS_MINUTE); // 根据uuid将loginUser缓存 - String userKey = getTokenKey(loginUser.getToken()); - redisCache.setCacheObject(userKey, loginUser, expireTime, TimeUnit.MINUTES); + CacheUtils.put(CacheConstants.LOGIN_TOKEN_KEY, loginUser.getToken(), loginUser, expireTime, TimeUnit.MINUTES); } /** @@ -223,9 +219,4 @@ public class TokenService } return token; } - - private String getTokenKey(String uuid) - { - return CacheConstants.LOGIN_TOKEN_KEY + uuid; - } } diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysConfigMapper.java b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysConfigMapper.java index 999995d7..8752e755 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysConfigMapper.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysConfigMapper.java @@ -1,6 +1,7 @@ package com.ruoyi.system.mapper; import java.util.List; + import com.ruoyi.system.domain.SysConfig; /** diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysConfigServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysConfigServiceImpl.java old mode 100644 new mode 100755 index 3615b88f..8d15a264 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysConfigServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysConfigServiceImpl.java @@ -1,21 +1,21 @@ package com.ruoyi.system.service.impl; -import java.util.Collection; -import java.util.List; -import javax.annotation.PostConstruct; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; import com.ruoyi.common.annotation.DataSource; import com.ruoyi.common.constant.CacheConstants; import com.ruoyi.common.constant.UserConstants; -import com.ruoyi.common.core.redis.RedisCache; import com.ruoyi.common.core.text.Convert; import com.ruoyi.common.enums.DataSourceType; import com.ruoyi.common.exception.ServiceException; +import com.ruoyi.common.utils.CacheUtils; import com.ruoyi.common.utils.StringUtils; import com.ruoyi.system.domain.SysConfig; import com.ruoyi.system.mapper.SysConfigMapper; import com.ruoyi.system.service.ISysConfigService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cache.Cache; +import org.springframework.stereotype.Service; +import javax.annotation.PostConstruct; +import java.util.List; /** * 参数配置 服务层实现 @@ -28,9 +28,6 @@ public class SysConfigServiceImpl implements ISysConfigService @Autowired private SysConfigMapper configMapper; - @Autowired - private RedisCache redisCache; - /** * 项目启动时,初始化参数到缓存 */ @@ -64,7 +61,7 @@ public class SysConfigServiceImpl implements ISysConfigService @Override public String selectConfigByKey(String configKey) { - String configValue = Convert.toStr(redisCache.getCacheObject(getCacheKey(configKey))); + String configValue = Convert.toStr(getCache().get(configKey, String.class)); if (StringUtils.isNotEmpty(configValue)) { return configValue; @@ -74,7 +71,7 @@ public class SysConfigServiceImpl implements ISysConfigService SysConfig retConfig = configMapper.selectConfig(config); if (StringUtils.isNotNull(retConfig)) { - redisCache.setCacheObject(getCacheKey(configKey), retConfig.getConfigValue()); + CacheUtils.put(CacheConstants.SYS_CONFIG_KEY, configKey, retConfig.getConfigValue()); return retConfig.getConfigValue(); } return StringUtils.EMPTY; @@ -120,7 +117,7 @@ public class SysConfigServiceImpl implements ISysConfigService int row = configMapper.insertConfig(config); if (row > 0) { - redisCache.setCacheObject(getCacheKey(config.getConfigKey()), config.getConfigValue()); + CacheUtils.put(CacheConstants.SYS_CONFIG_KEY, config.getConfigKey(), config.getConfigValue()); } return row; } @@ -137,13 +134,12 @@ public class SysConfigServiceImpl implements ISysConfigService SysConfig temp = configMapper.selectConfigById(config.getConfigId()); if (!StringUtils.equals(temp.getConfigKey(), config.getConfigKey())) { - redisCache.deleteObject(getCacheKey(temp.getConfigKey())); + CacheUtils.removeIfPresent(CacheConstants.SYS_CONFIG_KEY, temp.getConfigKey()); } - int row = configMapper.updateConfig(config); if (row > 0) { - redisCache.setCacheObject(getCacheKey(config.getConfigKey()), config.getConfigValue()); + CacheUtils.put(CacheConstants.SYS_CONFIG_KEY, config.getConfigKey(), config.getConfigValue()); } return row; } @@ -164,7 +160,7 @@ public class SysConfigServiceImpl implements ISysConfigService throw new ServiceException(String.format("内置参数【%1$s】不能删除 ", config.getConfigKey())); } configMapper.deleteConfigById(configId); - redisCache.deleteObject(getCacheKey(config.getConfigKey())); + getCache().evict(config.getConfigKey()); } } @@ -177,7 +173,7 @@ public class SysConfigServiceImpl implements ISysConfigService List configsList = configMapper.selectConfigList(new SysConfig()); for (SysConfig config : configsList) { - redisCache.setCacheObject(getCacheKey(config.getConfigKey()), config.getConfigValue()); + getCache().put(config.getConfigKey(), config.getConfigValue()); } } @@ -187,8 +183,7 @@ public class SysConfigServiceImpl implements ISysConfigService @Override public void clearConfigCache() { - Collection keys = redisCache.keys(CacheConstants.SYS_CONFIG_KEY + "*"); - redisCache.deleteObject(keys); + CacheUtils.getCache(CacheConstants.SYS_CONFIG_KEY).clear(); } /** @@ -220,13 +215,12 @@ public class SysConfigServiceImpl implements ISysConfigService } /** - * 设置cache key - * - * @param configKey 参数键 - * @return 缓存键key + * 获取config缓存 + * + * @return */ - private String getCacheKey(String configKey) + private Cache getCache() { - return CacheConstants.SYS_CONFIG_KEY + configKey; + return CacheUtils.getCache(CacheConstants.SYS_CONFIG_KEY); } }