feat: echache调整未redis

new
chenqp 1 year ago
parent 58d4f4c9b6
commit b37441d8de

47
.gitignore vendored

@ -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

@ -6,8 +6,6 @@ import java.util.concurrent.TimeUnit;
import javax.annotation.Resource; import javax.annotation.Resource;
import javax.imageio.ImageIO; import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import com.ruoyi.common.utils.EhcacheUtil;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FastByteArrayOutputStream; import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
@ -17,6 +15,7 @@ import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.CacheConstants; import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants; import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult; 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.sign.Base64;
import com.ruoyi.common.utils.uuid.IdUtils; import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.service.ISysConfigService; import com.ruoyi.system.service.ISysConfigService;
@ -35,6 +34,9 @@ public class CaptchaController
@Resource(name = "captchaProducerMath") @Resource(name = "captchaProducerMath")
private Producer captchaProducerMath; private Producer captchaProducerMath;
@Autowired
private RedisCache redisCache;
@Autowired @Autowired
private ISysConfigService configService; private ISysConfigService configService;
/** /**
@ -72,8 +74,8 @@ public class CaptchaController
capStr = code = captchaProducer.createText(); capStr = code = captchaProducer.createText();
image = captchaProducer.createImage(capStr); 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(); FastByteArrayOutputStream os = new FastByteArrayOutputStream();
try try

@ -1,120 +1,120 @@
//package com.ruoyi.web.controller.monitor; package com.ruoyi.web.controller.monitor;
//
//import java.util.ArrayList; import java.util.ArrayList;
//import java.util.Collection; import java.util.Collection;
//import java.util.HashMap; import java.util.HashMap;
//import java.util.List; import java.util.List;
//import java.util.Map; import java.util.Map;
//import java.util.Properties; import java.util.Properties;
//import java.util.Set; import java.util.Set;
//import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.data.redis.core.RedisCallback; import org.springframework.data.redis.core.RedisCallback;
//import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.RedisTemplate;
//import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.access.prepost.PreAuthorize;
//import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.DeleteMapping;
//import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
//import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
//import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
//import com.ruoyi.common.constant.CacheConstants; import com.ruoyi.common.constant.CacheConstants;
//import com.ruoyi.common.core.domain.AjaxResult; import com.ruoyi.common.core.domain.AjaxResult;
//import com.ruoyi.common.utils.StringUtils; import com.ruoyi.common.utils.StringUtils;
//import com.ruoyi.system.domain.SysCache; import com.ruoyi.system.domain.SysCache;
//
///** /**
// * 缓存监控 *
// * *
// * @author ruoyi * @author ruoyi
// */ */
//@RestController @RestController
//@RequestMapping("/monitor/cache") @RequestMapping("/monitor/cache")
//public class CacheController public class CacheController
//{ {
// @Autowired @Autowired
// private RedisTemplate<String, String> redisTemplate; private RedisTemplate<String, String> redisTemplate;
//
// private final static List<SysCache> caches = new ArrayList<SysCache>(); private final static List<SysCache> caches = new ArrayList<SysCache>();
// { {
// caches.add(new SysCache(CacheConstants.LOGIN_TOKEN_KEY, "用户信息")); caches.add(new SysCache(CacheConstants.LOGIN_TOKEN_KEY, "用户信息"));
// caches.add(new SysCache(CacheConstants.SYS_CONFIG_KEY, "配置信息")); caches.add(new SysCache(CacheConstants.SYS_CONFIG_KEY, "配置信息"));
// caches.add(new SysCache(CacheConstants.SYS_DICT_KEY, "数据字典")); caches.add(new SysCache(CacheConstants.SYS_DICT_KEY, "数据字典"));
// caches.add(new SysCache(CacheConstants.CAPTCHA_CODE_KEY, "验证码")); caches.add(new SysCache(CacheConstants.CAPTCHA_CODE_KEY, "验证码"));
// caches.add(new SysCache(CacheConstants.REPEAT_SUBMIT_KEY, "防重提交")); caches.add(new SysCache(CacheConstants.REPEAT_SUBMIT_KEY, "防重提交"));
// caches.add(new SysCache(CacheConstants.RATE_LIMIT_KEY, "限流处理")); caches.add(new SysCache(CacheConstants.RATE_LIMIT_KEY, "限流处理"));
// caches.add(new SysCache(CacheConstants.PWD_ERR_CNT_KEY, "密码错误次数")); caches.add(new SysCache(CacheConstants.PWD_ERR_CNT_KEY, "密码错误次数"));
// } }
//
// @PreAuthorize("@ss.hasPermi('monitor:cache:list')") @PreAuthorize("@ss.hasPermi('monitor:cache:list')")
// @GetMapping() @GetMapping()
// public AjaxResult getInfo() throws Exception public AjaxResult getInfo() throws Exception
// { {
// Properties info = (Properties) redisTemplate.execute((RedisCallback<Object>) connection -> connection.info()); Properties info = (Properties) redisTemplate.execute((RedisCallback<Object>) connection -> connection.info());
// Properties commandStats = (Properties) redisTemplate.execute((RedisCallback<Object>) connection -> connection.info("commandstats")); Properties commandStats = (Properties) redisTemplate.execute((RedisCallback<Object>) connection -> connection.info("commandstats"));
// Object dbSize = redisTemplate.execute((RedisCallback<Object>) connection -> connection.dbSize()); Object dbSize = redisTemplate.execute((RedisCallback<Object>) connection -> connection.dbSize());
//
// Map<String, Object> result = new HashMap<>(3); Map<String, Object> result = new HashMap<>(3);
// result.put("info", info); result.put("info", info);
// result.put("dbSize", dbSize); result.put("dbSize", dbSize);
//
// List<Map<String, String>> pieList = new ArrayList<>(); List<Map<String, String>> pieList = new ArrayList<>();
// commandStats.stringPropertyNames().forEach(key -> { commandStats.stringPropertyNames().forEach(key -> {
// Map<String, String> data = new HashMap<>(2); Map<String, String> data = new HashMap<>(2);
// String property = commandStats.getProperty(key); String property = commandStats.getProperty(key);
// data.put("name", StringUtils.removeStart(key, "cmdstat_")); data.put("name", StringUtils.removeStart(key, "cmdstat_"));
// data.put("value", StringUtils.substringBetween(property, "calls=", ",usec")); data.put("value", StringUtils.substringBetween(property, "calls=", ",usec"));
// pieList.add(data); pieList.add(data);
// }); });
// result.put("commandStats", pieList); result.put("commandStats", pieList);
// return AjaxResult.success(result); return AjaxResult.success(result);
// } }
//
// @PreAuthorize("@ss.hasPermi('monitor:cache:list')") @PreAuthorize("@ss.hasPermi('monitor:cache:list')")
// @GetMapping("/getNames") @GetMapping("/getNames")
// public AjaxResult cache() public AjaxResult cache()
// { {
// return AjaxResult.success(caches); return AjaxResult.success(caches);
// } }
//
// @PreAuthorize("@ss.hasPermi('monitor:cache:list')") @PreAuthorize("@ss.hasPermi('monitor:cache:list')")
// @GetMapping("/getKeys/{cacheName}") @GetMapping("/getKeys/{cacheName}")
// public AjaxResult getCacheKeys(@PathVariable String cacheName) public AjaxResult getCacheKeys(@PathVariable String cacheName)
// { {
// Set<String> cacheKeys = redisTemplate.keys(cacheName + "*"); Set<String> cacheKeys = redisTemplate.keys(cacheName + "*");
// return AjaxResult.success(cacheKeys); return AjaxResult.success(cacheKeys);
// } }
//
// @PreAuthorize("@ss.hasPermi('monitor:cache:list')") @PreAuthorize("@ss.hasPermi('monitor:cache:list')")
// @GetMapping("/getValue/{cacheName}/{cacheKey}") @GetMapping("/getValue/{cacheName}/{cacheKey}")
// public AjaxResult getCacheValue(@PathVariable String cacheName, @PathVariable String cacheKey) public AjaxResult getCacheValue(@PathVariable String cacheName, @PathVariable String cacheKey)
// { {
// String cacheValue = redisTemplate.opsForValue().get(cacheKey); String cacheValue = redisTemplate.opsForValue().get(cacheKey);
// SysCache sysCache = new SysCache(cacheName, cacheKey, cacheValue); SysCache sysCache = new SysCache(cacheName, cacheKey, cacheValue);
// return AjaxResult.success(sysCache); return AjaxResult.success(sysCache);
// } }
//
// @PreAuthorize("@ss.hasPermi('monitor:cache:list')") @PreAuthorize("@ss.hasPermi('monitor:cache:list')")
// @DeleteMapping("/clearCacheName/{cacheName}") @DeleteMapping("/clearCacheName/{cacheName}")
// public AjaxResult clearCacheName(@PathVariable String cacheName) public AjaxResult clearCacheName(@PathVariable String cacheName)
// { {
// Collection<String> cacheKeys = redisTemplate.keys(cacheName + "*"); Collection<String> cacheKeys = redisTemplate.keys(cacheName + "*");
// redisTemplate.delete(cacheKeys); redisTemplate.delete(cacheKeys);
// return AjaxResult.success(); return AjaxResult.success();
// } }
//
// @PreAuthorize("@ss.hasPermi('monitor:cache:list')") @PreAuthorize("@ss.hasPermi('monitor:cache:list')")
// @DeleteMapping("/clearCacheKey/{cacheKey}") @DeleteMapping("/clearCacheKey/{cacheKey}")
// public AjaxResult clearCacheKey(@PathVariable String cacheKey) public AjaxResult clearCacheKey(@PathVariable String cacheKey)
// { {
// redisTemplate.delete(cacheKey); redisTemplate.delete(cacheKey);
// return AjaxResult.success(); return AjaxResult.success();
// } }
//
// @PreAuthorize("@ss.hasPermi('monitor:cache:list')") @PreAuthorize("@ss.hasPermi('monitor:cache:list')")
// @DeleteMapping("/clearCacheAll") @DeleteMapping("/clearCacheAll")
// public AjaxResult clearCacheAll() public AjaxResult clearCacheAll()
// { {
// Collection<String> cacheKeys = redisTemplate.keys("*"); Collection<String> cacheKeys = redisTemplate.keys("*");
// redisTemplate.delete(cacheKeys); redisTemplate.delete(cacheKeys);
// return AjaxResult.success(); return AjaxResult.success();
// } }
//} }

@ -4,8 +4,6 @@ import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import com.ruoyi.common.utils.EhcacheUtil;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping; 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.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser; import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo; import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.BusinessType; import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils; import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SysUserOnline; import com.ruoyi.system.domain.SysUserOnline;
@ -36,46 +35,47 @@ public class SysUserOnlineController extends BaseController
@Autowired @Autowired
private ISysUserOnlineService userOnlineService; private ISysUserOnlineService userOnlineService;
@Autowired
private RedisCache redisCache;
@PreAuthorize("@ss.hasPermi('monitor:online:list')") @PreAuthorize("@ss.hasPermi('monitor:online:list')")
@GetMapping("/list") @GetMapping("/list")
public TableDataInfo list(String ipaddr, String userName) public TableDataInfo list(String ipaddr, String userName)
{ {
//// Collection<String> keys = redisCache.keys(CacheConstants.LOGIN_TOKEN_KEY + "*"); Collection<String> keys = redisCache.keys(CacheConstants.LOGIN_TOKEN_KEY + "*");
// List<SysUserOnline> userOnlineList = new ArrayList<SysUserOnline>(); List<SysUserOnline> userOnlineList = new ArrayList<SysUserOnline>();
// for (String key : keys) for (String key : keys)
// { {
// LoginUser user = redisCache.getCacheObject(key); LoginUser user = redisCache.getCacheObject(key);
// if (StringUtils.isNotEmpty(ipaddr) && StringUtils.isNotEmpty(userName)) if (StringUtils.isNotEmpty(ipaddr) && StringUtils.isNotEmpty(userName))
// { {
// if (StringUtils.equals(ipaddr, user.getIpaddr()) && StringUtils.equals(userName, user.getUsername())) if (StringUtils.equals(ipaddr, user.getIpaddr()) && StringUtils.equals(userName, user.getUsername()))
// { {
// userOnlineList.add(userOnlineService.selectOnlineByInfo(ipaddr, userName, user)); userOnlineList.add(userOnlineService.selectOnlineByInfo(ipaddr, userName, user));
// } }
// } }
// else if (StringUtils.isNotEmpty(ipaddr)) else if (StringUtils.isNotEmpty(ipaddr))
// { {
// if (StringUtils.equals(ipaddr, user.getIpaddr())) if (StringUtils.equals(ipaddr, user.getIpaddr()))
// { {
// userOnlineList.add(userOnlineService.selectOnlineByIpaddr(ipaddr, user)); userOnlineList.add(userOnlineService.selectOnlineByIpaddr(ipaddr, user));
// } }
// } }
// else if (StringUtils.isNotEmpty(userName) && StringUtils.isNotNull(user.getUser())) else if (StringUtils.isNotEmpty(userName) && StringUtils.isNotNull(user.getUser()))
// { {
// if (StringUtils.equals(userName, user.getUsername())) if (StringUtils.equals(userName, user.getUsername()))
// { {
// userOnlineList.add(userOnlineService.selectOnlineByUserName(userName, user)); userOnlineList.add(userOnlineService.selectOnlineByUserName(userName, user));
// } }
// } }
// else else
// { {
// userOnlineList.add(userOnlineService.loginUserToUserOnline(user)); userOnlineList.add(userOnlineService.loginUserToUserOnline(user));
// } }
// } }
// Collections.reverse(userOnlineList); Collections.reverse(userOnlineList);
// userOnlineList.removeAll(Collections.singleton(null)); userOnlineList.removeAll(Collections.singleton(null));
// return getDataTable(userOnlineList); return getDataTable(userOnlineList);
return null;
} }
/** /**
@ -86,7 +86,7 @@ public class SysUserOnlineController extends BaseController
@DeleteMapping("/{tokenId}") @DeleteMapping("/{tokenId}")
public AjaxResult forceLogout(@PathVariable String tokenId) public AjaxResult forceLogout(@PathVariable String tokenId)
{ {
// redisCache.deleteObject(CacheConstants.LOGIN_TOKEN_KEY + tokenId); redisCache.deleteObject(CacheConstants.LOGIN_TOKEN_KEY + tokenId);
return AjaxResult.success(); return AjaxResult.success();
} }
} }

@ -74,32 +74,28 @@ spring:
restart: restart:
# 热部署开关 # 热部署开关
enabled: false enabled: false
cache:
type: ehcache
ehcache:
config: classpath:/ehcache.xml
# redis 配置 # redis 配置
# redis: redis:
# # 地址 # 地址
# host: localhost host: 60.204.223.58
# # 端口默认为6379 # 端口默认为6379
# port: 6379 port: 6379
# # 数据库索引 # 数据库索引
# database: 0 database: 0
# # 密码 # 密码
# password: password: redis123!
# # 连接超时时间 # 连接超时时间
# timeout: 10s timeout: 10s
# lettuce: lettuce:
# pool: pool:
# # 连接池中的最小空闲连接 # 连接池中的最小空闲连接
# min-idle: 0 min-idle: 0
# # 连接池中的最大空闲连接 # 连接池中的最大空闲连接
# max-idle: 8 max-idle: 8
# # 连接池的最大数据库连接数 # 连接池的最大数据库连接数
# max-active: 8 max-active: 8
# # #连接池最大阻塞等待时间(使用负值表示没有限制) # #连接池最大阻塞等待时间(使用负值表示没有限制)
# max-wait: -1ms max-wait: -1ms
# token配置 # token配置
token: token:

@ -1,108 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
<!--
磁盘存储:将缓存中暂时不使用的对象,转移到硬盘,类似于Windows系统的虚拟内存
path:指定在硬盘上存储对象的路径
path可以配置的目录有
user.home用户的家目录
user.dir用户当前的工作目录
java.io.tmpdir默认的临时目录
ehcache.disk.store.direhcache的配置目录
绝对路径d:\\ehcache
查看路径方法String tmpDir = System.getProperty("java.io.tmpdir");
-->
<diskStore path="../hzyh/ehcache" />
<!--
defaultCache:默认的缓存配置信息,如果不加特殊说明,则所有对象按照此配置项处理
maxElementsInMemory:设置了缓存的上限,最多存储多少个记录对象
eternal:代表对象是否永不过期 (指定true则下面两项配置需为0无限期)
timeToIdleSeconds:最大的发呆时间 /秒
timeToLiveSeconds:最大的存活时间 /秒
overflowToDisk:是否允许对象被写入到磁盘
说明下列配置自缓存建立起600秒(10分钟)有效 。
在有效的600秒(10分钟)内如果连续120秒(2分钟)未访问缓存,则缓存失效。
就算有访问也只会存活600秒。
-->
<defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="600"
timeToLiveSeconds="600" overflowToDisk="true" />
<!--
maxElementsInMemory内存缓存中最多可以存放的元素数量,若放入Cache中的元素超过这个数值,则有以下两种情况
1)若overflowToDisk=true,则会将Cache中多出的元素放入磁盘文件中
2)若overflowToDisk=false,则根据memoryStoreEvictionPolicy策略替换Cache中原有的元素
eternal 缓存中对象是否永久有效
timeToIdleSeconds 缓存数据在失效前的允许闲置时间(单位:秒)仅当eternal=false时使用,默认值是0表示可闲置时间无穷大,若超过这个时间没有访问此Cache中的某个元素,那么此元素将被从Cache中清除
timeToLiveSeconds 缓存数据的总的存活时间单位仅当eternal=false时使用从创建开始计时失效结束
maxElementsOnDisk 磁盘缓存中最多可以存放的元素数量,0表示无穷大
overflowToDisk 内存不足时,是否启用磁盘缓存
diskExpiryThreadIntervalSeconds 磁盘缓存的清理线程运行间隔,默认是120秒
memoryStoreEvictionPolicy 内存存储与释放策略,即达到maxElementsInMemory限制时,Ehcache会根据指定策略清理内存 共有三种策略,分别为LRU(最近最少使用)、LFU(最常用的)、FIFO(先进先出)
-->
<!-- 登录-->
<cache name="login"
maxElementsInMemory="1"
eternal="false"
timeToIdleSeconds="0"
timeToLiveSeconds="259200"
maxElementsOnDisk="10000000"
overflowToDisk="true"
diskPersistent="true"
memoryStoreEvictionPolicy="LRU" />
<!-- 验证码-->
<cache name="verify"
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
maxElementsOnDisk="10000000"
overflowToDisk="true"
memoryStoreEvictionPolicy="LRU" />
<!-- 数据字典-->
<cache name="dict"
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="0"
timeToLiveSeconds="432000"
maxElementsOnDisk="10000000"
overflowToDisk="true"
memoryStoreEvictionPolicy="LRU" />
<!-- 树形数据字典-->
<cache name="tree"
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="0"
timeToLiveSeconds="432000"
maxElementsOnDisk="10000000"
overflowToDisk="true"
memoryStoreEvictionPolicy="LRU" />
<!-- 重复提交-->
<cache name="repeatsubmit"
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="0"
timeToLiveSeconds="5"
maxElementsOnDisk="10000000"
overflowToDisk="true"
memoryStoreEvictionPolicy="LRU" />
<!-- 账户锁定-->
<cache name="lock"
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="0"
timeToLiveSeconds="600"
maxElementsOnDisk="10000000"
overflowToDisk="true"
memoryStoreEvictionPolicy="LRU" />
<!-- 系统参数-->
<cache name="sysconfig"
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="0"
timeToLiveSeconds="864000"
maxElementsOnDisk="10000000"
overflowToDisk="true"
memoryStoreEvictionPolicy="LRU" />
</ehcache>

@ -129,10 +129,10 @@
</dependency> </dependency>
<!-- redis 缓存操作 --> <!-- redis 缓存操作 -->
<!-- <dependency>--> <dependency>
<!-- <groupId>org.springframework.boot</groupId>--> <groupId>org.springframework.boot</groupId>
<!-- <artifactId>spring-boot-starter-data-redis</artifactId>--> <artifactId>spring-boot-starter-data-redis</artifactId>
<!-- </dependency>--> </dependency>
<!-- pool 对象池 --> <!-- pool 对象池 -->
<dependency> <dependency>

@ -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;
/**
* IntegerString
*
* @param key
* @param value
*/
public <T> void setCacheObject(final String key, final T value)
{
redisTemplate.opsForValue().set(key, value);
}
/**
* IntegerString
*
* @param key
* @param value
* @param timeout
* @param timeUnit
*/
public <T> 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> T getCacheObject(final String key)
{
ValueOperations<String, T> 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 <T> long setCacheList(final String key, final List<T> dataList)
{
Long count = redisTemplate.opsForList().rightPushAll(key, dataList);
return count == null ? 0 : count;
}
/**
* list
*
* @param key
* @return
*/
public <T> List<T> getCacheList(final String key)
{
return redisTemplate.opsForList().range(key, 0, -1);
}
/**
* Set
*
* @param key
* @param dataSet
* @return
*/
public <T> BoundSetOperations<String, T> setCacheSet(final String key, final Set<T> dataSet)
{
BoundSetOperations<String, T> setOperation = redisTemplate.boundSetOps(key);
Iterator<T> it = dataSet.iterator();
while (it.hasNext())
{
setOperation.add(it.next());
}
return setOperation;
}
/**
* set
*
* @param key
* @return
*/
public <T> Set<T> getCacheSet(final String key)
{
return redisTemplate.opsForSet().members(key);
}
/**
* Map
*
* @param key
* @param dataMap
*/
public <T> void setCacheMap(final String key, final Map<String, T> dataMap)
{
if (dataMap != null) {
redisTemplate.opsForHash().putAll(key, dataMap);
}
}
/**
* Map
*
* @param key
* @return
*/
public <T> Map<String, T> getCacheMap(final String key)
{
return redisTemplate.opsForHash().entries(key);
}
/**
* Hash
*
* @param key Redis
* @param hKey Hash
* @param value
*/
public <T> 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> T getCacheMapValue(final String key, final String hKey)
{
HashOperations<String, String, T> opsForHash = redisTemplate.opsForHash();
return opsForHash.get(key, hKey);
}
/**
* Hash
*
* @param key Redis
* @param hKeys Hash
* @return Hash
*/
public <T> List<T> getMultiCacheMapValue(final String key, final Collection<Object> 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<String> keys(final String pattern)
{
return redisTemplate.keys(pattern);
}
}

@ -1,16 +1,12 @@
package com.ruoyi.common.utils; package com.ruoyi.common.utils;
import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONArray; import com.alibaba.fastjson2.JSONArray;
import com.ruoyi.common.constant.CacheConstants; import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.domain.entity.SysDictData; import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.spring.SpringUtils; import com.ruoyi.common.utils.spring.SpringUtils;
import net.sf.ehcache.CacheManager;
/** /**
* *
@ -32,8 +28,7 @@ public class DictUtils
*/ */
public static void setDictCache(String key, List<SysDictData> dictDatas) public static void setDictCache(String key, List<SysDictData> dictDatas)
{ {
EhcacheUtil.put("dict",getCacheKey(key),dictDatas); SpringUtils.getBean(RedisCache.class).setCacheObject(getCacheKey(key), dictDatas);
// SpringUtils.getBean(RedisCache.class).setCacheObject(getCacheKey(key), dictDatas);
} }
/** /**
@ -44,19 +39,12 @@ public class DictUtils
*/ */
public static List<SysDictData> getDictCache(String key) public static List<SysDictData> getDictCache(String key)
{ {
Object dict = EhcacheUtil.get("dict", getCacheKey(key)); JSONArray arrayCache = SpringUtils.getBean(RedisCache.class).getCacheObject(getCacheKey(key));
if (dict != null) { if (StringUtils.isNotNull(arrayCache))
JSONArray arrayCache = JSONArray.parseArray(JSONUtil.toJsonStr(dict)); {
if (CollUtil.isNotEmpty(arrayCache)) {
return arrayCache.toList(SysDictData.class); return arrayCache.toList(SysDictData.class);
} }
} return null;
// JSONArray arrayCache = SpringUtils.getBean(RedisCache.class).getCacheObject(getCacheKey(key));
// if (StringUtils.isNotNull(arrayCache))
// {
// return arrayCache.toList(SysDictData.class);
// }
return new ArrayList<>();
} }
/** /**
@ -173,8 +161,7 @@ public class DictUtils
*/ */
public static void removeDictCache(String 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,9 +169,8 @@ public class DictUtils
*/ */
public static void clearDictCache() public static void clearDictCache()
{ {
EhcacheUtil.cacheManager.getCache("dict").removeAll(); Collection<String> keys = SpringUtils.getBean(RedisCache.class).keys(CacheConstants.SYS_DICT_KEY + "*");
// Collection<String> keys = SpringUtils.getBean(RedisCache.class).keys(CacheConstants.SYS_DICT_KEY + "*"); SpringUtils.getBean(RedisCache.class).deleteObject(keys);
// SpringUtils.getBean(RedisCache.class).deleteObject(keys);
} }
/** /**

@ -3,6 +3,7 @@ package com.ruoyi.common.utils;
import com.ruoyi.common.constant.CacheConstants; import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.TreeConstants; import com.ruoyi.common.constant.TreeConstants;
import com.ruoyi.common.core.domain.DictTreeEntity; import com.ruoyi.common.core.domain.DictTreeEntity;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.spring.SpringUtils; import com.ruoyi.common.utils.spring.SpringUtils;
import java.util.ArrayList; import java.util.ArrayList;
@ -162,8 +163,7 @@ public class TreeUtils {
*/ */
public static void initCacheTreeData(String key, List<Object> node) { public static void initCacheTreeData(String key, List<Object> node) {
// 存储到redis // 存储到redis
EhcacheUtil.put("tree",getCacheKey(key),node); SpringUtils.getBean(RedisCache.class).setCacheObject(getCacheKey(key), node);
// SpringUtils.getBean(RedisCache.class).setCacheObject(getCacheKey(key), node);
} }
/** /**

@ -1,48 +1,48 @@
//package com.ruoyi.framework.config; package com.ruoyi.framework.config;
//
//import java.nio.charset.Charset; import java.nio.charset.Charset;
//import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.data.redis.serializer.RedisSerializer;
//import org.springframework.data.redis.serializer.SerializationException; import org.springframework.data.redis.serializer.SerializationException;
//import com.alibaba.fastjson2.JSON; import com.alibaba.fastjson2.JSON;
//import com.alibaba.fastjson2.JSONReader; import com.alibaba.fastjson2.JSONReader;
//import com.alibaba.fastjson2.JSONWriter; import com.alibaba.fastjson2.JSONWriter;
//
///** /**
// * Redis使用FastJson序列化 * Redis使FastJson
// * *
// * @author ruoyi * @author ruoyi
// */ */
//public class FastJson2JsonRedisSerializer<T> implements RedisSerializer<T> public class FastJson2JsonRedisSerializer<T> implements RedisSerializer<T>
//{ {
// public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
//
// private Class<T> clazz; private Class<T> clazz;
//
// public FastJson2JsonRedisSerializer(Class<T> clazz) public FastJson2JsonRedisSerializer(Class<T> clazz)
// { {
// super(); super();
// this.clazz = clazz; this.clazz = clazz;
// } }
//
// @Override @Override
// public byte[] serialize(T t) throws SerializationException public byte[] serialize(T t) throws SerializationException
// { {
// if (t == null) if (t == null)
// { {
// return new byte[0]; return new byte[0];
// } }
// return JSON.toJSONString(t, JSONWriter.Feature.WriteClassName).getBytes(DEFAULT_CHARSET); return JSON.toJSONString(t, JSONWriter.Feature.WriteClassName).getBytes(DEFAULT_CHARSET);
// } }
//
// @Override @Override
// public T deserialize(byte[] bytes) throws SerializationException public T deserialize(byte[] bytes) throws SerializationException
// { {
// if (bytes == null || bytes.length <= 0) if (bytes == null || bytes.length <= 0)
// { {
// return null; return null;
// } }
// String str = new String(bytes, DEFAULT_CHARSET); String str = new String(bytes, DEFAULT_CHARSET);
//
// return JSON.parseObject(str, clazz, JSONReader.Feature.SupportAutoType); return JSON.parseObject(str, clazz, JSONReader.Feature.SupportAutoType);
// } }
//} }

@ -1,69 +1,69 @@
//package com.ruoyi.framework.config; package com.ruoyi.framework.config;
//
//import org.springframework.cache.annotation.CachingConfigurerSupport; import org.springframework.cache.annotation.CachingConfigurerSupport;
//import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.annotation.EnableCaching;
//import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
//import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.connection.RedisConnectionFactory;
//import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.RedisTemplate;
//import org.springframework.data.redis.core.script.DefaultRedisScript; import org.springframework.data.redis.core.script.DefaultRedisScript;
//import org.springframework.data.redis.serializer.StringRedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer;
//
///** /**
// * redis配置 * redis
// * *
// * @author ruoyi * @author ruoyi
// */ */
//@Configuration @Configuration
//@EnableCaching @EnableCaching
//public class RedisConfig extends CachingConfigurerSupport public class RedisConfig extends CachingConfigurerSupport
//{ {
// @Bean @Bean
// @SuppressWarnings(value = { "unchecked", "rawtypes" }) @SuppressWarnings(value = { "unchecked", "rawtypes" })
// public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory)
// { {
// RedisTemplate<Object, Object> template = new RedisTemplate<>(); RedisTemplate<Object, Object> template = new RedisTemplate<>();
// template.setConnectionFactory(connectionFactory); template.setConnectionFactory(connectionFactory);
//
// FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer(Object.class); FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer(Object.class);
//
// // 使用StringRedisSerializer来序列化和反序列化redis的key值 // 使用StringRedisSerializer来序列化和反序列化redis的key值
// template.setKeySerializer(new StringRedisSerializer()); template.setKeySerializer(new StringRedisSerializer());
// template.setValueSerializer(serializer); template.setValueSerializer(serializer);
//
// // Hash的key也采用StringRedisSerializer的序列化方式 // Hash的key也采用StringRedisSerializer的序列化方式
// template.setHashKeySerializer(new StringRedisSerializer()); template.setHashKeySerializer(new StringRedisSerializer());
// template.setHashValueSerializer(serializer); template.setHashValueSerializer(serializer);
//
// template.afterPropertiesSet(); template.afterPropertiesSet();
// return template; return template;
// } }
//
// @Bean @Bean
// public DefaultRedisScript<Long> limitScript() public DefaultRedisScript<Long> limitScript()
// { {
// DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>(); DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
// redisScript.setScriptText(limitScriptText()); redisScript.setScriptText(limitScriptText());
// redisScript.setResultType(Long.class); redisScript.setResultType(Long.class);
// return redisScript; return redisScript;
// } }
//
// /** /**
// * 限流脚本 *
// */ */
// private String limitScriptText() private String limitScriptText()
// { {
// return "local key = KEYS[1]\n" + return "local key = KEYS[1]\n" +
// "local count = tonumber(ARGV[1])\n" + "local count = tonumber(ARGV[1])\n" +
// "local time = tonumber(ARGV[2])\n" + "local time = tonumber(ARGV[2])\n" +
// "local current = redis.call('get', key);\n" + "local current = redis.call('get', key);\n" +
// "if current and tonumber(current) > count then\n" + "if current and tonumber(current) > count then\n" +
// " return tonumber(current);\n" + " return tonumber(current);\n" +
// "end\n" + "end\n" +
// "current = redis.call('incr', key)\n" + "current = redis.call('incr', key)\n" +
// "if tonumber(current) == 1 then\n" + "if tonumber(current) == 1 then\n" +
// " redis.call('expire', key, time)\n" + " redis.call('expire', key, time)\n" +
// "end\n" + "end\n" +
// "return tonumber(current);"; "return tonumber(current);";
// } }
//} }

@ -4,14 +4,13 @@ import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import com.ruoyi.common.utils.EhcacheUtil;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import com.alibaba.fastjson2.JSON; import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.annotation.RepeatSubmit; import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.constant.CacheConstants; import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.filter.RepeatedlyRequestWrapper; import com.ruoyi.common.filter.RepeatedlyRequestWrapper;
import com.ruoyi.common.utils.StringUtils; import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpHelper; import com.ruoyi.common.utils.http.HttpHelper;
@ -34,8 +33,8 @@ public class SameUrlDataInterceptor extends RepeatSubmitInterceptor
@Value("${token.header}") @Value("${token.header}")
private String header; private String header;
// @Autowired @Autowired
// private RedisCache redisCache; private RedisCache redisCache;
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Override @Override
@ -65,8 +64,8 @@ public class SameUrlDataInterceptor extends RepeatSubmitInterceptor
// 唯一标识指定key + url + 消息头) // 唯一标识指定key + url + 消息头)
String cacheRepeatKey = CacheConstants.REPEAT_SUBMIT_KEY + url + submitKey; 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) if (sessionObj != null)
{ {
Map<String, Object> sessionMap = (Map<String, Object>) sessionObj; Map<String, Object> sessionMap = (Map<String, Object>) sessionObj;
@ -81,8 +80,7 @@ public class SameUrlDataInterceptor extends RepeatSubmitInterceptor
} }
Map<String, Object> cacheMap = new HashMap<String, Object>(); Map<String, Object> cacheMap = new HashMap<String, Object>();
cacheMap.put(url, nowDataMap); 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; return false;
} }

@ -2,7 +2,6 @@ package com.ruoyi.framework.web.service;
import javax.annotation.Resource; import javax.annotation.Resource;
import com.ruoyi.common.utils.*;
import com.ruoyi.framework.security.context.AuthenticationContextHolder; import com.ruoyi.framework.security.context.AuthenticationContextHolder;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager; 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.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysUser; import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser; 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.ServiceException;
import com.ruoyi.common.exception.user.CaptchaException; import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.exception.user.CaptchaExpireException; import com.ruoyi.common.exception.user.CaptchaExpireException;
import com.ruoyi.common.exception.user.UserPasswordNotMatchException; 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.common.utils.ip.IpUtils;
import com.ruoyi.framework.manager.AsyncManager; import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory; import com.ruoyi.framework.manager.factory.AsyncFactory;
@ -38,6 +42,9 @@ public class SysLoginService
@Resource @Resource
private AuthenticationManager authenticationManager; private AuthenticationManager authenticationManager;
@Autowired
private RedisCache redisCache;
@Autowired @Autowired
private ISysUserService userService; private ISysUserService userService;
@ -105,15 +112,14 @@ public class SysLoginService
public void validateCaptcha(String username, String code, String uuid) public void validateCaptcha(String username, String code, String uuid)
{ {
String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, ""); String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
Object captcha = EhcacheUtil.get("verify", verifyKey); String captcha = redisCache.getCacheObject(verifyKey);
// redisCache.deleteObject(verifyKey); redisCache.deleteObject(verifyKey);
if (captcha == null) if (captcha == null)
{ {
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire"))); AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
throw new CaptchaExpireException(); throw new CaptchaExpireException();
} }
EhcacheUtil.remove("verify", verifyKey); if (!code.equalsIgnoreCase(captcha))
if (!code.equalsIgnoreCase(captcha.toString()))
{ {
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error"))); AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
throw new CaptchaException(); throw new CaptchaException();

@ -1,8 +1,6 @@
package com.ruoyi.framework.web.service; package com.ruoyi.framework.web.service;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import com.ruoyi.common.utils.EhcacheUtil;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication; 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.CacheConstants;
import com.ruoyi.common.constant.Constants; import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysUser; 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.UserPasswordNotMatchException;
import com.ruoyi.common.exception.user.UserPasswordRetryLimitExceedException; import com.ruoyi.common.exception.user.UserPasswordRetryLimitExceedException;
import com.ruoyi.common.utils.MessageUtils; import com.ruoyi.common.utils.MessageUtils;
@ -26,8 +25,8 @@ import com.ruoyi.framework.security.context.AuthenticationContextHolder;
@Component @Component
public class SysPasswordService public class SysPasswordService
{ {
// @Autowired @Autowired
// private RedisCache redisCache; private RedisCache redisCache;
@Value(value = "${user.password.maxRetryCount}") @Value(value = "${user.password.maxRetryCount}")
private int maxRetryCount; private int maxRetryCount;
@ -52,11 +51,11 @@ public class SysPasswordService
String username = usernamePasswordAuthenticationToken.getName(); String username = usernamePasswordAuthenticationToken.getName();
String password = usernamePasswordAuthenticationToken.getCredentials().toString(); String password = usernamePasswordAuthenticationToken.getCredentials().toString();
Object obj = EhcacheUtil.get("lock", getCacheKey(username)); Integer retryCount = redisCache.getCacheObject(getCacheKey(username));
Integer retryCount = 0;
if (obj != null) if (retryCount == null)
{ {
retryCount = Integer.valueOf(obj.toString()); retryCount = 0;
} }
if (retryCount >= Integer.valueOf(maxRetryCount).intValue()) if (retryCount >= Integer.valueOf(maxRetryCount).intValue())
@ -71,8 +70,7 @@ public class SysPasswordService
retryCount = retryCount + 1; retryCount = retryCount + 1;
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL,
MessageUtils.message("user.password.retry.limit.count", retryCount))); 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(); throw new UserPasswordNotMatchException();
} }
else else
@ -88,11 +86,9 @@ public class SysPasswordService
public void clearLoginRecordCache(String loginName) public void clearLoginRecordCache(String loginName)
{ {
Object lock = EhcacheUtil.get("lock", getCacheKey(loginName)); if (redisCache.hasKey(getCacheKey(loginName)))
if (lock!= null)
{ {
EhcacheUtil.remove("lock", getCacheKey(loginName)); redisCache.deleteObject(getCacheKey(loginName));
// redisCache.deleteObject(getCacheKey(loginName));
} }
} }
} }

@ -5,9 +5,9 @@ import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants; import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysUser; import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.RegisterBody; 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.CaptchaException;
import com.ruoyi.common.exception.user.CaptchaExpireException; import com.ruoyi.common.exception.user.CaptchaExpireException;
import com.ruoyi.common.utils.EhcacheUtil;
import com.ruoyi.common.utils.MessageUtils; import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.SecurityUtils; import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils; import com.ruoyi.common.utils.StringUtils;
@ -31,8 +31,8 @@ public class SysRegisterService {
@Autowired @Autowired
private ISysConfigService configService; private ISysConfigService configService;
// @Autowired @Autowired
// private RedisCache redisCache; private RedisCache redisCache;
/** /**
* *
@ -82,13 +82,12 @@ public class SysRegisterService {
*/ */
public void validateCaptcha(String username, String code, String uuid) { public void validateCaptcha(String username, String code, String uuid) {
String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, ""); String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
Object obj = EhcacheUtil.get("verify", verifyKey); String captcha = redisCache.getCacheObject(verifyKey);
// String captcha = redisCache.getCacheObject(verifyKey); redisCache.deleteObject(verifyKey);
// redisCache.deleteObject(verifyKey); if (captcha == null) {
if (obj == null) {
throw new CaptchaExpireException(); throw new CaptchaExpireException();
} }
if (!code.equalsIgnoreCase(obj.toString())) { if (!code.equalsIgnoreCase(captcha)) {
throw new CaptchaException(); throw new CaptchaException();
} }
} }

@ -3,13 +3,12 @@ package com.ruoyi.system.service.impl;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
import com.ruoyi.common.utils.EhcacheUtil;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import com.ruoyi.common.annotation.DataSource; import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.constant.CacheConstants; import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.UserConstants; import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.core.text.Convert; import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.enums.DataSourceType; import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.common.exception.ServiceException; import com.ruoyi.common.exception.ServiceException;
@ -29,8 +28,8 @@ public class SysConfigServiceImpl implements ISysConfigService
@Autowired @Autowired
private SysConfigMapper configMapper; private SysConfigMapper configMapper;
// @Autowired @Autowired
// private RedisCache redisCache; private RedisCache redisCache;
/** /**
* *
@ -65,9 +64,7 @@ public class SysConfigServiceImpl implements ISysConfigService
@Override @Override
public String selectConfigByKey(String configKey) public String selectConfigByKey(String configKey)
{ {
// String configValue = Convert.toStr(redisCache.getCacheObject(getCacheKey(configKey))); String configValue = Convert.toStr(redisCache.getCacheObject(getCacheKey(configKey)));
Object obj = EhcacheUtil.get("sysconfig", getCacheKey(configKey));
String configValue = Convert.toStr(obj);
if (StringUtils.isNotEmpty(configValue)) if (StringUtils.isNotEmpty(configValue))
{ {
return configValue; return configValue;
@ -77,8 +74,7 @@ public class SysConfigServiceImpl implements ISysConfigService
SysConfig retConfig = configMapper.selectConfig(config); SysConfig retConfig = configMapper.selectConfig(config);
if (StringUtils.isNotNull(retConfig)) 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 retConfig.getConfigValue();
} }
return StringUtils.EMPTY; return StringUtils.EMPTY;
@ -124,8 +120,7 @@ public class SysConfigServiceImpl implements ISysConfigService
int row = configMapper.insertConfig(config); int row = configMapper.insertConfig(config);
if (row > 0) 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; return row;
} }
@ -142,8 +137,7 @@ public class SysConfigServiceImpl implements ISysConfigService
int row = configMapper.updateConfig(config); int row = configMapper.updateConfig(config);
if (row > 0) 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; return row;
} }
@ -164,8 +158,7 @@ public class SysConfigServiceImpl implements ISysConfigService
throw new ServiceException(String.format("内置参数【%1$s】不能删除 ", config.getConfigKey())); throw new ServiceException(String.format("内置参数【%1$s】不能删除 ", config.getConfigKey()));
} }
configMapper.deleteConfigById(configId); 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<SysConfig> configsList = configMapper.selectConfigList(new SysConfig()); List<SysConfig> configsList = configMapper.selectConfigList(new SysConfig());
for (SysConfig config : configsList) 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 @Override
public void clearConfigCache() public void clearConfigCache()
{ {
EhcacheUtil.removeAll("sysconfig"); Collection<String> keys = redisCache.keys(CacheConstants.SYS_CONFIG_KEY + "*");
// Collection<String> keys = redisCache.keys(CacheConstants.SYS_CONFIG_KEY + "*"); redisCache.deleteObject(keys);
// redisCache.deleteObject(keys);
} }
/** /**

Loading…
Cancel
Save