diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..ed8368aa --- /dev/null +++ b/.gitignore @@ -0,0 +1,47 @@ +###################################################################### +# Build Tools + +.gradle +/build/ +!gradle/wrapper/gradle-wrapper.jar + +target/ +!.mvn/wrapper/maven-wrapper.jar + +###################################################################### +# IDE + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### JRebel ### +rebel.xml + +### NetBeans ### +nbproject/private/ +build/* +nbbuild/ +dist/ +nbdist/ +.nb-gradle/ + +###################################################################### +# Others +*.log +*.xml.versionsBackup +*.swp + +!*/build/*.java +!*/build/*.html +!*/build/*.xml 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 bec40373..a6f4a3b4 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 @@ -6,8 +6,6 @@ import java.util.concurrent.TimeUnit; import javax.annotation.Resource; import javax.imageio.ImageIO; import javax.servlet.http.HttpServletResponse; - -import com.ruoyi.common.utils.EhcacheUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.FastByteArrayOutputStream; import org.springframework.web.bind.annotation.GetMapping; @@ -17,13 +15,14 @@ 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.sign.Base64; import com.ruoyi.common.utils.uuid.IdUtils; import com.ruoyi.system.service.ISysConfigService; /** * 验证码操作处理 - * + * * @author ruoyi */ @RestController @@ -35,6 +34,9 @@ public class CaptchaController @Resource(name = "captchaProducerMath") private Producer captchaProducerMath; + @Autowired + private RedisCache redisCache; + @Autowired private ISysConfigService configService; /** @@ -72,8 +74,8 @@ public class CaptchaController capStr = code = captchaProducer.createText(); image = captchaProducer.createImage(capStr); } - EhcacheUtil.put("verify",verifyKey,code); -// redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES); + + redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES); // 转换流信息写出 FastByteArrayOutputStream os = new FastByteArrayOutputStream(); try 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 index 9aaf45bf..75c2d116 100644 --- 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,120 +1,120 @@ -//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 org.springframework.beans.factory.annotation.Autowired; -//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; -//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.constant.CacheConstants; -//import com.ruoyi.common.core.domain.AjaxResult; -//import com.ruoyi.common.utils.StringUtils; -//import com.ruoyi.system.domain.SysCache; -// -///** -// * 缓存监控 -// * -// * @author ruoyi -// */ -//@RestController -//@RequestMapping("/monitor/cache") -//public class CacheController -//{ -// @Autowired -// private RedisTemplate redisTemplate; -// -// private final static List caches = new ArrayList(); -// { -// caches.add(new SysCache(CacheConstants.LOGIN_TOKEN_KEY, "用户信息")); -// caches.add(new SysCache(CacheConstants.SYS_CONFIG_KEY, "配置信息")); -// caches.add(new SysCache(CacheConstants.SYS_DICT_KEY, "数据字典")); -// caches.add(new SysCache(CacheConstants.CAPTCHA_CODE_KEY, "验证码")); -// caches.add(new SysCache(CacheConstants.REPEAT_SUBMIT_KEY, "防重提交")); -// caches.add(new SysCache(CacheConstants.RATE_LIMIT_KEY, "限流处理")); -// caches.add(new SysCache(CacheConstants.PWD_ERR_CNT_KEY, "密码错误次数")); -// } -// -// @PreAuthorize("@ss.hasPermi('monitor:cache:list')") -// @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); -// return AjaxResult.success(result); -// } -// -// @PreAuthorize("@ss.hasPermi('monitor:cache:list')") -// @GetMapping("/getNames") -// public AjaxResult cache() -// { -// return AjaxResult.success(caches); -// } -// -// @PreAuthorize("@ss.hasPermi('monitor:cache:list')") -// @GetMapping("/getKeys/{cacheName}") -// public AjaxResult getCacheKeys(@PathVariable String cacheName) -// { -// Set cacheKeys = redisTemplate.keys(cacheName + "*"); -// return AjaxResult.success(cacheKeys); -// } -// -// @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); -// return AjaxResult.success(sysCache); -// } -// -// @PreAuthorize("@ss.hasPermi('monitor:cache:list')") -// @DeleteMapping("/clearCacheName/{cacheName}") -// public AjaxResult clearCacheName(@PathVariable String cacheName) -// { -// Collection cacheKeys = redisTemplate.keys(cacheName + "*"); -// redisTemplate.delete(cacheKeys); -// return AjaxResult.success(); -// } -// -// @PreAuthorize("@ss.hasPermi('monitor:cache:list')") -// @DeleteMapping("/clearCacheKey/{cacheKey}") -// public AjaxResult clearCacheKey(@PathVariable String cacheKey) -// { -// redisTemplate.delete(cacheKey); -// return AjaxResult.success(); -// } -// -// @PreAuthorize("@ss.hasPermi('monitor:cache:list')") -// @DeleteMapping("/clearCacheAll") -// public AjaxResult clearCacheAll() -// { -// Collection cacheKeys = redisTemplate.keys("*"); -// redisTemplate.delete(cacheKeys); -// return AjaxResult.success(); -// } -//} +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 org.springframework.beans.factory.annotation.Autowired; +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; +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.constant.CacheConstants; +import com.ruoyi.common.core.domain.AjaxResult; +import com.ruoyi.common.utils.StringUtils; +import com.ruoyi.system.domain.SysCache; + +/** + * 缓存监控 + * + * @author ruoyi + */ +@RestController +@RequestMapping("/monitor/cache") +public class CacheController +{ + @Autowired + private RedisTemplate redisTemplate; + + private final static List caches = new ArrayList(); + { + caches.add(new SysCache(CacheConstants.LOGIN_TOKEN_KEY, "用户信息")); + caches.add(new SysCache(CacheConstants.SYS_CONFIG_KEY, "配置信息")); + caches.add(new SysCache(CacheConstants.SYS_DICT_KEY, "数据字典")); + caches.add(new SysCache(CacheConstants.CAPTCHA_CODE_KEY, "验证码")); + caches.add(new SysCache(CacheConstants.REPEAT_SUBMIT_KEY, "防重提交")); + caches.add(new SysCache(CacheConstants.RATE_LIMIT_KEY, "限流处理")); + caches.add(new SysCache(CacheConstants.PWD_ERR_CNT_KEY, "密码错误次数")); + } + + @PreAuthorize("@ss.hasPermi('monitor:cache:list')") + @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); + return AjaxResult.success(result); + } + + @PreAuthorize("@ss.hasPermi('monitor:cache:list')") + @GetMapping("/getNames") + public AjaxResult cache() + { + return AjaxResult.success(caches); + } + + @PreAuthorize("@ss.hasPermi('monitor:cache:list')") + @GetMapping("/getKeys/{cacheName}") + public AjaxResult getCacheKeys(@PathVariable String cacheName) + { + Set cacheKeys = redisTemplate.keys(cacheName + "*"); + return AjaxResult.success(cacheKeys); + } + + @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); + return AjaxResult.success(sysCache); + } + + @PreAuthorize("@ss.hasPermi('monitor:cache:list')") + @DeleteMapping("/clearCacheName/{cacheName}") + public AjaxResult clearCacheName(@PathVariable String cacheName) + { + Collection cacheKeys = redisTemplate.keys(cacheName + "*"); + redisTemplate.delete(cacheKeys); + return AjaxResult.success(); + } + + @PreAuthorize("@ss.hasPermi('monitor:cache:list')") + @DeleteMapping("/clearCacheKey/{cacheKey}") + public AjaxResult clearCacheKey(@PathVariable String cacheKey) + { + redisTemplate.delete(cacheKey); + return AjaxResult.success(); + } + + @PreAuthorize("@ss.hasPermi('monitor:cache:list')") + @DeleteMapping("/clearCacheAll") + public AjaxResult clearCacheAll() + { + Collection cacheKeys = redisTemplate.keys("*"); + redisTemplate.delete(cacheKeys); + 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 index 45ecb03a..e913da26 100644 --- 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 @@ -4,8 +4,6 @@ import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; - -import com.ruoyi.common.utils.EhcacheUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.DeleteMapping; @@ -19,6 +17,7 @@ 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.StringUtils; import com.ruoyi.system.domain.SysUserOnline; @@ -26,7 +25,7 @@ import com.ruoyi.system.service.ISysUserOnlineService; /** * 在线用户监控 - * + * * @author ruoyi */ @RestController @@ -36,46 +35,47 @@ 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 + "*"); -// List userOnlineList = new ArrayList(); -// for (String key : keys) -// { -// LoginUser user = redisCache.getCacheObject(key); -// if (StringUtils.isNotEmpty(ipaddr) && StringUtils.isNotEmpty(userName)) -// { -// if (StringUtils.equals(ipaddr, user.getIpaddr()) && StringUtils.equals(userName, user.getUsername())) -// { -// userOnlineList.add(userOnlineService.selectOnlineByInfo(ipaddr, userName, user)); -// } -// } -// else if (StringUtils.isNotEmpty(ipaddr)) -// { -// if (StringUtils.equals(ipaddr, user.getIpaddr())) -// { -// userOnlineList.add(userOnlineService.selectOnlineByIpaddr(ipaddr, user)); -// } -// } -// else if (StringUtils.isNotEmpty(userName) && StringUtils.isNotNull(user.getUser())) -// { -// if (StringUtils.equals(userName, user.getUsername())) -// { -// userOnlineList.add(userOnlineService.selectOnlineByUserName(userName, user)); -// } -// } -// else -// { -// userOnlineList.add(userOnlineService.loginUserToUserOnline(user)); -// } -// } -// Collections.reverse(userOnlineList); -// userOnlineList.removeAll(Collections.singleton(null)); -// return getDataTable(userOnlineList); - return null; + Collection keys = redisCache.keys(CacheConstants.LOGIN_TOKEN_KEY + "*"); + List userOnlineList = new ArrayList(); + for (String key : keys) + { + LoginUser user = redisCache.getCacheObject(key); + if (StringUtils.isNotEmpty(ipaddr) && StringUtils.isNotEmpty(userName)) + { + if (StringUtils.equals(ipaddr, user.getIpaddr()) && StringUtils.equals(userName, user.getUsername())) + { + userOnlineList.add(userOnlineService.selectOnlineByInfo(ipaddr, userName, user)); + } + } + else if (StringUtils.isNotEmpty(ipaddr)) + { + if (StringUtils.equals(ipaddr, user.getIpaddr())) + { + userOnlineList.add(userOnlineService.selectOnlineByIpaddr(ipaddr, user)); + } + } + else if (StringUtils.isNotEmpty(userName) && StringUtils.isNotNull(user.getUser())) + { + if (StringUtils.equals(userName, user.getUsername())) + { + userOnlineList.add(userOnlineService.selectOnlineByUserName(userName, user)); + } + } + else + { + userOnlineList.add(userOnlineService.loginUserToUserOnline(user)); + } + } + Collections.reverse(userOnlineList); + userOnlineList.removeAll(Collections.singleton(null)); + return getDataTable(userOnlineList); } /** @@ -86,7 +86,7 @@ public class SysUserOnlineController extends BaseController @DeleteMapping("/{tokenId}") public AjaxResult forceLogout(@PathVariable String tokenId) { -// redisCache.deleteObject(CacheConstants.LOGIN_TOKEN_KEY + tokenId); + redisCache.deleteObject(CacheConstants.LOGIN_TOKEN_KEY + tokenId); return AjaxResult.success(); } } diff --git a/ruoyi-admin/src/main/resources/application.yml b/ruoyi-admin/src/main/resources/application.yml index c05620e3..15c2654c 100644 --- a/ruoyi-admin/src/main/resources/application.yml +++ b/ruoyi-admin/src/main/resources/application.yml @@ -74,32 +74,28 @@ spring: restart: # 热部署开关 enabled: false - cache: - type: ehcache - ehcache: - config: classpath:/ehcache.xml # 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 + redis: + # 地址 + host: 60.204.223.58 + # 端口,默认为6379 + port: 6379 + # 数据库索引 + database: 0 + # 密码 + password: redis123! + # 连接超时时间 + timeout: 10s + lettuce: + pool: + # 连接池中的最小空闲连接 + min-idle: 0 + # 连接池中的最大空闲连接 + max-idle: 8 + # 连接池的最大数据库连接数 + max-active: 8 + # #连接池最大阻塞等待时间(使用负值表示没有限制) + max-wait: -1ms # token配置 token: diff --git a/ruoyi-admin/src/main/resources/ehcache.xml b/ruoyi-admin/src/main/resources/ehcache.xml deleted file mode 100644 index c2bad019..00000000 --- a/ruoyi-admin/src/main/resources/ehcache.xml +++ /dev/null @@ -1,108 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/ruoyi-common/pom.xml b/ruoyi-common/pom.xml index b929a62b..39d24b39 100644 --- a/ruoyi-common/pom.xml +++ b/ruoyi-common/pom.xml @@ -129,10 +129,10 @@ - - - - + + org.springframework.boot + spring-boot-starter-data-redis + diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/core/redis/RedisCache.java b/ruoyi-common/src/main/java/com/ruoyi/common/core/redis/RedisCache.java new file mode 100644 index 00000000..676486df --- /dev/null +++ b/ruoyi-common/src/main/java/com/ruoyi/common/core/redis/RedisCache.java @@ -0,0 +1,265 @@ +package com.ruoyi.common.core.redis; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.BoundSetOperations; +import org.springframework.data.redis.core.HashOperations; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.core.ValueOperations; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.concurrent.TimeUnit; + +/** + * spring redis 工具类 + * + * @author ruoyi + **/ +@SuppressWarnings(value = { "unchecked", "rawtypes" }) +@Component +public class RedisCache +{ + @Autowired + public RedisTemplate redisTemplate; + + /** + * 缓存基本的对象,Integer、String、实体类等 + * + * @param key 缓存的键值 + * @param value 缓存的值 + */ + public void setCacheObject(final String key, final T value) + { + redisTemplate.opsForValue().set(key, value); + } + + /** + * 缓存基本的对象,Integer、String、实体类等 + * + * @param key 缓存的键值 + * @param value 缓存的值 + * @param timeout 时间 + * @param timeUnit 时间颗粒度 + */ + public void setCacheObject(final String key, final T value, final Integer timeout, final TimeUnit timeUnit) + { + redisTemplate.opsForValue().set(key, value, timeout, timeUnit); + } + + /** + * 设置有效时间 + * + * @param key Redis键 + * @param timeout 超时时间 + * @return true=设置成功;false=设置失败 + */ + public boolean expire(final String key, final long timeout) + { + return expire(key, timeout, TimeUnit.SECONDS); + } + + /** + * 设置有效时间 + * + * @param key Redis键 + * @param timeout 超时时间 + * @param unit 时间单位 + * @return true=设置成功;false=设置失败 + */ + public boolean expire(final String key, final long timeout, final TimeUnit unit) + { + return redisTemplate.expire(key, timeout, unit); + } + + /** + * 获取有效时间 + * + * @param key Redis键 + * @return 有效时间 + */ + public long getExpire(final String key) + { + return redisTemplate.getExpire(key); + } + + /** + * 判断 key是否存在 + * + * @param key 键 + * @return true 存在 false不存在 + */ + public Boolean hasKey(String key) + { + return redisTemplate.hasKey(key); + } + + /** + * 获得缓存的基本对象。 + * + * @param key 缓存键值 + * @return 缓存键值对应的数据 + */ + public T getCacheObject(final String key) + { + ValueOperations operation = redisTemplate.opsForValue(); + return operation.get(key); + } + + /** + * 删除单个对象 + * + * @param key + */ + public boolean deleteObject(final String key) + { + return redisTemplate.delete(key); + } + + /** + * 删除集合对象 + * + * @param collection 多个对象 + * @return + */ + public boolean deleteObject(final Collection collection) + { + return redisTemplate.delete(collection) > 0; + } + + /** + * 缓存List数据 + * + * @param key 缓存的键值 + * @param dataList 待缓存的List数据 + * @return 缓存的对象 + */ + public long setCacheList(final String key, final List dataList) + { + Long count = redisTemplate.opsForList().rightPushAll(key, dataList); + return count == null ? 0 : count; + } + + /** + * 获得缓存的list对象 + * + * @param key 缓存的键值 + * @return 缓存键值对应的数据 + */ + public List getCacheList(final String key) + { + return redisTemplate.opsForList().range(key, 0, -1); + } + + /** + * 缓存Set + * + * @param key 缓存键值 + * @param dataSet 缓存的数据 + * @return 缓存数据的对象 + */ + public BoundSetOperations setCacheSet(final String key, final Set dataSet) + { + BoundSetOperations setOperation = redisTemplate.boundSetOps(key); + Iterator it = dataSet.iterator(); + while (it.hasNext()) + { + setOperation.add(it.next()); + } + return setOperation; + } + + /** + * 获得缓存的set + * + * @param key + * @return + */ + public Set getCacheSet(final String key) + { + return redisTemplate.opsForSet().members(key); + } + + /** + * 缓存Map + * + * @param key + * @param dataMap + */ + public void setCacheMap(final String key, final Map dataMap) + { + if (dataMap != null) { + redisTemplate.opsForHash().putAll(key, dataMap); + } + } + + /** + * 获得缓存的Map + * + * @param key + * @return + */ + public Map getCacheMap(final String key) + { + return redisTemplate.opsForHash().entries(key); + } + + /** + * 往Hash中存入数据 + * + * @param key Redis键 + * @param hKey Hash键 + * @param value 值 + */ + public void setCacheMapValue(final String key, final String hKey, final T value) + { + redisTemplate.opsForHash().put(key, hKey, value); + } + + /** + * 获取Hash中的数据 + * + * @param key Redis键 + * @param hKey Hash键 + * @return Hash中的对象 + */ + public T getCacheMapValue(final String key, final String hKey) + { + HashOperations opsForHash = redisTemplate.opsForHash(); + return opsForHash.get(key, hKey); + } + + /** + * 获取多个Hash中的数据 + * + * @param key Redis键 + * @param hKeys Hash键集合 + * @return Hash对象集合 + */ + public List getMultiCacheMapValue(final String key, final Collection hKeys) + { + return redisTemplate.opsForHash().multiGet(key, hKeys); + } + + /** + * 删除Hash中的某条数据 + * + * @param key Redis键 + * @param hKey Hash键 + * @return 是否成功 + */ + public boolean deleteCacheMapValue(final String key, final String hKey) + { + return redisTemplate.opsForHash().delete(key, hKey) > 0; + } + + /** + * 获得缓存的基本对象列表 + * + * @param pattern 字符串前缀 + * @return 对象列表 + */ + public Collection keys(final String pattern) + { + return redisTemplate.keys(pattern); + } +} 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 index 13b3a83d..4b503e88 100644 --- 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,20 +1,16 @@ package com.ruoyi.common.utils; -import java.util.ArrayList; import java.util.Collection; import java.util.List; - -import cn.hutool.core.collection.CollUtil; -import cn.hutool.json.JSONUtil; 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 net.sf.ehcache.CacheManager; /** * 字典工具类 - * + * * @author ruoyi */ public class DictUtils @@ -26,42 +22,34 @@ public class DictUtils /** * 设置字典缓存 - * + * * @param key 参数键 * @param dictDatas 字典数据列表 */ public static void setDictCache(String key, List dictDatas) { - EhcacheUtil.put("dict",getCacheKey(key),dictDatas); -// SpringUtils.getBean(RedisCache.class).setCacheObject(getCacheKey(key), dictDatas); + SpringUtils.getBean(RedisCache.class).setCacheObject(getCacheKey(key), dictDatas); } /** * 获取字典缓存 - * + * * @param key 参数键 * @return dictDatas 字典数据列表 */ public static List getDictCache(String key) { - Object dict = EhcacheUtil.get("dict", getCacheKey(key)); - if (dict != null) { - JSONArray arrayCache = JSONArray.parseArray(JSONUtil.toJsonStr(dict)); - if (CollUtil.isNotEmpty(arrayCache)) { - return arrayCache.toList(SysDictData.class); - } + JSONArray arrayCache = SpringUtils.getBean(RedisCache.class).getCacheObject(getCacheKey(key)); + if (StringUtils.isNotNull(arrayCache)) + { + return arrayCache.toList(SysDictData.class); } -// JSONArray arrayCache = SpringUtils.getBean(RedisCache.class).getCacheObject(getCacheKey(key)); -// if (StringUtils.isNotNull(arrayCache)) -// { -// return arrayCache.toList(SysDictData.class); -// } - return new ArrayList<>(); + return null; } /** * 根据字典类型和字典值获取字典标签 - * + * * @param dictType 字典类型 * @param dictValue 字典值 * @return 字典标签 @@ -73,7 +61,7 @@ public class DictUtils /** * 根据字典类型和字典标签获取字典值 - * + * * @param dictType 字典类型 * @param dictLabel 字典标签 * @return 字典值 @@ -85,7 +73,7 @@ public class DictUtils /** * 根据字典类型和字典值获取字典标签 - * + * * @param dictType 字典类型 * @param dictValue 字典值 * @param separator 分隔符 @@ -128,7 +116,7 @@ public class DictUtils /** * 根据字典类型和字典标签获取字典值 - * + * * @param dictType 字典类型 * @param dictLabel 字典标签 * @param separator 分隔符 @@ -168,13 +156,12 @@ public class DictUtils /** * 删除指定字典缓存 - * + * * @param key 字典键 */ public static void removeDictCache(String key) { - EhcacheUtil.remove("dict", getCacheKey(key)); -// SpringUtils.getBean(RedisCache.class).deleteObject(getCacheKey(key)); + SpringUtils.getBean(RedisCache.class).deleteObject(getCacheKey(key)); } /** @@ -182,14 +169,13 @@ public class DictUtils */ public static void clearDictCache() { - EhcacheUtil.cacheManager.getCache("dict").removeAll(); -// Collection keys = SpringUtils.getBean(RedisCache.class).keys(CacheConstants.SYS_DICT_KEY + "*"); -// SpringUtils.getBean(RedisCache.class).deleteObject(keys); + Collection keys = SpringUtils.getBean(RedisCache.class).keys(CacheConstants.SYS_DICT_KEY + "*"); + SpringUtils.getBean(RedisCache.class).deleteObject(keys); } /** * 设置cache key - * + * * @param configKey 参数键 * @return 缓存键key */ diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/utils/TreeUtils.java b/ruoyi-common/src/main/java/com/ruoyi/common/utils/TreeUtils.java index d711a7f4..640be160 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/utils/TreeUtils.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/utils/TreeUtils.java @@ -3,6 +3,7 @@ package com.ruoyi.common.utils; import com.ruoyi.common.constant.CacheConstants; import com.ruoyi.common.constant.TreeConstants; import com.ruoyi.common.core.domain.DictTreeEntity; +import com.ruoyi.common.core.redis.RedisCache; import com.ruoyi.common.utils.spring.SpringUtils; import java.util.ArrayList; @@ -162,8 +163,7 @@ public class TreeUtils { */ public static void initCacheTreeData(String key, List node) { // 存储到redis - EhcacheUtil.put("tree",getCacheKey(key),node); -// SpringUtils.getBean(RedisCache.class).setCacheObject(getCacheKey(key), node); + SpringUtils.getBean(RedisCache.class).setCacheObject(getCacheKey(key), node); } /** diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/config/FastJson2JsonRedisSerializer.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/config/FastJson2JsonRedisSerializer.java index 20bd8706..622a852b 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/config/FastJson2JsonRedisSerializer.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/config/FastJson2JsonRedisSerializer.java @@ -1,48 +1,48 @@ -//package com.ruoyi.framework.config; -// -//import java.nio.charset.Charset; -//import org.springframework.data.redis.serializer.RedisSerializer; -//import org.springframework.data.redis.serializer.SerializationException; -//import com.alibaba.fastjson2.JSON; -//import com.alibaba.fastjson2.JSONReader; -//import com.alibaba.fastjson2.JSONWriter; -// -///** -// * Redis使用FastJson序列化 -// * -// * @author ruoyi -// */ -//public class FastJson2JsonRedisSerializer implements RedisSerializer -//{ -// public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); -// -// private Class clazz; -// -// public FastJson2JsonRedisSerializer(Class clazz) -// { -// super(); -// this.clazz = clazz; -// } -// -// @Override -// public byte[] serialize(T t) throws SerializationException -// { -// if (t == null) -// { -// return new byte[0]; -// } -// return JSON.toJSONString(t, JSONWriter.Feature.WriteClassName).getBytes(DEFAULT_CHARSET); -// } -// -// @Override -// public T deserialize(byte[] bytes) throws SerializationException -// { -// if (bytes == null || bytes.length <= 0) -// { -// return null; -// } -// String str = new String(bytes, DEFAULT_CHARSET); -// -// return JSON.parseObject(str, clazz, JSONReader.Feature.SupportAutoType); -// } -//} +package com.ruoyi.framework.config; + +import java.nio.charset.Charset; +import org.springframework.data.redis.serializer.RedisSerializer; +import org.springframework.data.redis.serializer.SerializationException; +import com.alibaba.fastjson2.JSON; +import com.alibaba.fastjson2.JSONReader; +import com.alibaba.fastjson2.JSONWriter; + +/** + * Redis使用FastJson序列化 + * + * @author ruoyi + */ +public class FastJson2JsonRedisSerializer implements RedisSerializer +{ + public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); + + private Class clazz; + + public FastJson2JsonRedisSerializer(Class clazz) + { + super(); + this.clazz = clazz; + } + + @Override + public byte[] serialize(T t) throws SerializationException + { + if (t == null) + { + return new byte[0]; + } + return JSON.toJSONString(t, JSONWriter.Feature.WriteClassName).getBytes(DEFAULT_CHARSET); + } + + @Override + public T deserialize(byte[] bytes) throws SerializationException + { + if (bytes == null || bytes.length <= 0) + { + return null; + } + String str = new String(bytes, DEFAULT_CHARSET); + + return JSON.parseObject(str, clazz, JSONReader.Feature.SupportAutoType); + } +} 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 index 3235c42a..151be1b7 100644 --- 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,69 +1,69 @@ -//package com.ruoyi.framework.config; -// -//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.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.StringRedisSerializer; -// -///** -// * redis配置 -// * -// * @author ruoyi -// */ -//@Configuration -//@EnableCaching -//public class RedisConfig extends CachingConfigurerSupport -//{ -// @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; -// } -// -// @Bean -// public DefaultRedisScript limitScript() -// { -// DefaultRedisScript redisScript = new DefaultRedisScript<>(); -// redisScript.setScriptText(limitScriptText()); -// redisScript.setResultType(Long.class); -// return redisScript; -// } -// -// /** -// * 限流脚本 -// */ -// private String limitScriptText() -// { -// return "local key = KEYS[1]\n" + -// "local count = tonumber(ARGV[1])\n" + -// "local time = tonumber(ARGV[2])\n" + -// "local current = redis.call('get', key);\n" + -// "if current and tonumber(current) > count then\n" + -// " return tonumber(current);\n" + -// "end\n" + -// "current = redis.call('incr', key)\n" + -// "if tonumber(current) == 1 then\n" + -// " redis.call('expire', key, time)\n" + -// "end\n" + -// "return tonumber(current);"; -// } -//} +package com.ruoyi.framework.config; + +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.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.StringRedisSerializer; + +/** + * redis配置 + * + * @author ruoyi + */ +@Configuration +@EnableCaching +public class RedisConfig extends CachingConfigurerSupport +{ + @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; + } + + @Bean + public DefaultRedisScript limitScript() + { + DefaultRedisScript redisScript = new DefaultRedisScript<>(); + redisScript.setScriptText(limitScriptText()); + redisScript.setResultType(Long.class); + return redisScript; + } + + /** + * 限流脚本 + */ + private String limitScriptText() + { + return "local key = KEYS[1]\n" + + "local count = tonumber(ARGV[1])\n" + + "local time = tonumber(ARGV[2])\n" + + "local current = redis.call('get', key);\n" + + "if current and tonumber(current) > count then\n" + + " return tonumber(current);\n" + + "end\n" + + "current = redis.call('incr', key)\n" + + "if tonumber(current) == 1 then\n" + + " redis.call('expire', key, time)\n" + + "end\n" + + "return tonumber(current);"; + } +} 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 index 3160c054..46c25e3e 100644 --- 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 @@ -4,14 +4,13 @@ import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import javax.servlet.http.HttpServletRequest; - -import com.ruoyi.common.utils.EhcacheUtil; 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.StringUtils; import com.ruoyi.common.utils.http.HttpHelper; @@ -20,7 +19,7 @@ import com.ruoyi.framework.interceptor.RepeatSubmitInterceptor; /** * 判断请求url和数据是否和上一次相同, * 如果和上次相同,则是重复提交表单。 有效时间为10秒内。 - * + * * @author ruoyi */ @Component @@ -34,8 +33,8 @@ public class SameUrlDataInterceptor extends RepeatSubmitInterceptor @Value("${token.header}") private String header; -// @Autowired -// private RedisCache redisCache; + @Autowired + private RedisCache redisCache; @SuppressWarnings("unchecked") @Override @@ -65,8 +64,8 @@ public class SameUrlDataInterceptor extends RepeatSubmitInterceptor // 唯一标识(指定key + url + 消息头) String cacheRepeatKey = CacheConstants.REPEAT_SUBMIT_KEY + url + submitKey; -// Object sessionObj = redisCache.getCacheObject(cacheRepeatKey); - Object sessionObj = EhcacheUtil.get("repeatsubmit",cacheRepeatKey); + + Object sessionObj = redisCache.getCacheObject(cacheRepeatKey); if (sessionObj != null) { Map sessionMap = (Map) sessionObj; @@ -81,8 +80,7 @@ public class SameUrlDataInterceptor extends RepeatSubmitInterceptor } Map cacheMap = new HashMap(); cacheMap.put(url, nowDataMap); - EhcacheUtil.put("repeatsubmit",cacheRepeatKey,cacheMap); -// redisCache.setCacheObject(cacheRepeatKey, cacheMap, annotation.interval(), TimeUnit.MILLISECONDS); + redisCache.setCacheObject(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 index 07a523ee..5b76e1ed 100644 --- 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 @@ -2,7 +2,6 @@ package com.ruoyi.framework.web.service; import javax.annotation.Resource; -import com.ruoyi.common.utils.*; import com.ruoyi.framework.security.context.AuthenticationContextHolder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.AuthenticationManager; @@ -14,10 +13,15 @@ import com.ruoyi.common.constant.CacheConstants; import com.ruoyi.common.constant.Constants; 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.CaptchaException; import com.ruoyi.common.exception.user.CaptchaExpireException; import com.ruoyi.common.exception.user.UserPasswordNotMatchException; +import com.ruoyi.common.utils.DateUtils; +import com.ruoyi.common.utils.MessageUtils; +import com.ruoyi.common.utils.ServletUtils; +import com.ruoyi.common.utils.StringUtils; import com.ruoyi.common.utils.ip.IpUtils; import com.ruoyi.framework.manager.AsyncManager; import com.ruoyi.framework.manager.factory.AsyncFactory; @@ -38,6 +42,9 @@ public class SysLoginService @Resource private AuthenticationManager authenticationManager; + @Autowired + private RedisCache redisCache; + @Autowired private ISysUserService userService; @@ -105,15 +112,14 @@ public class SysLoginService public void validateCaptcha(String username, String code, String uuid) { String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, ""); - Object captcha = EhcacheUtil.get("verify", verifyKey); -// redisCache.deleteObject(verifyKey); + String captcha = redisCache.getCacheObject(verifyKey); + redisCache.deleteObject(verifyKey); if (captcha == null) { AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire"))); throw new CaptchaExpireException(); } - EhcacheUtil.remove("verify", verifyKey); - if (!code.equalsIgnoreCase(captcha.toString())) + if (!code.equalsIgnoreCase(captcha)) { AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error"))); throw new CaptchaException(); 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 index c01f6e6a..2c50bb57 100644 --- 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,8 +1,6 @@ package com.ruoyi.framework.web.service; import java.util.concurrent.TimeUnit; - -import com.ruoyi.common.utils.EhcacheUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.core.Authentication; @@ -10,6 +8,7 @@ import org.springframework.stereotype.Component; import com.ruoyi.common.constant.CacheConstants; import com.ruoyi.common.constant.Constants; 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.MessageUtils; @@ -26,8 +25,8 @@ import com.ruoyi.framework.security.context.AuthenticationContextHolder; @Component public class SysPasswordService { -// @Autowired -// private RedisCache redisCache; + @Autowired + private RedisCache redisCache; @Value(value = "${user.password.maxRetryCount}") private int maxRetryCount; @@ -52,11 +51,11 @@ public class SysPasswordService String username = usernamePasswordAuthenticationToken.getName(); String password = usernamePasswordAuthenticationToken.getCredentials().toString(); - Object obj = EhcacheUtil.get("lock", getCacheKey(username)); - Integer retryCount = 0; - if (obj != null) + Integer retryCount = redisCache.getCacheObject(getCacheKey(username)); + + if (retryCount == null) { - retryCount = Integer.valueOf(obj.toString()); + retryCount = 0; } if (retryCount >= Integer.valueOf(maxRetryCount).intValue()) @@ -71,8 +70,7 @@ public class SysPasswordService retryCount = retryCount + 1; AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.retry.limit.count", retryCount))); - EhcacheUtil.put("lock", getCacheKey(username), retryCount); -// redisCache.setCacheObject(getCacheKey(username), retryCount, lockTime, TimeUnit.MINUTES); + redisCache.setCacheObject(getCacheKey(username), retryCount, lockTime, TimeUnit.MINUTES); throw new UserPasswordNotMatchException(); } else @@ -88,11 +86,9 @@ public class SysPasswordService public void clearLoginRecordCache(String loginName) { - Object lock = EhcacheUtil.get("lock", getCacheKey(loginName)); - if (lock!= null) + if (redisCache.hasKey(getCacheKey(loginName))) { - EhcacheUtil.remove("lock", getCacheKey(loginName)); -// redisCache.deleteObject(getCacheKey(loginName)); + redisCache.deleteObject(getCacheKey(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 index 0736204d..83b64b26 100644 --- 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 @@ -5,9 +5,9 @@ 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.EhcacheUtil; import com.ruoyi.common.utils.MessageUtils; import com.ruoyi.common.utils.SecurityUtils; import com.ruoyi.common.utils.StringUtils; @@ -31,8 +31,8 @@ public class SysRegisterService { @Autowired private ISysConfigService configService; -// @Autowired -// private RedisCache redisCache; + @Autowired + private RedisCache redisCache; /** * 注册 @@ -82,13 +82,12 @@ public class SysRegisterService { */ public void validateCaptcha(String username, String code, String uuid) { String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, ""); - Object obj = EhcacheUtil.get("verify", verifyKey); -// String captcha = redisCache.getCacheObject(verifyKey); -// redisCache.deleteObject(verifyKey); - if (obj == null) { + String captcha = redisCache.getCacheObject(verifyKey); + redisCache.deleteObject(verifyKey); + if (captcha == null) { throw new CaptchaExpireException(); } - if (!code.equalsIgnoreCase(obj.toString())) { + if (!code.equalsIgnoreCase(captcha)) { throw new CaptchaException(); } } 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 index 62549f90..72279530 100644 --- 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 @@ -3,13 +3,12 @@ package com.ruoyi.system.service.impl; import java.util.Collection; import java.util.List; import javax.annotation.PostConstruct; - -import com.ruoyi.common.utils.EhcacheUtil; 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; @@ -20,7 +19,7 @@ import com.ruoyi.system.service.ISysConfigService; /** * 参数配置 服务层实现 - * + * * @author ruoyi */ @Service @@ -29,8 +28,8 @@ public class SysConfigServiceImpl implements ISysConfigService @Autowired private SysConfigMapper configMapper; -// @Autowired -// private RedisCache redisCache; + @Autowired + private RedisCache redisCache; /** * 项目启动时,初始化参数到缓存 @@ -43,7 +42,7 @@ public class SysConfigServiceImpl implements ISysConfigService /** * 查询参数配置信息 - * + * * @param configId 参数配置ID * @return 参数配置信息 */ @@ -58,16 +57,14 @@ public class SysConfigServiceImpl implements ISysConfigService /** * 根据键名查询参数配置信息 - * + * * @param configKey 参数key * @return 参数键值 */ @Override public String selectConfigByKey(String configKey) { -// String configValue = Convert.toStr(redisCache.getCacheObject(getCacheKey(configKey))); - Object obj = EhcacheUtil.get("sysconfig", getCacheKey(configKey)); - String configValue = Convert.toStr(obj); + String configValue = Convert.toStr(redisCache.getCacheObject(getCacheKey(configKey))); if (StringUtils.isNotEmpty(configValue)) { return configValue; @@ -77,8 +74,7 @@ public class SysConfigServiceImpl implements ISysConfigService SysConfig retConfig = configMapper.selectConfig(config); if (StringUtils.isNotNull(retConfig)) { - EhcacheUtil.put("sysconfig", getCacheKey(configKey),retConfig.getConfigValue()); -// redisCache.setCacheObject(getCacheKey(configKey), retConfig.getConfigValue()); + redisCache.setCacheObject(getCacheKey(configKey), retConfig.getConfigValue()); return retConfig.getConfigValue(); } return StringUtils.EMPTY; @@ -86,7 +82,7 @@ public class SysConfigServiceImpl implements ISysConfigService /** * 获取验证码开关 - * + * * @return true开启,false关闭 */ @Override @@ -102,7 +98,7 @@ public class SysConfigServiceImpl implements ISysConfigService /** * 查询参数配置列表 - * + * * @param config 参数配置信息 * @return 参数配置集合 */ @@ -114,7 +110,7 @@ public class SysConfigServiceImpl implements ISysConfigService /** * 新增参数配置 - * + * * @param config 参数配置信息 * @return 结果 */ @@ -124,15 +120,14 @@ public class SysConfigServiceImpl implements ISysConfigService int row = configMapper.insertConfig(config); if (row > 0) { - EhcacheUtil.put("sysconfig", getCacheKey(config.getConfigKey()), config.getConfigValue()); -// redisCache.setCacheObject(getCacheKey(config.getConfigKey()), config.getConfigValue()); + redisCache.setCacheObject(getCacheKey(config.getConfigKey()), config.getConfigValue()); } return row; } /** * 修改参数配置 - * + * * @param config 参数配置信息 * @return 结果 */ @@ -142,15 +137,14 @@ public class SysConfigServiceImpl implements ISysConfigService int row = configMapper.updateConfig(config); if (row > 0) { - EhcacheUtil.put("sysconfig", getCacheKey(config.getConfigKey()), config.getConfigValue()); -// redisCache.setCacheObject(getCacheKey(config.getConfigKey()), config.getConfigValue()); + redisCache.setCacheObject(getCacheKey(config.getConfigKey()), config.getConfigValue()); } return row; } /** * 批量删除参数信息 - * + * * @param configIds 需要删除的参数ID */ @Override @@ -164,8 +158,7 @@ public class SysConfigServiceImpl implements ISysConfigService throw new ServiceException(String.format("内置参数【%1$s】不能删除 ", config.getConfigKey())); } configMapper.deleteConfigById(configId); - EhcacheUtil.remove("sysconfig", getCacheKey(config.getConfigKey())); -// redisCache.deleteObject(getCacheKey(config.getConfigKey())); + redisCache.deleteObject(getCacheKey(config.getConfigKey())); } } @@ -178,8 +171,7 @@ public class SysConfigServiceImpl implements ISysConfigService List configsList = configMapper.selectConfigList(new SysConfig()); for (SysConfig config : configsList) { - EhcacheUtil.put("sysconfig", getCacheKey(config.getConfigKey()),config.getConfigValue()); -// redisCache.setCacheObject(getCacheKey(config.getConfigKey()), config.getConfigValue()); + redisCache.setCacheObject(getCacheKey(config.getConfigKey()), config.getConfigValue()); } } @@ -189,9 +181,8 @@ public class SysConfigServiceImpl implements ISysConfigService @Override public void clearConfigCache() { - EhcacheUtil.removeAll("sysconfig"); -// Collection keys = redisCache.keys(CacheConstants.SYS_CONFIG_KEY + "*"); -// redisCache.deleteObject(keys); + Collection keys = redisCache.keys(CacheConstants.SYS_CONFIG_KEY + "*"); + redisCache.deleteObject(keys); } /** @@ -206,7 +197,7 @@ public class SysConfigServiceImpl implements ISysConfigService /** * 校验参数键名是否唯一 - * + * * @param config 参数配置信息 * @return 结果 */ @@ -224,7 +215,7 @@ public class SysConfigServiceImpl implements ISysConfigService /** * 设置cache key - * + * * @param configKey 参数键 * @return 缓存键key */