test1(String key, String value){
- return AjaxResult.success("操作成功", value);
- }
+ /**
+ * 测试 @Cacheable
+ *
+ * 表示这个方法有了缓存的功能,方法的返回值会被缓存下来
+ * 下一次调用该方法前,会去检查是否缓存中已经有值
+ * 如果有就直接返回,不调用方法
+ * 如果没有,就调用方法,然后把结果缓存起来
+ * 这个注解「一般用在查询方法上」
+ *
+ * 重点说明: 缓存注解严谨与其他筛选数据功能一起使用
+ * 例如: 数据权限注解 会造成 缓存击穿 与 数据不一致问题
+ *
+ * cacheNames 为配置文件内 groupId
+ */
+ @ApiOperation("测试 @Cacheable")
+ @Cacheable(cacheNames = "redissonCacheMap", key = "#key", condition = "#key != null")
+ @GetMapping("/test1")
+ public AjaxResult test1(String key, String value) {
+ return AjaxResult.success("操作成功", value);
+ }
- /**
- * 测试 @CachePut
- *
- * 加了@CachePut注解的方法,会把方法的返回值put到缓存里面缓存起来,供其它地方使用
- * 它「通常用在新增方法上」
- *
- * cacheNames 为 配置文件内 groupId
- */
- @ApiOperation("测试 @CachePut")
- @CachePut(cacheNames = "redissonCacheMap", key = "#key", condition = "#key != null")
- @GetMapping("/test2")
- public AjaxResult test2(String key, String value){
- return AjaxResult.success("操作成功", value);
- }
+ /**
+ * 测试 @CachePut
+ *
+ * 加了@CachePut注解的方法,会把方法的返回值put到缓存里面缓存起来,供其它地方使用
+ * 它「通常用在新增方法上」
+ *
+ * cacheNames 为 配置文件内 groupId
+ */
+ @ApiOperation("测试 @CachePut")
+ @CachePut(cacheNames = "redissonCacheMap", key = "#key", condition = "#key != null")
+ @GetMapping("/test2")
+ public AjaxResult test2(String key, String value) {
+ return AjaxResult.success("操作成功", value);
+ }
- /**
- * 测试 @CacheEvict
- *
- * 使用了CacheEvict注解的方法,会清空指定缓存
- * 「一般用在更新或者删除的方法上」
- *
- * cacheNames 为 配置文件内 groupId
- */
- @ApiOperation("测试 @CacheEvict")
- @CacheEvict(cacheNames = "redissonCacheMap", key = "#key", condition = "#key != null")
- @GetMapping("/test3")
- public AjaxResult test3(String key, String value){
- return AjaxResult.success("操作成功", value);
- }
+ /**
+ * 测试 @CacheEvict
+ *
+ * 使用了CacheEvict注解的方法,会清空指定缓存
+ * 「一般用在更新或者删除的方法上」
+ *
+ * cacheNames 为 配置文件内 groupId
+ */
+ @ApiOperation("测试 @CacheEvict")
+ @CacheEvict(cacheNames = "redissonCacheMap", key = "#key", condition = "#key != null")
+ @GetMapping("/test3")
+ public AjaxResult test3(String key, String value) {
+ return AjaxResult.success("操作成功", value);
+ }
- /**
- * 测试设置过期时间
- * 手动设置过期时间10秒
- * 11秒后获取 判断是否相等
- */
- @ApiOperation("测试设置过期时间")
- @GetMapping("/test6")
- public AjaxResult test6(String key, String value){
- RedisUtils.setCacheObject(key, value);
- boolean flag = RedisUtils.expire(key, 10, TimeUnit.SECONDS);
- System.out.println("***********" + flag);
- try {
- Thread.sleep(11 * 1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- Object obj = RedisUtils.getCacheObject(key);
- return AjaxResult.success("操作成功", value.equals(obj));
- }
+ /**
+ * 测试设置过期时间
+ * 手动设置过期时间10秒
+ * 11秒后获取 判断是否相等
+ */
+ @ApiOperation("测试设置过期时间")
+ @GetMapping("/test6")
+ public AjaxResult test6(String key, String value) {
+ RedisUtils.setCacheObject(key, value);
+ boolean flag = RedisUtils.expire(key, 10, TimeUnit.SECONDS);
+ System.out.println("***********" + flag);
+ try {
+ Thread.sleep(11 * 1000);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ Object obj = RedisUtils.getCacheObject(key);
+ return AjaxResult.success("操作成功", value.equals(obj));
+ }
}
diff --git a/ruoyi/src/main/java/com/ruoyi/demo/controller/RedisLockController.java b/ruoyi/src/main/java/com/ruoyi/demo/controller/RedisLockController.java
index a72024663..94ad3c3a3 100644
--- a/ruoyi/src/main/java/com/ruoyi/demo/controller/RedisLockController.java
+++ b/ruoyi/src/main/java/com/ruoyi/demo/controller/RedisLockController.java
@@ -9,7 +9,6 @@ import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@@ -28,59 +27,50 @@ import java.time.LocalTime;
@RequestMapping("/demo/redisLock")
public class RedisLockController {
- @Autowired
- private LockTemplate lockTemplate;
+ @Autowired
+ private LockTemplate lockTemplate;
- /**
- * 测试lock4j 注解
- */
- @ApiOperation("测试lock4j 注解")
- @Lock4j(keys = {"#key"})
- @GetMapping("/testLock4j")
- public AjaxResult testLock4j(String key,String value){
- System.out.println("start:"+key+",time:"+ LocalTime.now().toString());
- try {
- Thread.sleep(10000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println("end :"+key+",time:"+LocalTime.now().toString());
- return AjaxResult.success("操作成功",value);
- }
+ /**
+ * 测试lock4j 注解
+ */
+ @ApiOperation("测试lock4j 注解")
+ @Lock4j(keys = {"#key"})
+ @GetMapping("/testLock4j")
+ public AjaxResult testLock4j(String key, String value) {
+ System.out.println("start:" + key + ",time:" + LocalTime.now().toString());
+ try {
+ Thread.sleep(10000);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ System.out.println("end :" + key + ",time:" + LocalTime.now().toString());
+ return AjaxResult.success("操作成功", value);
+ }
- /**
- * 测试lock4j 工具
- */
- @ApiOperation("测试lock4j 工具")
- @GetMapping("/testLock4jLockTemaplate")
- public AjaxResult testLock4jLockTemaplate(String key,String value){
- final LockInfo lockInfo = lockTemplate.lock(key, 30000L, 5000L, RedissonLockExecutor.class);
- if (null == lockInfo) {
- throw new RuntimeException("业务处理中,请稍后再试");
- }
- // 获取锁成功,处理业务
- try {
- try {
- Thread.sleep(8000);
- } catch (InterruptedException e) {
- //
- }
- System.out.println("执行简单方法1 , 当前线程:" + Thread.currentThread().getName());
- } finally {
- //释放锁
- lockTemplate.releaseLock(lockInfo);
- }
- //结束
- return AjaxResult.success("操作成功",value);
- }
+ /**
+ * 测试lock4j 工具
+ */
+ @ApiOperation("测试lock4j 工具")
+ @GetMapping("/testLock4jLockTemaplate")
+ public AjaxResult testLock4jLockTemaplate(String key, String value) {
+ final LockInfo lockInfo = lockTemplate.lock(key, 30000L, 5000L, RedissonLockExecutor.class);
+ if (null == lockInfo) {
+ throw new RuntimeException("业务处理中,请稍后再试");
+ }
+ // 获取锁成功,处理业务
+ try {
+ try {
+ Thread.sleep(8000);
+ } catch (InterruptedException e) {
+ //
+ }
+ System.out.println("执行简单方法1 , 当前线程:" + Thread.currentThread().getName());
+ } finally {
+ //释放锁
+ lockTemplate.releaseLock(lockInfo);
+ }
+ //结束
+ return AjaxResult.success("操作成功", value);
+ }
- /**
- * 测试spring-cache注解
- */
- @ApiOperation("测试spring-cache注解")
- @Cacheable(value = "test", key = "#key")
- @GetMapping("/testCache")
- public AjaxResult testCache(String key) {
- return AjaxResult.success("操作成功", key);
- }
}
diff --git a/ruoyi/src/main/java/com/ruoyi/demo/controller/RedisPubSubController.java b/ruoyi/src/main/java/com/ruoyi/demo/controller/RedisPubSubController.java
index 810b307dc..619a69028 100644
--- a/ruoyi/src/main/java/com/ruoyi/demo/controller/RedisPubSubController.java
+++ b/ruoyi/src/main/java/com/ruoyi/demo/controller/RedisPubSubController.java
@@ -4,6 +4,7 @@ import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.RedisUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
+import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
@@ -21,22 +22,22 @@ import org.springframework.web.bind.annotation.RestController;
@RequestMapping("/demo/redis/pubsub")
public class RedisPubSubController {
- @ApiOperation("发布消息")
- @GetMapping("/pub")
- public AjaxResult pub(String key, String value){
- RedisUtils.publish(key, value, consumer -> {
- System.out.println("发布通道 => " + key + ", 发送值 => " + value);
- });
- return AjaxResult.success("操作成功");
- }
+ @ApiOperation("发布消息")
+ @GetMapping("/pub")
+ public AjaxResult pub(@ApiParam("通道Key") String key, @ApiParam("发送内容") String value) {
+ RedisUtils.publish(key, value, consumer -> {
+ System.out.println("发布通道 => " + key + ", 发送值 => " + value);
+ });
+ return AjaxResult.success("操作成功");
+ }
- @ApiOperation("订阅消息")
- @GetMapping("/sub")
- public AjaxResult sub(String key){
- RedisUtils.subscribe(key, String.class, msg -> {
- System.out.println("订阅通道 => " + key + ", 接收值 => " + msg);
- });
- return AjaxResult.success("操作成功");
- }
+ @ApiOperation("订阅消息")
+ @GetMapping("/sub")
+ public AjaxResult sub(@ApiParam("通道Key") String key) {
+ RedisUtils.subscribe(key, String.class, msg -> {
+ System.out.println("订阅通道 => " + key + ", 接收值 => " + msg);
+ });
+ return AjaxResult.success("操作成功");
+ }
}
diff --git a/ruoyi/src/main/java/com/ruoyi/demo/controller/RedisRateLimiterController.java b/ruoyi/src/main/java/com/ruoyi/demo/controller/RedisRateLimiterController.java
index 33d75093b..1eeab6114 100644
--- a/ruoyi/src/main/java/com/ruoyi/demo/controller/RedisRateLimiterController.java
+++ b/ruoyi/src/main/java/com/ruoyi/demo/controller/RedisRateLimiterController.java
@@ -22,37 +22,37 @@ import org.springframework.web.bind.annotation.RestController;
@RequestMapping("/demo/rateLimiter")
public class RedisRateLimiterController {
- /**
- * 测试全局限流
- * 全局影响
- */
- @ApiOperation("测试全局限流")
- @RateLimiter(count = 2, time = 10)
- @GetMapping("/test")
- public AjaxResult test(String value){
- return AjaxResult.success("操作成功",value);
- }
+ /**
+ * 测试全局限流
+ * 全局影响
+ */
+ @ApiOperation("测试全局限流")
+ @RateLimiter(count = 2, time = 10)
+ @GetMapping("/test")
+ public AjaxResult test(String value) {
+ return AjaxResult.success("操作成功", value);
+ }
- /**
- * 测试请求IP限流
- * 同一IP请求受影响
- */
- @ApiOperation("测试请求IP限流")
- @RateLimiter(count = 2, time = 10, limitType = LimitType.IP)
- @GetMapping("/testip")
- public AjaxResult testip(String value){
- return AjaxResult.success("操作成功",value);
- }
+ /**
+ * 测试请求IP限流
+ * 同一IP请求受影响
+ */
+ @ApiOperation("测试请求IP限流")
+ @RateLimiter(count = 2, time = 10, limitType = LimitType.IP)
+ @GetMapping("/testip")
+ public AjaxResult testip(String value) {
+ return AjaxResult.success("操作成功", value);
+ }
- /**
- * 测试集群实例限流
- * 启动两个后端服务互不影响
- */
- @ApiOperation("测试集群实例限流")
- @RateLimiter(count = 2, time = 10, limitType = LimitType.CLUSTER)
- @GetMapping("/testcluster")
- public AjaxResult testcluster(String value){
- return AjaxResult.success("操作成功",value);
- }
+ /**
+ * 测试集群实例限流
+ * 启动两个后端服务互不影响
+ */
+ @ApiOperation("测试集群实例限流")
+ @RateLimiter(count = 2, time = 10, limitType = LimitType.CLUSTER)
+ @GetMapping("/testcluster")
+ public AjaxResult testcluster(String value) {
+ return AjaxResult.success("操作成功", value);
+ }
}
diff --git a/ruoyi/src/main/java/com/ruoyi/demo/controller/Swagger3DemoController.java b/ruoyi/src/main/java/com/ruoyi/demo/controller/Swagger3DemoController.java
index a8efb64e4..6b73d64a8 100644
--- a/ruoyi/src/main/java/com/ruoyi/demo/controller/Swagger3DemoController.java
+++ b/ruoyi/src/main/java/com/ruoyi/demo/controller/Swagger3DemoController.java
@@ -21,18 +21,18 @@ import org.springframework.web.multipart.MultipartFile;
@RequestMapping("/swagger/demo")
public class Swagger3DemoController {
- /**
- * 上传请求
- * 必须使用 @RequestPart 注解标注为文件
- * dataType 必须为 "java.io.File"
- */
- @ApiOperation(value = "通用上传请求")
- @ApiImplicitParams({
- @ApiImplicitParam(name = "file", value = "文件", dataType = "java.io.File", required = true),
- })
- @PostMapping(value = "/upload")
- public AjaxResult upload(@RequestPart("file") MultipartFile file) {
- return AjaxResult.success("操作成功", file.getOriginalFilename());
- }
+ /**
+ * 上传请求
+ * 必须使用 @RequestPart 注解标注为文件
+ * dataType 必须为 "java.io.File"
+ */
+ @ApiOperation(value = "通用上传请求")
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "file", value = "文件", dataType = "java.io.File", required = true),
+ })
+ @PostMapping(value = "/upload")
+ public AjaxResult upload(@RequestPart("file") MultipartFile file) {
+ return AjaxResult.success("操作成功", file.getOriginalFilename());
+ }
}
diff --git a/ruoyi/src/main/java/com/ruoyi/demo/controller/TestBatchController.java b/ruoyi/src/main/java/com/ruoyi/demo/controller/TestBatchController.java
index ef117a11c..d6e691dbb 100644
--- a/ruoyi/src/main/java/com/ruoyi/demo/controller/TestBatchController.java
+++ b/ruoyi/src/main/java/com/ruoyi/demo/controller/TestBatchController.java
@@ -34,48 +34,48 @@ public class TestBatchController extends BaseController {
/**
* 新增批量方法 可完美替代 saveBatch 秒级插入上万数据 (对mysql负荷较大)
*/
- @ApiOperation(value = "新增批量方法")
+ @ApiOperation(value = "新增批量方法")
@PostMapping("/add")
// @DataSource(DataSourceType.SLAVE)
public AjaxResult add() {
- List list = new ArrayList<>();
- for (int i = 0; i < 1000; i++) {
- list.add(new TestDemo().setOrderNum(-1L).setTestKey("批量新增").setValue("测试新增"));
- }
+ List list = new ArrayList<>();
+ for (int i = 0; i < 1000; i++) {
+ list.add(new TestDemo().setOrderNum(-1L).setTestKey("批量新增").setValue("测试新增"));
+ }
return toAjax(iTestDemoService.saveAll(list) ? 1 : 0);
}
- /**
- * 新增或更新 可完美替代 saveOrUpdateBatch 高性能
- */
- @ApiOperation(value = "新增或更新批量方法")
- @PostMapping("/addOrUpdate")
+ /**
+ * 新增或更新 可完美替代 saveOrUpdateBatch 高性能
+ */
+ @ApiOperation(value = "新增或更新批量方法")
+ @PostMapping("/addOrUpdate")
// @DataSource(DataSourceType.SLAVE)
- public AjaxResult addOrUpdate() {
- List list = new ArrayList<>();
- for (int i = 0; i < 1000; i++) {
- list.add(new TestDemo().setOrderNum(-1L).setTestKey("批量新增").setValue("测试新增"));
- }
- iTestDemoService.saveAll(list);
- for (int i = 0; i < list.size(); i++) {
- TestDemo testDemo = list.get(i);
- testDemo.setTestKey("批量新增或修改").setValue("批量新增或修改");
- if (i % 2 == 0) {
- testDemo.setId(null);
- }
- }
- return toAjax(iTestDemoService.saveOrUpdateAll(list) ? 1 : 0);
- }
+ public AjaxResult addOrUpdate() {
+ List list = new ArrayList<>();
+ for (int i = 0; i < 1000; i++) {
+ list.add(new TestDemo().setOrderNum(-1L).setTestKey("批量新增").setValue("测试新增"));
+ }
+ iTestDemoService.saveAll(list);
+ for (int i = 0; i < list.size(); i++) {
+ TestDemo testDemo = list.get(i);
+ testDemo.setTestKey("批量新增或修改").setValue("批量新增或修改");
+ if (i % 2 == 0) {
+ testDemo.setId(null);
+ }
+ }
+ return toAjax(iTestDemoService.saveOrUpdateAll(list) ? 1 : 0);
+ }
/**
* 删除批量方法
*/
- @ApiOperation(value = "删除批量方法")
+ @ApiOperation(value = "删除批量方法")
@DeleteMapping()
// @DataSource(DataSourceType.SLAVE)
public AjaxResult remove() {
return toAjax(iTestDemoService.remove(new LambdaQueryWrapper()
- .eq(TestDemo::getOrderNum, -1L)) ? 1 : 0);
+ .eq(TestDemo::getOrderNum, -1L)) ? 1 : 0);
}
}
diff --git a/ruoyi/src/main/java/com/ruoyi/demo/controller/TestDemoController.java b/ruoyi/src/main/java/com/ruoyi/demo/controller/TestDemoController.java
index 32af7d2dc..a3b1c7ffa 100644
--- a/ruoyi/src/main/java/com/ruoyi/demo/controller/TestDemoController.java
+++ b/ruoyi/src/main/java/com/ruoyi/demo/controller/TestDemoController.java
@@ -1,5 +1,6 @@
package com.ruoyi.demo.controller;
+import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
@@ -9,17 +10,21 @@ import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.core.validate.QueryGroup;
import com.ruoyi.common.enums.BusinessType;
+import com.ruoyi.common.utils.ValidatorUtils;
+import com.ruoyi.common.excel.ExcelResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
+import com.ruoyi.demo.domain.TestDemo;
import com.ruoyi.demo.domain.bo.TestDemoBo;
+import com.ruoyi.demo.domain.bo.TestDemoImportVo;
import com.ruoyi.demo.domain.vo.TestDemoVo;
import com.ruoyi.demo.service.ITestDemoService;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
+import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
+import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
@@ -53,30 +58,45 @@ public class TestDemoController extends BaseController {
return iTestDemoService.queryPageList(bo);
}
- /**
- * 自定义分页查询
- */
- @ApiOperation("自定义分页查询")
- @PreAuthorize("@ss.hasPermi('demo:demo:list')")
- @GetMapping("/page")
- public TableDataInfo page(@Validated(QueryGroup.class) TestDemoBo bo) {
- return iTestDemoService.customPageList(bo);
- }
+ /**
+ * 自定义分页查询
+ */
+ @ApiOperation("自定义分页查询")
+ @PreAuthorize("@ss.hasPermi('demo:demo:list')")
+ @GetMapping("/page")
+ public TableDataInfo page(@Validated(QueryGroup.class) TestDemoBo bo) {
+ return iTestDemoService.customPageList(bo);
+ }
- /**
+ @ApiOperation("导入测试-校验")
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "file", value = "导入文件", dataType = "java.io.File", required = true),
+ })
+ @Log(title = "测试单表", businessType = BusinessType.IMPORT)
+ @PreAuthorize("@ss.hasPermi('demo:demo:import')")
+ @PostMapping("/importData")
+ public AjaxResult importData(@RequestPart("file") MultipartFile file) throws Exception {
+ ExcelResult excelResult = ExcelUtil.importExcel(file.getInputStream(), TestDemoImportVo.class, true);
+ List volist = excelResult.getList();
+ List list = BeanUtil.copyToList(volist, TestDemo.class);
+ iTestDemoService.saveAll(list);
+ return AjaxResult.success(excelResult.getAnalysis());
+ }
+
+ /**
* 导出测试单表列表
*/
@ApiOperation("导出测试单表列表")
@PreAuthorize("@ss.hasPermi('demo:demo:export')")
@Log(title = "测试单表", businessType = BusinessType.EXPORT)
- @GetMapping("/export")
+ @PostMapping("/export")
public void export(@Validated TestDemoBo bo, HttpServletResponse response) {
List list = iTestDemoService.queryList(bo);
- // 测试雪花id导出
+ // 测试雪花id导出
// for (TestDemoVo vo : list) {
// vo.setId(1234567891234567893L);
// }
- ExcelUtil.exportExcel(list, "测试单表", TestDemoVo.class, response);
+ ExcelUtil.exportExcel(list, "测试单表", TestDemoVo.class, response);
}
/**
@@ -85,8 +105,9 @@ public class TestDemoController extends BaseController {
@ApiOperation("获取测试单表详细信息")
@PreAuthorize("@ss.hasPermi('demo:demo:query')")
@GetMapping("/{id}")
- public AjaxResult getInfo(@NotNull(message = "主键不能为空")
- @PathVariable("id") Long id) {
+ public AjaxResult getInfo(@ApiParam("测试ID")
+ @NotNull(message = "主键不能为空")
+ @PathVariable("id") Long id) {
return AjaxResult.success(iTestDemoService.queryById(id));
}
@@ -98,7 +119,10 @@ public class TestDemoController extends BaseController {
@Log(title = "测试单表", businessType = BusinessType.INSERT)
@RepeatSubmit(interval = 2, timeUnit = TimeUnit.SECONDS, message = "不允许重复提交")
@PostMapping()
- public AjaxResult add(@Validated(AddGroup.class) @RequestBody TestDemoBo bo) {
+ public AjaxResult add(@RequestBody TestDemoBo bo) {
+ // 使用校验工具对标 @Validated(AddGroup.class) 注解
+ // 用于在非 Controller 的地方校验对象
+ ValidatorUtils.validate(bo, AddGroup.class);
return toAjax(iTestDemoService.insertByBo(bo) ? 1 : 0);
}
@@ -119,10 +143,11 @@ public class TestDemoController extends BaseController {
*/
@ApiOperation("删除测试单表")
@PreAuthorize("@ss.hasPermi('demo:demo:remove')")
- @Log(title = "测试单表" , businessType = BusinessType.DELETE)
+ @Log(title = "测试单表", businessType = BusinessType.DELETE)
@DeleteMapping("/{ids}")
- public AjaxResult remove(@NotEmpty(message = "主键不能为空")
- @PathVariable Long[] ids) {
+ public AjaxResult remove(@ApiParam("测试ID串")
+ @NotEmpty(message = "主键不能为空")
+ @PathVariable Long[] ids) {
return toAjax(iTestDemoService.deleteWithValidByIds(Arrays.asList(ids), true) ? 1 : 0);
}
}
diff --git a/ruoyi/src/main/java/com/ruoyi/demo/controller/TestI18nController.java b/ruoyi/src/main/java/com/ruoyi/demo/controller/TestI18nController.java
index bb0695f78..40b031b51 100644
--- a/ruoyi/src/main/java/com/ruoyi/demo/controller/TestI18nController.java
+++ b/ruoyi/src/main/java/com/ruoyi/demo/controller/TestI18nController.java
@@ -4,16 +4,24 @@ import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.MessageUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
+import io.swagger.annotations.ApiParam;
+import lombok.Data;
+import org.hibernate.validator.constraints.Range;
+import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
+import javax.validation.constraints.NotBlank;
+import javax.validation.constraints.NotNull;
+
/**
* 测试国际化
*
* @author Lion Li
*/
+@Validated
@Api(value = "测试国际化控制器", tags = {"测试国际化管理"})
@RestController
@RequestMapping("/demo/i18n")
@@ -27,7 +35,42 @@ public class TestI18nController {
*/
@ApiOperation("通过code获取国际化内容")
@GetMapping()
- public AjaxResult get(String code) {
+ public AjaxResult get(@ApiParam("国际化code") String code) {
return AjaxResult.success(MessageUtils.message(code));
}
+
+ /**
+ * Validator 校验国际化
+ * 不传值 分别查看异常返回
+ *
+ * 测试使用 not.null
+ */
+ @ApiOperation("Validator 校验国际化")
+ @GetMapping("/test1")
+ public AjaxResult test1(@NotBlank(message = "{not.null}") String str) {
+ return AjaxResult.success(str);
+ }
+
+ /**
+ * Bean 校验国际化
+ * 不传值 分别查看异常返回
+ *
+ * 测试使用 not.null
+ */
+ @ApiOperation("Bean 校验国际化")
+ @GetMapping("/test2")
+ public AjaxResult test2(@Validated TestI18nBo bo) {
+ return AjaxResult.success(bo);
+ }
+
+ @Data
+ public static class TestI18nBo {
+
+ @NotBlank(message = "{not.null}")
+ private String name;
+
+ @NotNull(message = "{not.null}")
+ @Range(min = 0, max = 100, message = "{length.not.valid}")
+ private Integer age;
+ }
}
diff --git a/ruoyi/src/main/java/com/ruoyi/demo/controller/TestTreeController.java b/ruoyi/src/main/java/com/ruoyi/demo/controller/TestTreeController.java
index c34c77c4b..463ea3bf6 100644
--- a/ruoyi/src/main/java/com/ruoyi/demo/controller/TestTreeController.java
+++ b/ruoyi/src/main/java/com/ruoyi/demo/controller/TestTreeController.java
@@ -14,6 +14,7 @@ import com.ruoyi.demo.domain.vo.TestTreeVo;
import com.ruoyi.demo.service.ITestTreeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
+import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
@@ -61,7 +62,7 @@ public class TestTreeController extends BaseController {
@GetMapping("/export")
public void export(@Validated TestTreeBo bo, HttpServletResponse response) {
List list = iTestTreeService.queryList(bo);
- ExcelUtil.exportExcel(list, "测试树表", TestTreeVo.class, response);
+ ExcelUtil.exportExcel(list, "测试树表", TestTreeVo.class, response);
}
/**
@@ -70,8 +71,9 @@ public class TestTreeController extends BaseController {
@ApiOperation("获取测试树表详细信息")
@PreAuthorize("@ss.hasPermi('demo:tree:query')")
@GetMapping("/{id}")
- public AjaxResult getInfo(@NotNull(message = "主键不能为空")
- @PathVariable("id") Long id) {
+ public AjaxResult getInfo(@ApiParam("测试树ID")
+ @NotNull(message = "主键不能为空")
+ @PathVariable("id") Long id) {
return AjaxResult.success(iTestTreeService.queryById(id));
}
@@ -104,10 +106,11 @@ public class TestTreeController extends BaseController {
*/
@ApiOperation("删除测试树表")
@PreAuthorize("@ss.hasPermi('demo:tree:remove')")
- @Log(title = "测试树表" , businessType = BusinessType.DELETE)
+ @Log(title = "测试树表", businessType = BusinessType.DELETE)
@DeleteMapping("/{ids}")
- public AjaxResult remove(@NotEmpty(message = "主键不能为空")
- @PathVariable Long[] ids) {
+ public AjaxResult remove(@ApiParam("测试树ID串")
+ @NotEmpty(message = "主键不能为空")
+ @PathVariable Long[] ids) {
return toAjax(iTestTreeService.deleteWithValidByIds(Arrays.asList(ids), true) ? 1 : 0);
}
}
diff --git a/ruoyi/src/main/java/com/ruoyi/demo/feign/FeignTestService.java b/ruoyi/src/main/java/com/ruoyi/demo/feign/FeignTestService.java
deleted file mode 100644
index 50eb4ebf6..000000000
--- a/ruoyi/src/main/java/com/ruoyi/demo/feign/FeignTestService.java
+++ /dev/null
@@ -1,27 +0,0 @@
-package com.ruoyi.demo.feign;
-
-import com.ruoyi.demo.feign.constant.FeignTestConstant;
-import com.ruoyi.demo.feign.fallback.FeignTestFallback;
-import org.springframework.cloud.openfeign.FeignClient;
-import org.springframework.web.bind.annotation.GetMapping;
-import org.springframework.web.bind.annotation.RequestParam;
-
-/**
- * feign测试service
- * 规范接口 Service 无感调用
- * 常量管理请求路径 更加规范
- * 自定义容错处理 安全可靠 (需自行配置熔断器)
- * 增加 feign 的目的为使 http 请求接口化
- *
- * @author Lion Li
- * @deprecated 由于使用人数较少 决定与 3.4.0 版本移除
- */
-@FeignClient(
- name = FeignTestConstant.BAIDU_NAME,
- url = FeignTestConstant.BAIDU_URL,
- fallback = FeignTestFallback.class)
-public interface FeignTestService {
-
- @GetMapping("/s")
- String search(@RequestParam("wd") String wd);
-}
diff --git a/ruoyi/src/main/java/com/ruoyi/demo/feign/constant/FeignTestConstant.java b/ruoyi/src/main/java/com/ruoyi/demo/feign/constant/FeignTestConstant.java
deleted file mode 100644
index 28dfa8adb..000000000
--- a/ruoyi/src/main/java/com/ruoyi/demo/feign/constant/FeignTestConstant.java
+++ /dev/null
@@ -1,13 +0,0 @@
-package com.ruoyi.demo.feign.constant;
-
-/**
- * @deprecated 由于使用人数较少 决定与 3.4.0 版本移除
- */
-@Deprecated
-public class FeignTestConstant {
-
- public static final String BAIDU_NAME = "baidu";
-
- public static final String BAIDU_URL = "http://www.baidu.com";
-
-}
diff --git a/ruoyi/src/main/java/com/ruoyi/demo/feign/fallback/FeignTestFallback.java b/ruoyi/src/main/java/com/ruoyi/demo/feign/fallback/FeignTestFallback.java
deleted file mode 100644
index 8e81ad7ad..000000000
--- a/ruoyi/src/main/java/com/ruoyi/demo/feign/fallback/FeignTestFallback.java
+++ /dev/null
@@ -1,28 +0,0 @@
-package com.ruoyi.demo.feign.fallback;
-
-
-import com.ruoyi.demo.feign.FeignTestService;
-import lombok.extern.slf4j.Slf4j;
-import org.springframework.stereotype.Component;
-
-/**
- * feign测试fallback
- * 自定义封装结构体熔断
- * 需重写解码器 根据自定义实体 自行解析熔断
- *
- * 熔断器需要自行添加配置
- *
- * @see {com.ruoyi.framework.config.FeignConfig#errorDecoder()}
- * @author Lion Li
- * @deprecated 由于使用人数较少 决定与 3.4.0 版本移除
- */
-@Slf4j
-@Component
-public class FeignTestFallback implements FeignTestService {
-
- @Override
- public String search(String wd) {
- log.error("fallback");
- return "报错啦";
- }
-}
diff --git a/ruoyi/src/main/java/com/ruoyi/demo/feign/fallback/package-info.java b/ruoyi/src/main/java/com/ruoyi/demo/feign/fallback/package-info.java
deleted file mode 100644
index 47983a0e1..000000000
--- a/ruoyi/src/main/java/com/ruoyi/demo/feign/fallback/package-info.java
+++ /dev/null
@@ -1 +0,0 @@
-package com.ruoyi.demo.feign.fallback;
\ No newline at end of file
diff --git a/ruoyi/src/main/java/com/ruoyi/demo/feign/package-info.java b/ruoyi/src/main/java/com/ruoyi/demo/feign/package-info.java
deleted file mode 100644
index 91e4b4a5b..000000000
--- a/ruoyi/src/main/java/com/ruoyi/demo/feign/package-info.java
+++ /dev/null
@@ -1 +0,0 @@
-package com.ruoyi.demo.feign;
\ No newline at end of file
diff --git a/ruoyi/src/main/java/com/ruoyi/demo/mapper/TestDemoMapper.java b/ruoyi/src/main/java/com/ruoyi/demo/mapper/TestDemoMapper.java
index efbbffc44..dccea6154 100644
--- a/ruoyi/src/main/java/com/ruoyi/demo/mapper/TestDemoMapper.java
+++ b/ruoyi/src/main/java/com/ruoyi/demo/mapper/TestDemoMapper.java
@@ -2,11 +2,9 @@ package com.ruoyi.demo.mapper;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
-import com.ruoyi.common.core.mybatisplus.cache.MybatisPlusRedisCache;
import com.ruoyi.common.core.mybatisplus.core.BaseMapperPlus;
import com.ruoyi.demo.domain.TestDemo;
import com.ruoyi.demo.domain.vo.TestDemoVo;
-import org.apache.ibatis.annotations.CacheNamespace;
import org.apache.ibatis.annotations.Param;
/**
@@ -15,8 +13,6 @@ import org.apache.ibatis.annotations.Param;
* @author Lion Li
* @date 2021-07-26
*/
-// 如使需切换数据源 请勿使用缓存 会造成数据不一致现象
-@CacheNamespace(implementation = MybatisPlusRedisCache.class, eviction = MybatisPlusRedisCache.class)
public interface TestDemoMapper extends BaseMapperPlus {
Page customPageList(@Param("page") Page page, @Param("ew") Wrapper wrapper);
diff --git a/ruoyi/src/main/java/com/ruoyi/framework/aspectj/DataScopeAspect.java b/ruoyi/src/main/java/com/ruoyi/framework/aspectj/DataScopeAspect.java
index e4a6cdcdb..40cedcaff 100644
--- a/ruoyi/src/main/java/com/ruoyi/framework/aspectj/DataScopeAspect.java
+++ b/ruoyi/src/main/java/com/ruoyi/framework/aspectj/DataScopeAspect.java
@@ -5,9 +5,11 @@ import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
+import com.ruoyi.common.core.service.UserService;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.reflect.ReflectUtils;
+import com.ruoyi.common.utils.spring.SpringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@@ -64,8 +66,8 @@ public class DataScopeAspect {
// 获取当前的用户
LoginUser loginUser = SecurityUtils.getLoginUser();
if (StringUtils.isNotNull(loginUser)) {
- SysUser currentUser = loginUser.getUser();
- // 如果是超级管理员,则不过滤数据
+ SysUser currentUser = SpringUtils.getBean(UserService.class).selectUserById(loginUser.getUserId());
+ // 如果是超级管理员,则不过滤数据
if (StringUtils.isNotNull(currentUser) && !currentUser.isAdmin()) {
dataScopeFilter(joinPoint, currentUser, controllerDataScope.deptAlias(),
controllerDataScope.userAlias(), controllerDataScope.isUser());
diff --git a/ruoyi/src/main/java/com/ruoyi/framework/aspectj/RepeatSubmitAspect.java b/ruoyi/src/main/java/com/ruoyi/framework/aspectj/RepeatSubmitAspect.java
index 41116d880..f8f5c370b 100644
--- a/ruoyi/src/main/java/com/ruoyi/framework/aspectj/RepeatSubmitAspect.java
+++ b/ruoyi/src/main/java/com/ruoyi/framework/aspectj/RepeatSubmitAspect.java
@@ -1,13 +1,12 @@
package com.ruoyi.framework.aspectj;
-import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
-import com.baomidou.lock.LockInfo;
-import com.baomidou.lock.LockTemplate;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.properties.TokenProperties;
+import com.ruoyi.common.utils.JsonUtils;
+import com.ruoyi.common.utils.RedisUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.config.properties.RepeatSubmitProperties;
@@ -18,8 +17,14 @@ import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
+import org.springframework.validation.BindingResult;
+import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.util.Collection;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
/**
* 防止重复提交
@@ -34,7 +39,6 @@ public class RepeatSubmitAspect {
private final TokenProperties tokenProperties;
private final RepeatSubmitProperties repeatSubmitProperties;
- private final LockTemplate lockTemplate;
@Before("@annotation(repeatSubmit)")
public void doBefore(JoinPoint point, RepeatSubmit repeatSubmit) throws Throwable {
@@ -47,7 +51,7 @@ public class RepeatSubmitAspect {
throw new ServiceException("重复提交间隔时间不能小于'1'秒");
}
HttpServletRequest request = ServletUtils.getRequest();
- String nowParams = StrUtil.join(",", point.getArgs());
+ String nowParams = argsArrayToString(point.getArgs());
// 请求地址(作为存放cache的key值)
String url = request.getRequestURI();
@@ -60,10 +64,58 @@ public class RepeatSubmitAspect {
submitKey = SecureUtil.md5(submitKey + ":" + nowParams);
// 唯一标识(指定key + 消息头)
String cacheRepeatKey = Constants.REPEAT_SUBMIT_KEY + submitKey;
- LockInfo lock = lockTemplate.lock(cacheRepeatKey, interval, interval / 2);
- if (lock == null) {
+ String key = RedisUtils.getCacheObject(cacheRepeatKey);
+ if (key == null) {
+ RedisUtils.setCacheObject(cacheRepeatKey, "", interval, TimeUnit.MILLISECONDS);
+ } else {
throw new ServiceException(repeatSubmit.message());
}
}
+ /**
+ * 参数拼装
+ */
+ private String argsArrayToString(Object[] paramsArray) {
+ StringBuilder params = new StringBuilder();
+ if (paramsArray != null && paramsArray.length > 0) {
+ for (Object o : paramsArray) {
+ if (StringUtils.isNotNull(o) && !isFilterObject(o)) {
+ try {
+ params.append(JsonUtils.toJsonString(o)).append(" ");
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+ }
+ }
+ return params.toString().trim();
+ }
+
+ /**
+ * 判断是否需要过滤的对象。
+ *
+ * @param o 对象信息。
+ * @return 如果是需要过滤的对象,则返回true;否则返回false。
+ */
+ @SuppressWarnings("rawtypes")
+ public boolean isFilterObject(final Object o) {
+ Class> clazz = o.getClass();
+ if (clazz.isArray()) {
+ return clazz.getComponentType().isAssignableFrom(MultipartFile.class);
+ } else if (Collection.class.isAssignableFrom(clazz)) {
+ Collection collection = (Collection) o;
+ for (Object value : collection) {
+ return value instanceof MultipartFile;
+ }
+ } else if (Map.class.isAssignableFrom(clazz)) {
+ Map map = (Map) o;
+ for (Object value : map.entrySet()) {
+ Map.Entry entry = (Map.Entry) value;
+ return entry.getValue() instanceof MultipartFile;
+ }
+ }
+ return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse
+ || o instanceof BindingResult;
+ }
+
}
diff --git a/ruoyi/src/main/java/com/ruoyi/framework/config/FeignConfig.java b/ruoyi/src/main/java/com/ruoyi/framework/config/FeignConfig.java
deleted file mode 100644
index 8b432ad89..000000000
--- a/ruoyi/src/main/java/com/ruoyi/framework/config/FeignConfig.java
+++ /dev/null
@@ -1,95 +0,0 @@
-package com.ruoyi.framework.config;
-
-import feign.*;
-import okhttp3.ConnectionPool;
-import okhttp3.OkHttpClient;
-import org.springframework.boot.autoconfigure.AutoConfigureBefore;
-import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
-import org.springframework.cloud.openfeign.EnableFeignClients;
-import org.springframework.cloud.openfeign.FeignAutoConfiguration;
-import org.springframework.cloud.openfeign.support.SpringMvcContract;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-
-import java.util.concurrent.TimeUnit;
-
-/**
- * openfeign配置类
- *
- * @author Lion Li
- * @deprecated 由于使用人数较少 决定与 3.4.0 版本移除
- */
-@Deprecated
-@EnableFeignClients("${feign.package}")
-@Configuration
-@ConditionalOnClass(Feign.class)
-@AutoConfigureBefore(FeignAutoConfiguration.class)
-public class FeignConfig {
-
- @Bean
- public OkHttpClient okHttpClient(){
- return new OkHttpClient.Builder()
- .readTimeout(60, TimeUnit.SECONDS)
- .connectTimeout(60, TimeUnit.SECONDS)
- .writeTimeout(120, TimeUnit.SECONDS)
- .connectionPool(new ConnectionPool())
- .build();
- }
-
- @Bean
- public Contract feignContract() {
- return new SpringMvcContract();
- }
-
- @Bean
- public Logger.Level feignLoggerLevel() {
- return Logger.Level.BASIC;
- }
-
- @Bean
- public Request.Options feignRequestOptions() {
- return new Request.Options(10, TimeUnit.SECONDS, 60,TimeUnit.SECONDS,true);
- }
-
- @Bean
- public Retryer feignRetry() {
- return new Retryer.Default();
- }
-
-// /**
-// * 自定义异常解码器
-// * 用于自定义返回体异常熔断
-// */
-// @Bean
-// public ErrorDecoder errorDecoder() {
-// return new CustomErrorDecoder();
-// }
-//
-//
-// /**
-// * 自定义返回体解码器
-// */
-// @Slf4j
-// public static class CustomErrorDecoder implements ErrorDecoder {
-//
-// @Override
-// public Exception decode(String methodKey, Response response) {
-// Exception exception = null;
-// try {
-// // 获取原始的返回内容
-// String json = JsonUtils.toJsonString(response.body().asReader(StandardCharsets.UTF_8));
-// exception = new RuntimeException(json);
-// // 将返回内容反序列化为Result,这里应根据自身项目作修改
-// AjaxResult result = JsonUtils.parseObject(json, AjaxResult.class);
-// // 业务异常抛出简单的 RuntimeException,保留原来错误信息
-// if (result.getCode() != 200) {
-// exception = new RuntimeException(result.getMsg());
-// }
-// } catch (IOException e) {
-// log.error(e.getMessage(), e);
-// }
-// return exception;
-// }
-// }
-
-}
diff --git a/ruoyi/src/main/java/com/ruoyi/framework/config/FilterConfig.java b/ruoyi/src/main/java/com/ruoyi/framework/config/FilterConfig.java
index 459020d87..6f3b099ab 100644
--- a/ruoyi/src/main/java/com/ruoyi/framework/config/FilterConfig.java
+++ b/ruoyi/src/main/java/com/ruoyi/framework/config/FilterConfig.java
@@ -20,7 +20,6 @@ import java.util.Map;
* @author Lion Li
*/
@Configuration
-@ConditionalOnProperty(value = "xss.enabled", havingValue = "true")
public class FilterConfig {
@Autowired
@@ -28,6 +27,7 @@ public class FilterConfig {
@SuppressWarnings({"rawtypes", "unchecked"})
@Bean
+ @ConditionalOnProperty(value = "xss.enabled", havingValue = "true")
public FilterRegistrationBean xssFilterRegistration() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setDispatcherTypes(DispatcherType.REQUEST);
diff --git a/ruoyi/src/main/java/com/ruoyi/framework/config/I18nConfig.java b/ruoyi/src/main/java/com/ruoyi/framework/config/I18nConfig.java
index 48b341beb..20b52a8e2 100644
--- a/ruoyi/src/main/java/com/ruoyi/framework/config/I18nConfig.java
+++ b/ruoyi/src/main/java/com/ruoyi/framework/config/I18nConfig.java
@@ -1,7 +1,6 @@
package com.ruoyi.framework.config;
import cn.hutool.core.util.StrUtil;
-import org.jetbrains.annotations.NotNull;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
@@ -28,7 +27,6 @@ public class I18nConfig {
*/
static class I18nLocaleResolver implements LocaleResolver {
- @NotNull
@Override
public Locale resolveLocale(HttpServletRequest httpServletRequest) {
String language = httpServletRequest.getHeader("content-language");
@@ -41,7 +39,7 @@ public class I18nConfig {
}
@Override
- public void setLocale(@NotNull HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {
+ public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {
}
}
diff --git a/ruoyi/src/main/java/com/ruoyi/framework/config/SecurityConfig.java b/ruoyi/src/main/java/com/ruoyi/framework/config/SecurityConfig.java
index bb8b7f231..450eccd45 100644
--- a/ruoyi/src/main/java/com/ruoyi/framework/config/SecurityConfig.java
+++ b/ruoyi/src/main/java/com/ruoyi/framework/config/SecurityConfig.java
@@ -21,18 +21,17 @@ import org.springframework.web.filter.CorsFilter;
/**
* spring security配置
- *
+ *
* @author ruoyi
*/
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
-public class SecurityConfig extends WebSecurityConfigurerAdapter
-{
+public class SecurityConfig extends WebSecurityConfigurerAdapter {
/**
* 自定义用户认证逻辑
*/
@Autowired
private UserDetailsService userDetailsService;
-
+
/**
* 认证失败处理类
*/
@@ -50,7 +49,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter
*/
@Autowired
private JwtAuthenticationTokenFilter authenticationTokenFilter;
-
+
/**
* 跨域过滤器
*/
@@ -68,8 +67,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter
*/
@Bean
@Override
- public AuthenticationManager authenticationManagerBean() throws Exception
- {
+ public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@@ -89,31 +87,30 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter
* authenticated | 用户登录后可访问
*/
@Override
- protected void configure(HttpSecurity httpSecurity) throws Exception
- {
+ protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
- // CSRF禁用,因为不使用session
- .csrf().disable()
- // 认证失败处理类
- .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
- // 基于token,所以不需要session
- .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
- // 过滤请求
- .authorizeRequests()
- .antMatchers(
- HttpMethod.GET,
- "/",
- "/*.html",
- "/**/*.html",
- "/**/*.css",
- "/**/*.js"
- ).permitAll()
- .antMatchers(securityProperties.getAnonymous()).anonymous()
- .antMatchers(securityProperties.getPermitAll()).permitAll()
- // 除上面外的所有请求全部需要鉴权认证
- .anyRequest().authenticated()
- .and()
- .headers().frameOptions().disable();
+ // CSRF禁用,因为不使用session
+ .csrf().disable()
+ // 认证失败处理类
+ .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
+ // 基于token,所以不需要session
+ .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
+ // 过滤请求
+ .authorizeRequests()
+ .antMatchers(
+ HttpMethod.GET,
+ "/",
+ "/*.html",
+ "/**/*.html",
+ "/**/*.css",
+ "/**/*.js"
+ ).permitAll()
+ .antMatchers(securityProperties.getAnonymous()).anonymous()
+ .antMatchers(securityProperties.getPermitAll()).permitAll()
+ // 除上面外的所有请求全部需要鉴权认证
+ .anyRequest().authenticated()
+ .and()
+ .headers().frameOptions().disable();
httpSecurity.logout().logoutUrl(securityProperties.getLogoutUrl()).logoutSuccessHandler(logoutSuccessHandler);
// 添加JWT filter
httpSecurity.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
@@ -126,8 +123,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter
* 强散列哈希加密实现
*/
@Bean
- public BCryptPasswordEncoder bCryptPasswordEncoder()
- {
+ public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
@@ -135,8 +131,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter
* 身份认证接口
*/
@Override
- protected void configure(AuthenticationManagerBuilder auth) throws Exception
- {
+ protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
}
}
diff --git a/ruoyi/src/main/java/com/ruoyi/framework/config/SwaggerConfig.java b/ruoyi/src/main/java/com/ruoyi/framework/config/SwaggerConfig.java
index 4da3b9949..bf6bc8f9f 100644
--- a/ruoyi/src/main/java/com/ruoyi/framework/config/SwaggerConfig.java
+++ b/ruoyi/src/main/java/com/ruoyi/framework/config/SwaggerConfig.java
@@ -1,6 +1,7 @@
package com.ruoyi.framework.config;
import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
+import com.github.xiaoymin.knife4j.spring.extension.OpenApiExtensionResolver;
import com.ruoyi.common.properties.TokenProperties;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
@@ -35,6 +36,9 @@ public class SwaggerConfig {
@Autowired
private TokenProperties tokenProperties;
+ @Autowired
+ private OpenApiExtensionResolver openApiExtensionResolver;
+
/**
* 创建API
*/
@@ -59,6 +63,7 @@ public class SwaggerConfig {
// 设置安全模式,swagger可以设置访问token
.securitySchemes(securitySchemes())
.securityContexts(securityContexts())
+ .extensions(openApiExtensionResolver.buildExtensions(group.getName()))
.pathMapping(swaggerProperties.getPathMapping());
String beanName = StringUtils.substringAfterLast(basePackage, ".") + "Docket";
SpringUtils.registerBean(beanName, docket);
diff --git a/ruoyi/src/main/java/com/ruoyi/framework/config/TLogConfig.java b/ruoyi/src/main/java/com/ruoyi/framework/config/TLogConfig.java
index 68bc425d6..c1665d9b0 100644
--- a/ruoyi/src/main/java/com/ruoyi/framework/config/TLogConfig.java
+++ b/ruoyi/src/main/java/com/ruoyi/framework/config/TLogConfig.java
@@ -1,7 +1,6 @@
package com.ruoyi.framework.config;
import com.yomahub.tlog.core.aop.AspectLogAop;
-import com.yomahub.tlog.feign.filter.TLogFeignFilter;
import com.yomahub.tlog.spring.TLogPropertyInit;
import com.yomahub.tlog.spring.TLogSpringAware;
import com.yomahub.tlog.springboot.property.TLogProperty;
@@ -41,9 +40,4 @@ public class TLogConfig {
return new AspectLogAop();
}
- @Bean
- public TLogFeignFilter tLogFeignFilter() {
- return new TLogFeignFilter();
- }
-
}
diff --git a/ruoyi/src/main/java/com/ruoyi/framework/config/ValidatorConfig.java b/ruoyi/src/main/java/com/ruoyi/framework/config/ValidatorConfig.java
index 258e855cd..0a2007c81 100644
--- a/ruoyi/src/main/java/com/ruoyi/framework/config/ValidatorConfig.java
+++ b/ruoyi/src/main/java/com/ruoyi/framework/config/ValidatorConfig.java
@@ -1,12 +1,14 @@
package com.ruoyi.framework.config;
import org.hibernate.validator.HibernateValidator;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
+import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
-import javax.validation.Validation;
import javax.validation.Validator;
-import javax.validation.ValidatorFactory;
+import java.util.Properties;
/**
* 校验框架配置类
@@ -16,16 +18,26 @@ import javax.validation.ValidatorFactory;
@Configuration
public class ValidatorConfig {
+ @Autowired
+ private MessageSource messageSource;
+
/**
* 配置校验框架 快速返回模式
*/
@Bean
public Validator validator() {
- ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class)
- .configure()
- .failFast(true)
- .buildValidatorFactory();
- return validatorFactory.getValidator();
+ LocalValidatorFactoryBean factoryBean = new LocalValidatorFactoryBean();
+ // 国际化
+ factoryBean.setValidationMessageSource(messageSource);
+ // 设置使用 HibernateValidator 校验器
+ factoryBean.setProviderClass(HibernateValidator.class);
+ Properties properties = new Properties();
+ // 设置 快速异常返回
+ properties.setProperty("hibernate.validator.fail_fast", "true");
+ factoryBean.setValidationProperties(properties);
+ // 加载配置
+ factoryBean.afterPropertiesSet();
+ return factoryBean.getValidator();
}
}
diff --git a/ruoyi/src/main/java/com/ruoyi/framework/manager/ShutdownManager.java b/ruoyi/src/main/java/com/ruoyi/framework/manager/ShutdownManager.java
index 4ed536690..ef77a219a 100644
--- a/ruoyi/src/main/java/com/ruoyi/framework/manager/ShutdownManager.java
+++ b/ruoyi/src/main/java/com/ruoyi/framework/manager/ShutdownManager.java
@@ -14,7 +14,7 @@ import java.util.concurrent.ScheduledExecutorService;
*
* @author Lion Li
*/
-@Slf4j(topic = "sys-user")
+@Slf4j
@Component
public class ShutdownManager {
diff --git a/ruoyi/src/main/java/com/ruoyi/framework/web/exception/GlobalExceptionHandler.java b/ruoyi/src/main/java/com/ruoyi/framework/web/exception/GlobalExceptionHandler.java
index d76e61601..4c642c2d7 100644
--- a/ruoyi/src/main/java/com/ruoyi/framework/web/exception/GlobalExceptionHandler.java
+++ b/ruoyi/src/main/java/com/ruoyi/framework/web/exception/GlobalExceptionHandler.java
@@ -6,6 +6,7 @@ import com.ruoyi.common.exception.DemoModeException;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
+import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
@@ -14,7 +15,9 @@ import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.servlet.http.HttpServletRequest;
+import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
+import java.util.stream.Collectors;
/**
* 全局异常处理器
@@ -82,7 +85,9 @@ public class GlobalExceptionHandler {
@ExceptionHandler(BindException.class)
public AjaxResult handleBindException(BindException e) {
log.error(e.getMessage(), e);
- String message = e.getAllErrors().get(0).getDefaultMessage();
+ String message = e.getAllErrors().stream()
+ .map(DefaultMessageSourceResolvable::getDefaultMessage)
+ .collect(Collectors.joining(", "));
return AjaxResult.error(message);
}
@@ -92,7 +97,9 @@ public class GlobalExceptionHandler {
@ExceptionHandler(ConstraintViolationException.class)
public AjaxResult constraintViolationException(ConstraintViolationException e) {
log.error(e.getMessage(), e);
- String message = e.getConstraintViolations().iterator().next().getMessage();
+ String message = e.getConstraintViolations().stream()
+ .map(ConstraintViolation::getMessage)
+ .collect(Collectors.joining(", "));
return AjaxResult.error(message);
}
diff --git a/ruoyi/src/main/java/com/ruoyi/generator/controller/GenController.java b/ruoyi/src/main/java/com/ruoyi/generator/controller/GenController.java
index 649d1dc67..b90addf71 100644
--- a/ruoyi/src/main/java/com/ruoyi/generator/controller/GenController.java
+++ b/ruoyi/src/main/java/com/ruoyi/generator/controller/GenController.java
@@ -1,6 +1,7 @@
package com.ruoyi.generator.controller;
import cn.hutool.core.convert.Convert;
+import cn.hutool.core.io.IoUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
@@ -13,7 +14,6 @@ import com.ruoyi.generator.service.IGenTableService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
-import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
@@ -201,6 +201,6 @@ public class GenController extends BaseController {
response.setHeader("Content-Disposition", "attachment; filename=\"ruoyi.zip\"");
response.addHeader("Content-Length", "" + data.length);
response.setContentType("application/octet-stream; charset=UTF-8");
- IOUtils.write(data, response.getOutputStream());
+ IoUtil.write(response.getOutputStream(), false, data);
}
-}
\ No newline at end of file
+}
diff --git a/ruoyi/src/main/java/com/ruoyi/generator/service/GenTableServiceImpl.java b/ruoyi/src/main/java/com/ruoyi/generator/service/GenTableServiceImpl.java
index 62fe67a3a..b53393f0c 100644
--- a/ruoyi/src/main/java/com/ruoyi/generator/service/GenTableServiceImpl.java
+++ b/ruoyi/src/main/java/com/ruoyi/generator/service/GenTableServiceImpl.java
@@ -2,6 +2,7 @@ package com.ruoyi.generator.service;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
+import cn.hutool.core.io.IoUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.GenConstants;
@@ -21,7 +22,7 @@ import com.ruoyi.generator.util.GenUtils;
import com.ruoyi.generator.util.VelocityInitializer;
import com.ruoyi.generator.util.VelocityUtils;
import lombok.extern.slf4j.Slf4j;
-import org.apache.commons.io.IOUtils;
+import org.apache.poi.util.IOUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
@@ -33,6 +34,7 @@ import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
+import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
@@ -341,8 +343,8 @@ public class GenTableServiceImpl extends ServicePlusImpl dicts = new ArrayList();
for (GenTableColumn column : columns) {
if (!column.isSuperColumn() && StringUtils.isNotEmpty(column.getDictType()) && StringUtils.equalsAny(
- column.getHtmlType(), new String[]{GenConstants.HTML_SELECT, GenConstants.HTML_RADIO})) {
+ column.getHtmlType(),
+ new String[] { GenConstants.HTML_SELECT, GenConstants.HTML_RADIO, GenConstants.HTML_CHECKBOX })) {
dicts.add("'" + column.getDictType() + "'");
}
}
diff --git a/ruoyi/src/main/java/com/ruoyi/oss/constant/CloudConstant.java b/ruoyi/src/main/java/com/ruoyi/oss/constant/CloudConstant.java
deleted file mode 100644
index 7bba1f4db..000000000
--- a/ruoyi/src/main/java/com/ruoyi/oss/constant/CloudConstant.java
+++ /dev/null
@@ -1,38 +0,0 @@
-package com.ruoyi.oss.constant;
-
-import java.util.Arrays;
-import java.util.List;
-
-/**
- * 对象存储常量
- *
- * @author Lion Li
- */
-public class CloudConstant {
-
- /**
- * OSS模块KEY
- */
- public static final String SYS_OSS_KEY = "sys_oss:";
-
- /**
- * 对象存储配置KEY
- */
- public static final String CLOUD_STORAGE_CONFIG_KEY = "CloudStorageConfig";
-
- /**
- * 缓存配置KEY
- */
- public static final String CACHE_CONFIG_KEY = SYS_OSS_KEY + CLOUD_STORAGE_CONFIG_KEY;
-
- /**
- * 预览列表资源开关Key
- */
- public static final String PEREVIEW_LIST_RESOURCE_KEY = "sys.oss.previewListResource";
-
- /**
- * 系统数据ids
- */
- public static final List SYSTEM_DATA_IDS = Arrays.asList(1, 2, 3, 4);
-
-}
diff --git a/ruoyi/src/main/java/com/ruoyi/oss/enumd/CloudServiceEnumd.java b/ruoyi/src/main/java/com/ruoyi/oss/enumd/CloudServiceEnumd.java
deleted file mode 100644
index ac8ad8184..000000000
--- a/ruoyi/src/main/java/com/ruoyi/oss/enumd/CloudServiceEnumd.java
+++ /dev/null
@@ -1,63 +0,0 @@
-package com.ruoyi.oss.enumd;
-
-import com.ruoyi.common.utils.StringUtils;
-import com.ruoyi.oss.service.impl.AliyunCloudStorageStrategy;
-import com.ruoyi.oss.service.impl.MinioCloudStorageStrategy;
-import com.ruoyi.oss.service.impl.QcloudCloudStorageStrategy;
-import com.ruoyi.oss.service.impl.QiniuCloudStorageStrategy;
-import lombok.AllArgsConstructor;
-import lombok.Getter;
-
-/**
- * 对象存储服务商枚举
- *
- * @author Lion Li
- */
-@Getter
-@AllArgsConstructor
-public enum CloudServiceEnumd {
-
- /**
- * 七牛云
- */
- QINIU("qiniu", QiniuCloudStorageStrategy.class),
-
- /**
- * 阿里云
- */
- ALIYUN("aliyun", AliyunCloudStorageStrategy.class),
-
- /**
- * 腾讯云
- */
- QCLOUD("qcloud", QcloudCloudStorageStrategy.class),
-
- /**
- * minio
- */
- MINIO("minio", MinioCloudStorageStrategy.class);
-
- private final String value;
-
- private final Class> serviceClass;
-
- public static Class> getServiceClass(String value) {
- for (CloudServiceEnumd clazz : values()) {
- if (clazz.getValue().equals(value)) {
- return clazz.getServiceClass();
- }
- }
- return null;
- }
-
- public static String getServiceName(String value) {
- for (CloudServiceEnumd clazz : values()) {
- if (clazz.getValue().equals(value)) {
- return StringUtils.uncapitalize(clazz.getServiceClass().getSimpleName());
- }
- }
- return null;
- }
-
-
-}
diff --git a/ruoyi/src/main/java/com/ruoyi/oss/factory/OssFactory.java b/ruoyi/src/main/java/com/ruoyi/oss/factory/OssFactory.java
index ecb269dd7..169159602 100644
--- a/ruoyi/src/main/java/com/ruoyi/oss/factory/OssFactory.java
+++ b/ruoyi/src/main/java/com/ruoyi/oss/factory/OssFactory.java
@@ -1,16 +1,15 @@
package com.ruoyi.oss.factory;
-import cn.hutool.core.convert.Convert;
import com.ruoyi.common.utils.JsonUtils;
import com.ruoyi.common.utils.RedisUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.reflect.ReflectUtils;
-import com.ruoyi.oss.constant.CloudConstant;
-import com.ruoyi.oss.enumd.CloudServiceEnumd;
+import com.ruoyi.oss.constant.OssConstant;
+import com.ruoyi.oss.enumd.OssEnumd;
import com.ruoyi.oss.exception.OssException;
-import com.ruoyi.oss.properties.CloudStorageProperties;
-import com.ruoyi.oss.service.ICloudStorageStrategy;
-import com.ruoyi.oss.service.abstractd.AbstractCloudStorageStrategy;
+import com.ruoyi.oss.properties.OssProperties;
+import com.ruoyi.oss.service.IOssStrategy;
+import com.ruoyi.oss.service.abstractd.AbstractOssStrategy;
import lombok.extern.slf4j.Slf4j;
import java.util.Map;
@@ -24,24 +23,31 @@ import java.util.concurrent.ConcurrentHashMap;
@Slf4j
public class OssFactory {
- static {
- RedisUtils.subscribe(CloudConstant.CACHE_CONFIG_KEY, String.class, msg -> {
- refreshService(msg);
- log.info("订阅刷新OSS配置 => " + msg);
- });
- }
-
/**
* 服务实例缓存
*/
- private static final Map SERVICES = new ConcurrentHashMap<>();
+ private static final Map SERVICES = new ConcurrentHashMap<>();
+
+ /**
+ * 初始化工厂
+ */
+ public static void init() {
+ log.info("初始化OSS工厂");
+ RedisUtils.subscribe(OssConstant.CACHE_CONFIG_KEY, String.class, type -> {
+ // 没有的实例不处理
+ if (SERVICES.containsKey(type)) {
+ refreshService(type);
+ log.info("订阅刷新OSS配置 => " + type);
+ }
+ });
+ }
/**
* 获取默认实例
*/
- public static ICloudStorageStrategy instance() {
+ public static IOssStrategy instance() {
// 获取redis 默认类型
- String type = Convert.toStr(RedisUtils.getCacheObject(CloudConstant.CACHE_CONFIG_KEY));
+ String type = RedisUtils.getCacheObject(OssConstant.CACHE_CONFIG_KEY);
if (StringUtils.isEmpty(type)) {
throw new OssException("文件存储服务类型无法找到!");
}
@@ -51,8 +57,8 @@ public class OssFactory {
/**
* 根据类型获取实例
*/
- public static ICloudStorageStrategy instance(String type) {
- ICloudStorageStrategy service = SERVICES.get(type);
+ public static IOssStrategy instance(String type) {
+ IOssStrategy service = SERVICES.get(type);
if (service == null) {
refreshService(type);
service = SERVICES.get(type);
@@ -61,14 +67,14 @@ public class OssFactory {
}
private static void refreshService(String type) {
- Object json = RedisUtils.getCacheObject(CloudConstant.SYS_OSS_KEY + type);
- CloudStorageProperties properties = JsonUtils.parseObject(json.toString(), CloudStorageProperties.class);
+ Object json = RedisUtils.getCacheObject(OssConstant.SYS_OSS_KEY + type);
+ OssProperties properties = JsonUtils.parseObject(json.toString(), OssProperties.class);
if (properties == null) {
throw new OssException("系统异常, '" + type + "'配置信息不存在!");
}
// 获取redis配置信息 创建对象 并缓存
- ICloudStorageStrategy service = (ICloudStorageStrategy) ReflectUtils.newInstance(CloudServiceEnumd.getServiceClass(type));
- ((AbstractCloudStorageStrategy)service).init(properties);
+ IOssStrategy service = (IOssStrategy) ReflectUtils.newInstance(OssEnumd.getServiceClass(type));
+ ((AbstractOssStrategy)service).init(properties);
SERVICES.put(type, service);
}
diff --git a/ruoyi/src/main/java/com/ruoyi/oss/properties/CloudStorageProperties.java b/ruoyi/src/main/java/com/ruoyi/oss/properties/CloudStorageProperties.java
deleted file mode 100644
index 9d3f15afb..000000000
--- a/ruoyi/src/main/java/com/ruoyi/oss/properties/CloudStorageProperties.java
+++ /dev/null
@@ -1,55 +0,0 @@
-package com.ruoyi.oss.properties;
-
-import lombok.Data;
-
-import java.util.Date;
-
-/**
- * OSS对象存储 配置属性
- *
- * @author Lion Li
- */
-@Data
-public class CloudStorageProperties {
-
- /**
- * 域名
- */
- private String endpoint;
-
- /**
- * 前缀
- */
- private String prefix;
-
- /**
- * ACCESS_KEY
- */
- private String accessKey;
-
- /**
- * SECRET_KEY
- */
- private String secretKey;
-
- /**
- * 存储空间名
- */
- private String bucketName;
-
- /**
- * 存储区域
- */
- private String region;
-
- /**
- * 是否https(Y=是,N=否)
- */
- private String isHttps;
-
- /**
- * 更新时间
- */
- private Date updateTime;
-
-}
diff --git a/ruoyi/src/main/java/com/ruoyi/oss/service/ICloudStorageStrategy.java b/ruoyi/src/main/java/com/ruoyi/oss/service/ICloudStorageStrategy.java
deleted file mode 100644
index 96ea53992..000000000
--- a/ruoyi/src/main/java/com/ruoyi/oss/service/ICloudStorageStrategy.java
+++ /dev/null
@@ -1,74 +0,0 @@
-package com.ruoyi.oss.service;
-
-import com.ruoyi.oss.entity.UploadResult;
-
-import java.io.InputStream;
-
-/**
- * 对象存储策略
- *
- * @author Lion Li
- */
-public interface ICloudStorageStrategy {
-
- void createBucket();
-
- /**
- * 获取服务商类型
- */
- String getServiceType();
-
- /**
- * 文件路径
- *
- * @param prefix 前缀
- * @param suffix 后缀
- * @return 返回上传路径
- */
- String getPath(String prefix, String suffix);
-
- /**
- * 文件上传
- *
- * @param data 文件字节数组
- * @param path 文件路径,包含文件名
- * @return 返回http地址
- */
- UploadResult upload(byte[] data, String path, String contentType);
-
- /**
- * 文件删除
- *
- * @param path 文件路径,包含文件名
- */
- void delete(String path);
-
- /**
- * 文件上传
- *
- * @param data 文件字节数组
- * @param suffix 后缀
- * @return 返回http地址
- */
- UploadResult uploadSuffix(byte[] data, String suffix, String contentType);
-
- /**
- * 文件上传
- *
- * @param inputStream 字节流
- * @param path 文件路径,包含文件名
- * @return 返回http地址
- */
- UploadResult upload(InputStream inputStream, String path, String contentType);
-
- /**
- * 文件上传
- *
- * @param inputStream 字节流
- * @param suffix 后缀
- * @return 返回http地址
- */
- UploadResult uploadSuffix(InputStream inputStream, String suffix, String contentType);
-
- String getEndpointLink();
-}
diff --git a/ruoyi/src/main/java/com/ruoyi/oss/service/abstractd/AbstractCloudStorageStrategy.java b/ruoyi/src/main/java/com/ruoyi/oss/service/abstractd/AbstractCloudStorageStrategy.java
deleted file mode 100644
index 8f5e9625d..000000000
--- a/ruoyi/src/main/java/com/ruoyi/oss/service/abstractd/AbstractCloudStorageStrategy.java
+++ /dev/null
@@ -1,62 +0,0 @@
-package com.ruoyi.oss.service.abstractd;
-
-import cn.hutool.core.io.IoUtil;
-import cn.hutool.core.util.IdUtil;
-import com.ruoyi.common.utils.DateUtils;
-import com.ruoyi.common.utils.StringUtils;
-import com.ruoyi.oss.entity.UploadResult;
-import com.ruoyi.oss.properties.CloudStorageProperties;
-import com.ruoyi.oss.service.ICloudStorageStrategy;
-
-import java.io.InputStream;
-
-/**
- * 对象存储策略(支持七牛、阿里云、腾讯云、minio)
- *
- * @author Lion Li
- */
-public abstract class AbstractCloudStorageStrategy implements ICloudStorageStrategy {
-
- protected CloudStorageProperties properties;
-
- public abstract void init(CloudStorageProperties properties);
-
- @Override
- public abstract void createBucket();
-
- @Override
- public abstract String getServiceType();
-
- @Override
- public String getPath(String prefix, String suffix) {
- // 生成uuid
- String uuid = IdUtil.fastSimpleUUID();
- // 文件路径
- String path = DateUtils.datePath() + "/" + uuid;
- if (StringUtils.isNotBlank(prefix)) {
- path = prefix + "/" + path;
- }
- return path + suffix;
- }
-
- @Override
- public abstract UploadResult upload(byte[] data, String path, String contentType);
-
- @Override
- public abstract void delete(String path);
-
- @Override
- public UploadResult upload(InputStream inputStream, String path, String contentType) {
- byte[] data = IoUtil.readBytes(inputStream);
- return this.upload(data, path, contentType);
- }
-
- @Override
- public abstract UploadResult uploadSuffix(byte[] data, String suffix, String contentType);
-
- @Override
- public abstract UploadResult uploadSuffix(InputStream inputStream, String suffix, String contentType);
-
- @Override
- public abstract String getEndpointLink();
-}
diff --git a/ruoyi/src/main/java/com/ruoyi/oss/service/impl/AliyunCloudStorageStrategy.java b/ruoyi/src/main/java/com/ruoyi/oss/service/impl/AliyunCloudStorageStrategy.java
deleted file mode 100644
index 04ee67500..000000000
--- a/ruoyi/src/main/java/com/ruoyi/oss/service/impl/AliyunCloudStorageStrategy.java
+++ /dev/null
@@ -1,113 +0,0 @@
-package com.ruoyi.oss.service.impl;
-
-import com.aliyun.oss.ClientConfiguration;
-import com.aliyun.oss.OSSClient;
-import com.aliyun.oss.common.auth.DefaultCredentialProvider;
-import com.aliyun.oss.model.CannedAccessControlList;
-import com.aliyun.oss.model.CreateBucketRequest;
-import com.aliyun.oss.model.ObjectMetadata;
-import com.aliyun.oss.model.PutObjectRequest;
-import com.ruoyi.common.utils.StringUtils;
-import com.ruoyi.oss.entity.UploadResult;
-import com.ruoyi.oss.enumd.CloudServiceEnumd;
-import com.ruoyi.oss.exception.OssException;
-import com.ruoyi.oss.properties.CloudStorageProperties;
-import com.ruoyi.oss.service.abstractd.AbstractCloudStorageStrategy;
-
-import java.io.ByteArrayInputStream;
-import java.io.InputStream;
-
-/**
- * 阿里云存储策略
- *
- * @author Lion Li
- */
-public class AliyunCloudStorageStrategy extends AbstractCloudStorageStrategy {
-
- private OSSClient client;
-
- @Override
- public void init(CloudStorageProperties cloudStorageProperties) {
- properties = cloudStorageProperties;
- try {
- ClientConfiguration configuration = new ClientConfiguration();
- DefaultCredentialProvider credentialProvider = new DefaultCredentialProvider(
- properties.getAccessKey(), properties.getSecretKey());
- client = new OSSClient(properties.getEndpoint(), credentialProvider, configuration);
- createBucket();
- } catch (Exception e) {
- throw new OssException("阿里云存储配置错误! 请检查系统配置:[" + e.getMessage() + "]");
- }
- }
-
- @Override
- public void createBucket() {
- try {
- String bucketName = properties.getBucketName();
- if (client.doesBucketExist(bucketName)) {
- return;
- }
- CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
- createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
- client.createBucket(createBucketRequest);
- } catch (Exception e) {
- throw new OssException("创建Bucket失败, 请核对阿里云配置信息:[" + e.getMessage() + "]");
- }
- }
-
- @Override
- public String getServiceType() {
- return CloudServiceEnumd.ALIYUN.getValue();
- }
-
- @Override
- public UploadResult upload(byte[] data, String path, String contentType) {
- return upload(new ByteArrayInputStream(data), path, contentType);
- }
-
- @Override
- public UploadResult upload(InputStream inputStream, String path, String contentType) {
- try {
- ObjectMetadata metadata = new ObjectMetadata();
- metadata.setContentType(contentType);
- client.putObject(new PutObjectRequest(properties.getBucketName(), path, inputStream, metadata));
- } catch (Exception e) {
- throw new OssException("上传文件失败,请检查阿里云配置信息:[" + e.getMessage() + "]");
- }
- return new UploadResult().setUrl(getEndpointLink() + "/" + path).setFilename(path);
- }
-
- @Override
- public void delete(String path) {
- path = path.replace(getEndpointLink() + "/", "");
- try {
- client.deleteObject(properties.getBucketName(), path);
- } catch (Exception e) {
- throw new OssException("上传文件失败,请检查阿里云配置信息:[" + e.getMessage() + "]");
- }
- }
-
- @Override
- public UploadResult uploadSuffix(byte[] data, String suffix, String contentType) {
- return upload(data, getPath(properties.getPrefix(), suffix), contentType);
- }
-
- @Override
- public UploadResult uploadSuffix(InputStream inputStream, String suffix, String contentType) {
- return upload(inputStream, getPath(properties.getPrefix(), suffix), contentType);
- }
-
- @Override
- public String getEndpointLink() {
- String endpoint = properties.getEndpoint();
- StringBuilder sb = new StringBuilder(endpoint);
- if (StringUtils.containsAnyIgnoreCase(endpoint, "http://")) {
- sb.insert(7, properties.getBucketName() + ".");
- } else if (StringUtils.containsAnyIgnoreCase(endpoint, "https://")) {
- sb.insert(8, properties.getBucketName() + ".");
- } else {
- throw new OssException("Endpoint配置错误");
- }
- return sb.toString();
- }
-}
diff --git a/ruoyi/src/main/java/com/ruoyi/oss/service/impl/MinioCloudStorageStrategy.java b/ruoyi/src/main/java/com/ruoyi/oss/service/impl/MinioCloudStorageStrategy.java
deleted file mode 100644
index 3bbf187c9..000000000
--- a/ruoyi/src/main/java/com/ruoyi/oss/service/impl/MinioCloudStorageStrategy.java
+++ /dev/null
@@ -1,181 +0,0 @@
-package com.ruoyi.oss.service.impl;
-
-import com.ruoyi.common.utils.StringUtils;
-import com.ruoyi.oss.entity.UploadResult;
-import com.ruoyi.oss.enumd.CloudServiceEnumd;
-import com.ruoyi.oss.enumd.PolicyType;
-import com.ruoyi.oss.exception.OssException;
-import com.ruoyi.oss.properties.CloudStorageProperties;
-import com.ruoyi.oss.service.abstractd.AbstractCloudStorageStrategy;
-import io.minio.*;
-import org.springframework.http.MediaType;
-
-import java.io.ByteArrayInputStream;
-import java.io.InputStream;
-
-/**
- * minio存储策略
- *
- * @author Lion Li
- */
-public class MinioCloudStorageStrategy extends AbstractCloudStorageStrategy {
-
- private MinioClient minioClient;
-
- @Override
- public void init(CloudStorageProperties cloudStorageProperties) {
- properties = cloudStorageProperties;
- try {
- minioClient = MinioClient.builder()
- .endpoint(properties.getEndpoint())
- .credentials(properties.getAccessKey(), properties.getSecretKey())
- .build();
- createBucket();
- } catch (Exception e) {
- throw new OssException("Minio存储配置错误! 请检查系统配置:[" + e.getMessage() + "]");
- }
- }
-
- @Override
- public void createBucket() {
- try {
- String bucketName = properties.getBucketName();
- boolean exists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
- if (exists) {
- return;
- }
- // 不存在就创建桶
- minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
- minioClient.setBucketPolicy(SetBucketPolicyArgs.builder()
- .bucket(bucketName)
- .config(getPolicy(bucketName, PolicyType.READ))
- .build());
- } catch (Exception e) {
- throw new OssException("创建Bucket失败, 请核对Minio配置信息:[" + e.getMessage() + "]");
- }
- }
-
- @Override
- public String getServiceType() {
- return CloudServiceEnumd.MINIO.getValue();
- }
-
- @Override
- public UploadResult upload(byte[] data, String path, String contentType) {
- return upload(new ByteArrayInputStream(data), path, contentType);
- }
-
- @Override
- public UploadResult upload(InputStream inputStream, String path, String contentType) {
- try {
- minioClient.putObject(PutObjectArgs.builder()
- .bucket(properties.getBucketName())
- .object(path)
- .contentType(StringUtils.blankToDefault(contentType, MediaType.APPLICATION_OCTET_STREAM_VALUE))
- .stream(inputStream, inputStream.available(), -1)
- .build());
- } catch (Exception e) {
- throw new OssException("上传文件失败,请核对Minio配置信息:[" + e.getMessage() + "]");
- }
- return new UploadResult().setUrl(getEndpointLink() + "/" + path).setFilename(path);
- }
-
- @Override
- public void delete(String path) {
- path = path.replace(getEndpointLink() + "/", "");
- try {
- minioClient.removeObject(RemoveObjectArgs.builder()
- .bucket(properties.getBucketName())
- .object(path)
- .build());
- } catch (Exception e) {
- throw new OssException(e.getMessage());
- }
- }
-
- @Override
- public UploadResult uploadSuffix(byte[] data, String suffix, String contentType) {
- return upload(data, getPath(properties.getPrefix(), suffix), contentType);
- }
-
- @Override
- public UploadResult uploadSuffix(InputStream inputStream, String suffix, String contentType) {
- return upload(inputStream, getPath(properties.getPrefix(), suffix), contentType);
- }
-
- @Override
- public String getEndpointLink() {
- return properties.getEndpoint() + "/" + properties.getBucketName();
- }
-
- private String getPolicy(String bucketName, PolicyType policyType) {
- StringBuilder builder = new StringBuilder();
- builder.append("{\n");
- builder.append(" \"Statement\": [\n");
- builder.append(" {\n");
- builder.append(" \"Action\": [\n");
- if (policyType == PolicyType.WRITE) {
- builder.append(" \"s3:GetBucketLocation\",\n");
- builder.append(" \"s3:ListBucketMultipartUploads\"\n");
- } else if (policyType == PolicyType.READ_WRITE) {
- builder.append(" \"s3:GetBucketLocation\",\n");
- builder.append(" \"s3:ListBucket\",\n");
- builder.append(" \"s3:ListBucketMultipartUploads\"\n");
- } else {
- builder.append(" \"s3:GetBucketLocation\"\n");
- }
- builder.append(" ],\n");
- builder.append(" \"Effect\": \"Allow\",\n");
- builder.append(" \"Principal\": \"*\",\n");
- builder.append(" \"Resource\": \"arn:aws:s3:::");
- builder.append(bucketName);
- builder.append("\"\n");
- builder.append(" },\n");
- if (PolicyType.READ.equals(policyType)) {
- builder.append(" {\n");
- builder.append(" \"Action\": [\n");
- builder.append(" \"s3:ListBucket\"\n");
- builder.append(" ],\n");
- builder.append(" \"Effect\": \"Deny\",\n");
- builder.append(" \"Principal\": \"*\",\n");
- builder.append(" \"Resource\": \"arn:aws:s3:::");
- builder.append(bucketName);
- builder.append("\"\n");
- builder.append(" },\n");
- }
- builder.append(" {\n");
- builder.append(" \"Action\": ");
- switch (policyType) {
- case WRITE:
- builder.append("[\n");
- builder.append(" \"s3:AbortMultipartUpload\",\n");
- builder.append(" \"s3:DeleteObject\",\n");
- builder.append(" \"s3:ListMultipartUploadParts\",\n");
- builder.append(" \"s3:PutObject\"\n");
- builder.append(" ],\n");
- break;
- case READ_WRITE:
- builder.append("[\n");
- builder.append(" \"s3:AbortMultipartUpload\",\n");
- builder.append(" \"s3:DeleteObject\",\n");
- builder.append(" \"s3:GetObject\",\n");
- builder.append(" \"s3:ListMultipartUploadParts\",\n");
- builder.append(" \"s3:PutObject\"\n");
- builder.append(" ],\n");
- break;
- default:
- builder.append("\"s3:GetObject\",\n");
- break;
- }
- builder.append(" \"Effect\": \"Allow\",\n");
- builder.append(" \"Principal\": \"*\",\n");
- builder.append(" \"Resource\": \"arn:aws:s3:::");
- builder.append(bucketName);
- builder.append("/*\"\n");
- builder.append(" }\n");
- builder.append(" ],\n");
- builder.append(" \"Version\": \"2012-10-17\"\n");
- builder.append("}\n");
- return builder.toString();
- }
-}
diff --git a/ruoyi/src/main/java/com/ruoyi/oss/service/impl/QcloudCloudStorageStrategy.java b/ruoyi/src/main/java/com/ruoyi/oss/service/impl/QcloudCloudStorageStrategy.java
deleted file mode 100644
index 9bd366e0d..000000000
--- a/ruoyi/src/main/java/com/ruoyi/oss/service/impl/QcloudCloudStorageStrategy.java
+++ /dev/null
@@ -1,121 +0,0 @@
-package com.ruoyi.oss.service.impl;
-
-import com.qcloud.cos.COSClient;
-import com.qcloud.cos.ClientConfig;
-import com.qcloud.cos.auth.BasicCOSCredentials;
-import com.qcloud.cos.auth.COSCredentials;
-import com.qcloud.cos.http.HttpProtocol;
-import com.qcloud.cos.model.*;
-import com.qcloud.cos.region.Region;
-import com.ruoyi.common.utils.StringUtils;
-import com.ruoyi.oss.entity.UploadResult;
-import com.ruoyi.oss.enumd.CloudServiceEnumd;
-import com.ruoyi.oss.exception.OssException;
-import com.ruoyi.oss.properties.CloudStorageProperties;
-import com.ruoyi.oss.service.abstractd.AbstractCloudStorageStrategy;
-
-import java.io.ByteArrayInputStream;
-import java.io.InputStream;
-
-/**
- * 腾讯云存储策略
- *
- * @author Lion Li
- */
-public class QcloudCloudStorageStrategy extends AbstractCloudStorageStrategy {
-
- private COSClient client;
-
- @Override
- public void init(CloudStorageProperties cloudStorageProperties) {
- properties = cloudStorageProperties;
- try {
- COSCredentials credentials = new BasicCOSCredentials(
- properties.getAccessKey(), properties.getSecretKey());
- // 初始化客户端配置
- ClientConfig clientConfig = new ClientConfig();
- // 设置bucket所在的区域,华南:gz 华北:tj 华东:sh
- clientConfig.setRegion(new Region(properties.getRegion()));
- if ("Y".equals(properties.getIsHttps())) {
- clientConfig.setHttpProtocol(HttpProtocol.https);
- } else {
- clientConfig.setHttpProtocol(HttpProtocol.http);
- }
- client = new COSClient(credentials, clientConfig);
- createBucket();
- } catch (Exception e) {
- throw new OssException("腾讯云存储配置错误! 请检查系统配置:[" + e.getMessage() + "]");
- }
- }
-
- @Override
- public void createBucket() {
- try {
- String bucketName = properties.getBucketName();
- if (client.doesBucketExist(bucketName)) {
- return;
- }
- CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
- createBucketRequest.setCannedAcl(CannedAccessControlList.PublicRead);
- client.createBucket(createBucketRequest);
- } catch (Exception e) {
- throw new OssException("创建Bucket失败, 请核对腾讯云配置信息:[" + e.getMessage() + "]");
- }
- }
-
- @Override
- public String getServiceType() {
- return CloudServiceEnumd.QCLOUD.getValue();
- }
-
- @Override
- public UploadResult upload(byte[] data, String path, String contentType) {
- return upload(new ByteArrayInputStream(data), path, contentType);
- }
-
- @Override
- public UploadResult upload(InputStream inputStream, String path, String contentType) {
- try {
- ObjectMetadata metadata = new ObjectMetadata();
- metadata.setContentType(contentType);
- client.putObject(new PutObjectRequest(properties.getBucketName(), path, inputStream, metadata));
- } catch (Exception e) {
- throw new OssException("上传文件失败,请检查腾讯云配置信息:[" + e.getMessage() + "]");
- }
- return new UploadResult().setUrl(getEndpointLink() + "/" + path).setFilename(path);
- }
-
- @Override
- public void delete(String path) {
- path = path.replace(getEndpointLink() + "/", "");
- try {
- client.deleteObject(new DeleteObjectRequest(properties.getBucketName(), path));
- } catch (Exception e) {
- throw new OssException("上传文件失败,请检腾讯云查配置信息:[" + e.getMessage() + "]");
- }
- }
-
- @Override
- public UploadResult uploadSuffix(byte[] data, String suffix, String contentType) {
- return upload(data, getPath(properties.getPrefix(), suffix), contentType);
- }
-
- @Override
- public UploadResult uploadSuffix(InputStream inputStream, String suffix, String contentType) {
- return upload(inputStream, getPath(properties.getPrefix(), suffix), contentType);
- }
-
- @Override
- public String getEndpointLink() {
- String endpoint = properties.getEndpoint();
- StringBuilder sb = new StringBuilder(endpoint);
- if (StringUtils.containsAnyIgnoreCase(endpoint, "http://")) {
- sb.insert(7, properties.getBucketName() + ".");
- } else if (StringUtils.containsAnyIgnoreCase(endpoint, "https://")) {
- sb.insert(8, properties.getBucketName() + ".");
- } else {
- throw new OssException("Endpoint配置错误");
- }
- return sb.toString();
- }
-}
diff --git a/ruoyi/src/main/java/com/ruoyi/oss/service/impl/QiniuCloudStorageStrategy.java b/ruoyi/src/main/java/com/ruoyi/oss/service/impl/QiniuCloudStorageStrategy.java
deleted file mode 100644
index e9b8dc096..000000000
--- a/ruoyi/src/main/java/com/ruoyi/oss/service/impl/QiniuCloudStorageStrategy.java
+++ /dev/null
@@ -1,127 +0,0 @@
-package com.ruoyi.oss.service.impl;
-
-import cn.hutool.core.util.ArrayUtil;
-import com.qiniu.http.Response;
-import com.qiniu.storage.BucketManager;
-import com.qiniu.storage.Configuration;
-import com.qiniu.storage.Region;
-import com.qiniu.storage.UploadManager;
-import com.qiniu.util.Auth;
-import com.ruoyi.oss.entity.UploadResult;
-import com.ruoyi.oss.enumd.CloudServiceEnumd;
-import com.ruoyi.oss.exception.OssException;
-import com.ruoyi.oss.properties.CloudStorageProperties;
-import com.ruoyi.oss.service.abstractd.AbstractCloudStorageStrategy;
-
-import java.io.InputStream;
-
-/**
- * 七牛云存储策略
- *
- * @author Lion Li
- */
-public class QiniuCloudStorageStrategy extends AbstractCloudStorageStrategy {
-
- private UploadManager uploadManager;
- private BucketManager bucketManager;
- private String token;
-
- @Override
- public void init(CloudStorageProperties cloudStorageProperties) {
- properties = cloudStorageProperties;
- try {
- Configuration config = new Configuration(getRegion(properties.getRegion()));
- // https设置
- config.useHttpsDomains = false;
- config.useHttpsDomains = "Y".equals(properties.getIsHttps());
- uploadManager = new UploadManager(config);
- Auth auth = Auth.create(properties.getAccessKey(), properties.getSecretKey());
- String bucketName = properties.getBucketName();
- token = auth.uploadToken(bucketName);
- bucketManager = new BucketManager(auth, config);
-
- if (!ArrayUtil.contains(bucketManager.buckets(), bucketName)) {
- bucketManager.createBucket(bucketName, properties.getRegion());
- }
- } catch (Exception e) {
- throw new OssException("七牛云存储配置错误! 请检查系统配置:[" + e.getMessage() + "]");
- }
- }
-
- @Override
- public void createBucket() {
- try {
- String bucketName = properties.getBucketName();
- if (ArrayUtil.contains(bucketManager.buckets(), bucketName)) {
- return;
- }
- bucketManager.createBucket(bucketName, properties.getRegion());
- } catch (Exception e) {
- throw new OssException("创建Bucket失败, 请核对七牛云配置信息:[" + e.getMessage() + "]");
- }
- }
-
- @Override
- public String getServiceType() {
- return CloudServiceEnumd.QINIU.getValue();
- }
-
- @Override
- public UploadResult upload(byte[] data, String path, String contentType) {
- try {
- Response res = uploadManager.put(data, path, token, null, contentType, false);
- if (!res.isOK()) {
- throw new RuntimeException("上传七牛出错:" + res.toString());
- }
- } catch (Exception e) {
- throw new OssException("上传文件失败,请核对七牛配置信息:[" + e.getMessage() + "]");
- }
- return new UploadResult().setUrl(getEndpointLink() + "/" + path).setFilename(path);
- }
-
- @Override
- public void delete(String path) {
- try {
- path = path.replace(getEndpointLink() + "/", "");
- Response res = bucketManager.delete(properties.getBucketName(), path);
- if (!res.isOK()) {
- throw new RuntimeException("删除七牛文件出错:" + res.toString());
- }
- } catch (Exception e) {
- throw new OssException(e.getMessage());
- }
- }
-
- @Override
- public UploadResult uploadSuffix(byte[] data, String suffix, String contentType) {
- return upload(data, getPath(properties.getPrefix(), suffix), contentType);
- }
-
- @Override
- public UploadResult uploadSuffix(InputStream inputStream, String suffix, String contentType) {
- return upload(inputStream, getPath(properties.getPrefix(), suffix), contentType);
- }
-
- @Override
- public String getEndpointLink() {
- return properties.getEndpoint();
- }
-
- private Region getRegion(String region) {
- switch (region) {
- case "z0":
- return Region.region0();
- case "z1":
- return Region.region1();
- case "z2":
- return Region.region2();
- case "na0":
- return Region.regionNa0();
- case "as0":
- return Region.regionAs0();
- default:
- return Region.autoRegion();
- }
- }
-
-}
diff --git a/ruoyi/src/main/java/com/ruoyi/system/domain/vo/SysUserImportVo.java b/ruoyi/src/main/java/com/ruoyi/system/domain/vo/SysUserImportVo.java
index 16932ad68..d461332f2 100644
--- a/ruoyi/src/main/java/com/ruoyi/system/domain/vo/SysUserImportVo.java
+++ b/ruoyi/src/main/java/com/ruoyi/system/domain/vo/SysUserImportVo.java
@@ -67,7 +67,7 @@ public class SysUserImportVo implements Serializable {
* 帐号状态(0正常 1停用)
*/
@ExcelProperty(value = "帐号状态", converter = ExcelDictConvert.class)
- @ExcelDictFormat(dictType = "sys_common_status")
+ @ExcelDictFormat(dictType = "sys_normal_disable")
private String status;
}
diff --git a/ruoyi/src/main/java/com/ruoyi/system/mapper/SysMenuMapper.java b/ruoyi/src/main/java/com/ruoyi/system/mapper/SysMenuMapper.java
index 8b5dcd6b1..f1a018ff6 100644
--- a/ruoyi/src/main/java/com/ruoyi/system/mapper/SysMenuMapper.java
+++ b/ruoyi/src/main/java/com/ruoyi/system/mapper/SysMenuMapper.java
@@ -58,6 +58,6 @@ public interface SysMenuMapper extends BaseMapperPlus {
* @param menuCheckStrictly 菜单树选择项是否关联显示
* @return 选中菜单列表
*/
- List selectMenuListByRoleId(@Param("roleId") Long roleId, @Param("menuCheckStrictly") boolean menuCheckStrictly);
+ List selectMenuListByRoleId(@Param("roleId") Long roleId, @Param("menuCheckStrictly") boolean menuCheckStrictly);
}
diff --git a/ruoyi/src/main/java/com/ruoyi/system/service/ISysDeptService.java b/ruoyi/src/main/java/com/ruoyi/system/service/ISysDeptService.java
index ea6afa2e5..bd8c5ffbf 100644
--- a/ruoyi/src/main/java/com/ruoyi/system/service/ISysDeptService.java
+++ b/ruoyi/src/main/java/com/ruoyi/system/service/ISysDeptService.java
@@ -1,7 +1,7 @@
package com.ruoyi.system.service;
+import cn.hutool.core.lang.tree.Tree;
import com.baomidou.mybatisplus.extension.service.IService;
-import com.ruoyi.common.core.domain.TreeSelect;
import com.ruoyi.common.core.domain.entity.SysDept;
import java.util.List;
@@ -20,21 +20,13 @@ public interface ISysDeptService extends IService {
*/
List selectDeptList(SysDept dept);
- /**
- * 构建前端所需要树结构
- *
- * @param depts 部门列表
- * @return 树结构列表
- */
- List buildDeptTree(List depts);
-
/**
* 构建前端所需要下拉树结构
*
* @param depts 部门列表
* @return 下拉树结构列表
*/
- List buildDeptTreeSelect(List depts);
+ List> buildDeptTreeSelect(List depts);
/**
* 根据角色ID查询部门树信息
diff --git a/ruoyi/src/main/java/com/ruoyi/system/service/ISysMenuService.java b/ruoyi/src/main/java/com/ruoyi/system/service/ISysMenuService.java
index eea882e67..9424052d6 100644
--- a/ruoyi/src/main/java/com/ruoyi/system/service/ISysMenuService.java
+++ b/ruoyi/src/main/java/com/ruoyi/system/service/ISysMenuService.java
@@ -1,7 +1,7 @@
package com.ruoyi.system.service;
+import cn.hutool.core.lang.tree.Tree;
import com.baomidou.mybatisplus.extension.service.IService;
-import com.ruoyi.common.core.domain.TreeSelect;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.system.domain.vo.RouterVo;
@@ -54,7 +54,7 @@ public interface ISysMenuService extends IService {
* @param roleId 角色ID
* @return 选中菜单列表
*/
- List selectMenuListByRoleId(Long roleId);
+ List selectMenuListByRoleId(Long roleId);
/**
* 构建前端路由所需要的菜单
@@ -64,21 +64,13 @@ public interface ISysMenuService extends IService {
*/
List buildMenus(List menus);
- /**
- * 构建前端所需要树结构
- *
- * @param menus 菜单列表
- * @return 树结构列表
- */
- List buildMenuTree(List menus);
-
/**
* 构建前端所需要下拉树结构
*
* @param menus 菜单列表
* @return 下拉树结构列表
*/
- List buildMenuTreeSelect(List menus);
+ List> buildMenuTreeSelect(List menus);
/**
* 根据菜单ID查询信息
diff --git a/ruoyi/src/main/java/com/ruoyi/system/service/ISysOssConfigService.java b/ruoyi/src/main/java/com/ruoyi/system/service/ISysOssConfigService.java
index 759ec5b41..9d9fd5341 100644
--- a/ruoyi/src/main/java/com/ruoyi/system/service/ISysOssConfigService.java
+++ b/ruoyi/src/main/java/com/ruoyi/system/service/ISysOssConfigService.java
@@ -17,6 +17,11 @@ import java.util.Collection;
*/
public interface ISysOssConfigService extends IServicePlus {
+ /**
+ * 初始化OSS配置
+ */
+ void init();
+
/**
* 查询单个
*/
diff --git a/ruoyi/src/main/java/com/ruoyi/system/service/ISysUserService.java b/ruoyi/src/main/java/com/ruoyi/system/service/ISysUserService.java
index d6e8d9d3d..a901e0abe 100644
--- a/ruoyi/src/main/java/com/ruoyi/system/service/ISysUserService.java
+++ b/ruoyi/src/main/java/com/ruoyi/system/service/ISysUserService.java
@@ -3,6 +3,7 @@ package com.ruoyi.system.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
+import com.ruoyi.common.core.service.UserService;
import java.util.List;
@@ -11,7 +12,7 @@ import java.util.List;
*
* @author Lion Li
*/
-public interface ISysUserService extends IService {
+public interface ISysUserService extends IService, UserService {
TableDataInfo selectPageUserList(SysUser user);
@@ -46,6 +47,7 @@ public interface ISysUserService extends IService {
* @param userName 用户名
* @return 用户对象信息
*/
+ @Override
SysUser selectUserByUserName(String userName);
/**
@@ -54,6 +56,7 @@ public interface ISysUserService extends IService {
* @param userId 用户ID
* @return 用户对象信息
*/
+ @Override
SysUser selectUserById(Long userId);
/**
diff --git a/ruoyi/src/main/java/com/ruoyi/system/service/PermissionService.java b/ruoyi/src/main/java/com/ruoyi/system/service/PermissionService.java
index ce9af68dd..e41333391 100644
--- a/ruoyi/src/main/java/com/ruoyi/system/service/PermissionService.java
+++ b/ruoyi/src/main/java/com/ruoyi/system/service/PermissionService.java
@@ -1,9 +1,12 @@
package com.ruoyi.system.service;
import com.ruoyi.common.core.domain.entity.SysRole;
+import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
+import com.ruoyi.common.core.service.UserService;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
+import com.ruoyi.common.utils.spring.SpringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
@@ -91,10 +94,14 @@ public class PermissionService {
return false;
}
LoginUser loginUser = SecurityUtils.getLoginUser();
- if (StringUtils.isNull(loginUser) || CollectionUtils.isEmpty(loginUser.getUser().getRoles())) {
+ if (StringUtils.isNull(loginUser)) {
return false;
}
- for (SysRole sysRole : loginUser.getUser().getRoles()) {
+ SysUser sysUser = SpringUtils.getBean(UserService.class).selectUserById(loginUser.getUserId());
+ if (CollectionUtils.isEmpty(sysUser.getRoles())) {
+ return false;
+ }
+ for (SysRole sysRole : sysUser.getRoles()) {
String roleKey = sysRole.getRoleKey();
if (SUPER_ADMIN.equals(roleKey) || roleKey.equals(StringUtils.trim(role))) {
return true;
@@ -124,7 +131,11 @@ public class PermissionService {
return false;
}
LoginUser loginUser = SecurityUtils.getLoginUser();
- if (StringUtils.isNull(loginUser) || CollectionUtils.isEmpty(loginUser.getUser().getRoles())) {
+ if (StringUtils.isNull(loginUser)) {
+ return false;
+ }
+ SysUser sysUser = SpringUtils.getBean(UserService.class).selectUserById(loginUser.getUserId());
+ if (CollectionUtils.isEmpty(sysUser.getRoles())) {
return false;
}
for (String role : roles.split(ROLE_DELIMETER)) {
diff --git a/ruoyi/src/main/java/com/ruoyi/system/service/impl/SysConfigServiceImpl.java b/ruoyi/src/main/java/com/ruoyi/system/service/impl/SysConfigServiceImpl.java
index a01bcd141..bbd09a1d7 100644
--- a/ruoyi/src/main/java/com/ruoyi/system/service/impl/SysConfigServiceImpl.java
+++ b/ruoyi/src/main/java/com/ruoyi/system/service/impl/SysConfigServiceImpl.java
@@ -7,6 +7,7 @@ import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.mybatisplus.core.ServicePlusImpl;
import com.ruoyi.common.core.page.TableDataInfo;
+import com.ruoyi.common.core.service.ConfigService;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.PageUtils;
@@ -17,7 +18,6 @@ import com.ruoyi.system.mapper.SysConfigMapper;
import com.ruoyi.system.service.ISysConfigService;
import org.springframework.stereotype.Service;
-import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
@@ -29,29 +29,17 @@ import java.util.Map;
* @author Lion Li
*/
@Service
-public class SysConfigServiceImpl extends ServicePlusImpl implements ISysConfigService {
-
- /**
- * 项目启动时,初始化参数到缓存
- */
- @PostConstruct
- public void init() {
- loadingConfigCache();
- }
+public class SysConfigServiceImpl extends ServicePlusImpl implements ISysConfigService, ConfigService {
@Override
public TableDataInfo selectPageConfigList(SysConfig config) {
Map params = config.getParams();
LambdaQueryWrapper lqw = new LambdaQueryWrapper()
- .like(StringUtils.isNotBlank(config.getConfigName()), SysConfig::getConfigName, config.getConfigName())
- .eq(StringUtils.isNotBlank(config.getConfigType()), SysConfig::getConfigType, config.getConfigType())
- .like(StringUtils.isNotBlank(config.getConfigKey()), SysConfig::getConfigKey, config.getConfigKey())
- .apply(StringUtils.isNotEmpty(params.get("beginTime")),
- "date_format(create_time,'%y%m%d') >= date_format({0},'%y%m%d')",
- params.get("beginTime"))
- .apply(StringUtils.isNotEmpty(params.get("endTime")),
- "date_format(create_time,'%y%m%d') <= date_format({0},'%y%m%d')",
- params.get("endTime"));
+ .like(StringUtils.isNotBlank(config.getConfigName()), SysConfig::getConfigName, config.getConfigName())
+ .eq(StringUtils.isNotBlank(config.getConfigType()), SysConfig::getConfigType, config.getConfigType())
+ .like(StringUtils.isNotBlank(config.getConfigKey()), SysConfig::getConfigKey, config.getConfigKey())
+ .between(params.get("beginTime") != null && params.get("endTime") != null,
+ SysConfig::getCreateTime, params.get("beginTime"), params.get("endTime"));
return PageUtils.buildDataInfo(page(PageUtils.buildPage(), lqw));
}
@@ -75,12 +63,12 @@ public class SysConfigServiceImpl extends ServicePlusImpl()
- .eq(SysConfig::getConfigKey, configKey));
+ .eq(SysConfig::getConfigKey, configKey));
if (StringUtils.isNotNull(retConfig)) {
RedisUtils.setCacheObject(getCacheKey(configKey), retConfig.getConfigValue());
return retConfig.getConfigValue();
@@ -112,15 +100,11 @@ public class SysConfigServiceImpl extends ServicePlusImpl selectConfigList(SysConfig config) {
Map params = config.getParams();
LambdaQueryWrapper lqw = new LambdaQueryWrapper()
- .like(StringUtils.isNotBlank(config.getConfigName()), SysConfig::getConfigName, config.getConfigName())
- .eq(StringUtils.isNotBlank(config.getConfigType()), SysConfig::getConfigType, config.getConfigType())
- .like(StringUtils.isNotBlank(config.getConfigKey()), SysConfig::getConfigKey, config.getConfigKey())
- .apply(StringUtils.isNotEmpty(params.get("beginTime")),
- "date_format(create_time,'%y%m%d') >= date_format({0},'%y%m%d')",
- params.get("beginTime"))
- .apply(StringUtils.isNotEmpty(params.get("endTime")),
- "date_format(create_time,'%y%m%d') <= date_format({0},'%y%m%d')",
- params.get("endTime"));
+ .like(StringUtils.isNotBlank(config.getConfigName()), SysConfig::getConfigName, config.getConfigName())
+ .eq(StringUtils.isNotBlank(config.getConfigType()), SysConfig::getConfigType, config.getConfigType())
+ .like(StringUtils.isNotBlank(config.getConfigKey()), SysConfig::getConfigKey, config.getConfigKey())
+ .between(params.get("beginTime") != null && params.get("endTime") != null,
+ SysConfig::getCreateTime, params.get("beginTime"), params.get("endTime"));
return baseMapper.selectList(lqw);
}
@@ -217,6 +201,17 @@ public class SysConfigServiceImpl extends ServicePlusImpl buildDeptTree(List depts) {
- List returnList = new ArrayList();
- List tempList = new ArrayList();
- for (SysDept dept : depts) {
- tempList.add(dept.getDeptId());
- }
- for (SysDept dept : depts) {
- // 如果是顶级节点, 遍历该父节点的所有子节点
- if (!tempList.contains(dept.getParentId())) {
- recursionFn(depts, dept);
- returnList.add(dept);
- }
- }
- if (returnList.isEmpty()) {
- returnList = depts;
- }
- return returnList;
- }
-
/**
* 构建前端所需要下拉树结构
*
@@ -85,9 +58,12 @@ public class SysDeptServiceImpl extends ServicePlusImpl buildDeptTreeSelect(List depts) {
- List deptTrees = buildDeptTree(depts);
- return deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
+ public List> buildDeptTreeSelect(List depts) {
+ return TreeBuildUtils.build(depts, (dept, tree) ->
+ tree.setId(dept.getDeptId())
+ .setParentId(dept.getParentId())
+ .setName(dept.getDeptName())
+ .setWeight(dept.getOrderNum()));
}
/**
@@ -122,8 +98,8 @@ public class SysDeptServiceImpl extends ServicePlusImpl()
- .eq(SysDept::getStatus, 0)
- .apply("find_in_set({0}, ancestors)", deptId));
+ .eq(SysDept::getStatus, 0)
+ .apply("find_in_set({0}, ancestors)", deptId));
}
/**
@@ -135,8 +111,7 @@ public class SysDeptServiceImpl extends ServicePlusImpl()
- .eq(SysDept::getParentId, deptId)
- .last("limit 1"));
+ .eq(SysDept::getParentId, deptId));
return result > 0;
}
@@ -149,7 +124,7 @@ public class SysDeptServiceImpl extends ServicePlusImpl()
- .eq(SysUser::getDeptId, deptId));
+ .eq(SysUser::getDeptId, deptId));
return result > 0;
}
@@ -162,11 +137,11 @@ public class SysDeptServiceImpl extends ServicePlusImpl()
- .eq(SysDept::getDeptName, dept.getDeptName())
- .eq(SysDept::getParentId, dept.getParentId())
- .last("limit 1"));
- if (StringUtils.isNotNull(info) && info.getDeptId().longValue() != deptId.longValue()) {
+ long count = count(new LambdaQueryWrapper()
+ .eq(SysDept::getDeptName, dept.getDeptName())
+ .eq(SysDept::getParentId, dept.getParentId())
+ .ne(SysDept::getDeptId, deptId));
+ if (count > 0) {
return UserConstants.NOT_UNIQUE;
}
return UserConstants.UNIQUE;
@@ -224,7 +199,7 @@ public class SysDeptServiceImpl extends ServicePlusImpl()
- .set(SysDept::getStatus, "0")
- .in(SysDept::getDeptId, Arrays.asList(deptIds)));
+ .set(SysDept::getStatus, "0")
+ .in(SysDept::getDeptId, Arrays.asList(deptIds)));
}
/**
@@ -253,7 +228,7 @@ public class SysDeptServiceImpl extends ServicePlusImpl children = list(new LambdaQueryWrapper()
- .apply("find_in_set({0},ancestors)", deptId));
+ .apply("find_in_set({0},ancestors)", deptId));
for (SysDept child : children) {
child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
}
@@ -273,37 +248,4 @@ public class SysDeptServiceImpl extends ServicePlusImpl list, SysDept t) {
- // 得到子节点列表
- List childList = getChildList(list, t);
- t.setChildren(childList);
- for (SysDept tChild : childList) {
- if (hasChild(list, tChild)) {
- recursionFn(list, tChild);
- }
- }
- }
-
- /**
- * 得到子节点列表
- */
- private List getChildList(List list, SysDept t) {
- List tlist = new ArrayList();
- for (SysDept n : list) {
- if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getDeptId().longValue()) {
- tlist.add(n);
- }
- }
- return tlist;
- }
-
- /**
- * 判断是否有子节点
- */
- private boolean hasChild(List list, SysDept t) {
- return getChildList(list, t).size() > 0;
- }
}
diff --git a/ruoyi/src/main/java/com/ruoyi/system/service/impl/SysDictDataServiceImpl.java b/ruoyi/src/main/java/com/ruoyi/system/service/impl/SysDictDataServiceImpl.java
index 35908e3b1..d2ac2a02e 100644
--- a/ruoyi/src/main/java/com/ruoyi/system/service/impl/SysDictDataServiceImpl.java
+++ b/ruoyi/src/main/java/com/ruoyi/system/service/impl/SysDictDataServiceImpl.java
@@ -1,11 +1,12 @@
package com.ruoyi.system.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.mybatisplus.core.ServicePlusImpl;
import com.ruoyi.common.core.page.TableDataInfo;
-import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.PageUtils;
+import com.ruoyi.common.utils.RedisUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.mapper.SysDictDataMapper;
import com.ruoyi.system.service.ISysDictDataService;
@@ -85,7 +86,7 @@ public class SysDictDataServiceImpl extends ServicePlusImpl dictDatas = baseMapper.selectDictDataByType(data.getDictType());
- DictUtils.setDictCache(data.getDictType(), dictDatas);
+ RedisUtils.setCacheObject(getCacheKey(data.getDictType()), dictDatas);
}
}
@@ -100,7 +101,7 @@ public class SysDictDataServiceImpl extends ServicePlusImpl 0) {
List dictDatas = baseMapper.selectDictDataByType(data.getDictType());
- DictUtils.setDictCache(data.getDictType(), dictDatas);
+ RedisUtils.setCacheObject(getCacheKey(data.getDictType()), dictDatas);
}
return row;
}
@@ -116,8 +117,18 @@ public class SysDictDataServiceImpl extends ServicePlusImpl 0) {
List dictDatas = baseMapper.selectDictDataByType(data.getDictType());
- DictUtils.setDictCache(data.getDictType(), dictDatas);
+ RedisUtils.setCacheObject(getCacheKey(data.getDictType()), dictDatas);
}
return row;
}
+
+ /**
+ * 设置cache key
+ *
+ * @param configKey 参数键
+ * @return 缓存键key
+ */
+ String getCacheKey(String configKey) {
+ return Constants.SYS_DICT_KEY + configKey;
+ }
}
diff --git a/ruoyi/src/main/java/com/ruoyi/system/service/impl/SysDictTypeServiceImpl.java b/ruoyi/src/main/java/com/ruoyi/system/service/impl/SysDictTypeServiceImpl.java
index bb940c2b0..b520d4188 100644
--- a/ruoyi/src/main/java/com/ruoyi/system/service/impl/SysDictTypeServiceImpl.java
+++ b/ruoyi/src/main/java/com/ruoyi/system/service/impl/SysDictTypeServiceImpl.java
@@ -3,14 +3,16 @@ package com.ruoyi.system.service.impl;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
+import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysDictType;
import com.ruoyi.common.core.mybatisplus.core.ServicePlusImpl;
import com.ruoyi.common.core.page.TableDataInfo;
+import com.ruoyi.common.core.service.DictService;
import com.ruoyi.common.exception.ServiceException;
-import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.PageUtils;
+import com.ruoyi.common.utils.RedisUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.mapper.SysDictDataMapper;
import com.ruoyi.system.mapper.SysDictTypeMapper;
@@ -19,8 +21,8 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
-import javax.annotation.PostConstruct;
import java.util.Arrays;
+import java.util.Collection;
import java.util.List;
import java.util.Map;
@@ -30,32 +32,20 @@ import java.util.Map;
* @author Lion Li
*/
@Service
-public class SysDictTypeServiceImpl extends ServicePlusImpl implements ISysDictTypeService {
+public class SysDictTypeServiceImpl extends ServicePlusImpl implements ISysDictTypeService, DictService {
@Autowired
private SysDictDataMapper dictDataMapper;
- /**
- * 项目启动时,初始化字典到缓存
- */
- @PostConstruct
- public void init() {
- loadingDictCache();
- }
-
@Override
public TableDataInfo selectPageDictTypeList(SysDictType dictType) {
Map params = dictType.getParams();
LambdaQueryWrapper lqw = new LambdaQueryWrapper()
- .like(StringUtils.isNotBlank(dictType.getDictName()), SysDictType::getDictName, dictType.getDictName())
- .eq(StringUtils.isNotBlank(dictType.getStatus()), SysDictType::getStatus, dictType.getStatus())
- .like(StringUtils.isNotBlank(dictType.getDictType()), SysDictType::getDictType, dictType.getDictType())
- .apply(StringUtils.isNotEmpty(params.get("beginTime")),
- "date_format(create_time,'%y%m%d') >= date_format({0},'%y%m%d')",
- params.get("beginTime"))
- .apply(StringUtils.isNotEmpty(params.get("endTime")),
- "date_format(create_time,'%y%m%d') <= date_format({0},'%y%m%d')",
- params.get("endTime"));
+ .like(StringUtils.isNotBlank(dictType.getDictName()), SysDictType::getDictName, dictType.getDictName())
+ .eq(StringUtils.isNotBlank(dictType.getStatus()), SysDictType::getStatus, dictType.getStatus())
+ .like(StringUtils.isNotBlank(dictType.getDictType()), SysDictType::getDictType, dictType.getDictType())
+ .between(params.get("beginTime") != null && params.get("endTime") != null,
+ SysDictType::getCreateTime, params.get("beginTime"), params.get("endTime"));
return PageUtils.buildDataInfo(page(PageUtils.buildPage(), lqw));
}
@@ -69,15 +59,11 @@ public class SysDictTypeServiceImpl extends ServicePlusImpl selectDictTypeList(SysDictType dictType) {
Map params = dictType.getParams();
return list(new LambdaQueryWrapper()
- .like(StringUtils.isNotBlank(dictType.getDictName()), SysDictType::getDictName, dictType.getDictName())
- .eq(StringUtils.isNotBlank(dictType.getStatus()), SysDictType::getStatus, dictType.getStatus())
- .like(StringUtils.isNotBlank(dictType.getDictType()), SysDictType::getDictType, dictType.getDictType())
- .apply(StringUtils.isNotEmpty(params.get("beginTime")),
- "date_format(create_time,'%y%m%d') >= date_format({0},'%y%m%d')",
- params.get("beginTime"))
- .apply(StringUtils.isNotEmpty(params.get("endTime")),
- "date_format(create_time,'%y%m%d') <= date_format({0},'%y%m%d')",
- params.get("endTime")));
+ .like(StringUtils.isNotBlank(dictType.getDictName()), SysDictType::getDictName, dictType.getDictName())
+ .eq(StringUtils.isNotBlank(dictType.getStatus()), SysDictType::getStatus, dictType.getStatus())
+ .like(StringUtils.isNotBlank(dictType.getDictType()), SysDictType::getDictType, dictType.getDictType())
+ .between(params.get("beginTime") != null && params.get("endTime") != null,
+ SysDictType::getCreateTime, params.get("beginTime"), params.get("endTime")));
}
/**
@@ -98,13 +84,13 @@ public class SysDictTypeServiceImpl extends ServicePlusImpl selectDictDataByType(String dictType) {
- List dictDatas = DictUtils.getDictCache(dictType);
- if (CollUtil.isNotEmpty(dictDatas)) {
+ List dictDatas = RedisUtils.getCacheObject(getCacheKey(dictType));
+ if (StringUtils.isNotEmpty(dictDatas)) {
return dictDatas;
}
dictDatas = dictDataMapper.selectDictDataByType(dictType);
if (CollUtil.isNotEmpty(dictDatas)) {
- DictUtils.setDictCache(dictType, dictDatas);
+ RedisUtils.setCacheObject(getCacheKey(dictType), dictDatas);
return dictDatas;
}
return null;
@@ -143,10 +129,10 @@ public class SysDictTypeServiceImpl extends ServicePlusImpl()
- .eq(SysDictData::getDictType, dictType.getDictType())) > 0) {
+ .eq(SysDictData::getDictType, dictType.getDictType())) > 0) {
throw new ServiceException(String.format("%1$s已分配,不能删除", dictType.getDictName()));
}
- DictUtils.removeDictCache(dictType.getDictType());
+ RedisUtils.deleteObject(getCacheKey(dictType.getDictType()));
}
baseMapper.deleteBatchIds(Arrays.asList(dictIds));
}
@@ -159,7 +145,7 @@ public class SysDictTypeServiceImpl extends ServicePlusImpl dictTypeList = list();
for (SysDictType dictType : dictTypeList) {
List dictDatas = dictDataMapper.selectDictDataByType(dictType.getDictType());
- DictUtils.setDictCache(dictType.getDictType(), dictDatas);
+ RedisUtils.setCacheObject(getCacheKey(dictType.getDictType()), dictDatas);
}
}
@@ -168,7 +154,8 @@ public class SysDictTypeServiceImpl extends ServicePlusImpl keys = RedisUtils.keys(Constants.SYS_DICT_KEY + "*");
+ RedisUtils.deleteObject(keys);
}
/**
@@ -190,7 +177,7 @@ public class SysDictTypeServiceImpl extends ServicePlusImpl 0) {
- DictUtils.setDictCache(dict.getDictType(), null);
+ RedisUtils.setCacheObject(getCacheKey(dict.getDictType()), null);
}
return row;
}
@@ -206,12 +193,12 @@ public class SysDictTypeServiceImpl extends ServicePlusImpl()
- .set(SysDictData::getDictType, dict.getDictType())
- .eq(SysDictData::getDictType, oldDict.getDictType()));
+ .set(SysDictData::getDictType, dict.getDictType())
+ .eq(SysDictData::getDictType, oldDict.getDictType()));
int row = baseMapper.updateById(dict);
if (row > 0) {
List dictDatas = dictDataMapper.selectDictDataByType(dict.getDictType());
- DictUtils.setDictCache(dict.getDictType(), dictDatas);
+ RedisUtils.setCacheObject(getCacheKey(dict.getDictType()), dictDatas);
}
return row;
}
@@ -225,12 +212,86 @@ public class SysDictTypeServiceImpl extends ServicePlusImpl()
- .eq(SysDictType::getDictType, dict.getDictType())
- .last("limit 1"));
- if (StringUtils.isNotNull(dictType) && dictType.getDictId().longValue() != dictId.longValue()) {
+ long count = count(new LambdaQueryWrapper()
+ .eq(SysDictType::getDictType, dict.getDictType())
+ .ne(SysDictType::getDictId, dictId));
+ if (count > 0) {
return UserConstants.NOT_UNIQUE;
}
return UserConstants.UNIQUE;
}
+
+ /**
+ * 根据字典类型和字典值获取字典标签
+ *
+ * @param dictType 字典类型
+ * @param dictValue 字典值
+ * @param separator 分隔符
+ * @return 字典标签
+ */
+ @Override
+ public String getDictLabel(String dictType, String dictValue, String separator) {
+ StringBuilder propertyString = new StringBuilder();
+ List datas = selectDictDataByType(dictType);
+
+ if (StringUtils.containsAny(dictValue, separator) && CollUtil.isNotEmpty(datas)) {
+ for (SysDictData dict : datas) {
+ for (String value : dictValue.split(separator)) {
+ if (value.equals(dict.getDictValue())) {
+ propertyString.append(dict.getDictLabel() + separator);
+ break;
+ }
+ }
+ }
+ } else {
+ for (SysDictData dict : datas) {
+ if (dictValue.equals(dict.getDictValue())) {
+ return dict.getDictLabel();
+ }
+ }
+ }
+ return StringUtils.stripEnd(propertyString.toString(), separator);
+ }
+
+ /**
+ * 根据字典类型和字典标签获取字典值
+ *
+ * @param dictType 字典类型
+ * @param dictLabel 字典标签
+ * @param separator 分隔符
+ * @return 字典值
+ */
+ @Override
+ public String getDictValue(String dictType, String dictLabel, String separator) {
+ StringBuilder propertyString = new StringBuilder();
+ List datas = selectDictDataByType(dictType);
+
+ if (StringUtils.containsAny(dictLabel, separator) && CollUtil.isNotEmpty(datas)) {
+ for (SysDictData dict : datas) {
+ for (String label : dictLabel.split(separator)) {
+ if (label.equals(dict.getDictLabel())) {
+ propertyString.append(dict.getDictValue() + separator);
+ break;
+ }
+ }
+ }
+ } else {
+ for (SysDictData dict : datas) {
+ if (dictLabel.equals(dict.getDictLabel())) {
+ return dict.getDictValue();
+ }
+ }
+ }
+ return StringUtils.stripEnd(propertyString.toString(), separator);
+ }
+
+ /**
+ * 设置cache key
+ *
+ * @param configKey 参数键
+ * @return 缓存键key
+ */
+ String getCacheKey(String configKey) {
+ return Constants.SYS_DICT_KEY + configKey;
+ }
}
diff --git a/ruoyi/src/main/java/com/ruoyi/system/service/impl/SysLogininforServiceImpl.java b/ruoyi/src/main/java/com/ruoyi/system/service/impl/SysLogininforServiceImpl.java
index dda5b5d1b..0ce33be0f 100644
--- a/ruoyi/src/main/java/com/ruoyi/system/service/impl/SysLogininforServiceImpl.java
+++ b/ruoyi/src/main/java/com/ruoyi/system/service/impl/SysLogininforServiceImpl.java
@@ -90,16 +90,12 @@ public class SysLogininforServiceImpl extends ServicePlusImpl selectPageLogininforList(SysLogininfor logininfor) {
Map params = logininfor.getParams();
LambdaQueryWrapper lqw = new LambdaQueryWrapper()
- .like(StringUtils.isNotBlank(logininfor.getIpaddr()), SysLogininfor::getIpaddr, logininfor.getIpaddr())
- .eq(StringUtils.isNotBlank(logininfor.getStatus()), SysLogininfor::getStatus, logininfor.getStatus())
- .like(StringUtils.isNotBlank(logininfor.getUserName()), SysLogininfor::getUserName, logininfor.getUserName())
- .apply(StringUtils.isNotEmpty(params.get("beginTime")),
- "date_format(login_time,'%y%m%d') >= date_format({0},'%y%m%d')",
- params.get("beginTime"))
- .apply(StringUtils.isNotEmpty(params.get("endTime")),
- "date_format(login_time,'%y%m%d') <= date_format({0},'%y%m%d')",
- params.get("endTime"));
- return PageUtils.buildDataInfo(page(PageUtils.buildPage("info_id","desc"), lqw));
+ .like(StringUtils.isNotBlank(logininfor.getIpaddr()), SysLogininfor::getIpaddr, logininfor.getIpaddr())
+ .eq(StringUtils.isNotBlank(logininfor.getStatus()), SysLogininfor::getStatus, logininfor.getStatus())
+ .like(StringUtils.isNotBlank(logininfor.getUserName()), SysLogininfor::getUserName, logininfor.getUserName())
+ .between(params.get("beginTime") != null && params.get("endTime") != null,
+ SysLogininfor::getLoginTime, params.get("beginTime"), params.get("endTime"));
+ return PageUtils.buildDataInfo(page(PageUtils.buildPage("info_id", "desc"), lqw));
}
/**
@@ -123,16 +119,12 @@ public class SysLogininforServiceImpl extends ServicePlusImpl selectLogininforList(SysLogininfor logininfor) {
Map params = logininfor.getParams();
return list(new LambdaQueryWrapper()
- .like(StringUtils.isNotBlank(logininfor.getIpaddr()),SysLogininfor::getIpaddr,logininfor.getIpaddr())
- .eq(StringUtils.isNotBlank(logininfor.getStatus()),SysLogininfor::getStatus,logininfor.getStatus())
- .like(StringUtils.isNotBlank(logininfor.getUserName()),SysLogininfor::getUserName,logininfor.getUserName())
- .apply(StringUtils.isNotEmpty(params.get("beginTime")),
- "date_format(login_time,'%y%m%d') >= date_format({0},'%y%m%d')",
- params.get("beginTime"))
- .apply(StringUtils.isNotEmpty(params.get("endTime")),
- "date_format(login_time,'%y%m%d') <= date_format({0},'%y%m%d')",
- params.get("endTime"))
- .orderByDesc(SysLogininfor::getInfoId));
+ .like(StringUtils.isNotBlank(logininfor.getIpaddr()), SysLogininfor::getIpaddr, logininfor.getIpaddr())
+ .eq(StringUtils.isNotBlank(logininfor.getStatus()), SysLogininfor::getStatus, logininfor.getStatus())
+ .like(StringUtils.isNotBlank(logininfor.getUserName()), SysLogininfor::getUserName, logininfor.getUserName())
+ .between(params.get("beginTime") != null && params.get("endTime") != null,
+ SysLogininfor::getLoginTime, params.get("beginTime"), params.get("endTime"))
+ .orderByDesc(SysLogininfor::getInfoId));
}
/**
diff --git a/ruoyi/src/main/java/com/ruoyi/system/service/impl/SysMenuServiceImpl.java b/ruoyi/src/main/java/com/ruoyi/system/service/impl/SysMenuServiceImpl.java
index 643d304eb..9c3bfeb77 100644
--- a/ruoyi/src/main/java/com/ruoyi/system/service/impl/SysMenuServiceImpl.java
+++ b/ruoyi/src/main/java/com/ruoyi/system/service/impl/SysMenuServiceImpl.java
@@ -1,15 +1,16 @@
package com.ruoyi.system.service.impl;
+import cn.hutool.core.lang.tree.Tree;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
-import com.ruoyi.common.core.domain.TreeSelect;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.mybatisplus.core.ServicePlusImpl;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
+import com.ruoyi.common.utils.TreeBuildUtils;
import com.ruoyi.system.domain.SysRoleMenu;
import com.ruoyi.system.domain.vo.MetaVo;
import com.ruoyi.system.domain.vo.RouterVo;
@@ -21,7 +22,6 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;
-import java.util.stream.Collectors;
/**
* 菜单 业务层处理
@@ -60,11 +60,11 @@ public class SysMenuServiceImpl extends ServicePlusImpl()
- .like(StringUtils.isNotBlank(menu.getMenuName()), SysMenu::getMenuName, menu.getMenuName())
- .eq(StringUtils.isNotBlank(menu.getVisible()), SysMenu::getVisible, menu.getVisible())
- .eq(StringUtils.isNotBlank(menu.getStatus()), SysMenu::getStatus, menu.getStatus())
- .orderByAsc(SysMenu::getParentId)
- .orderByAsc(SysMenu::getOrderNum));
+ .like(StringUtils.isNotBlank(menu.getMenuName()), SysMenu::getMenuName, menu.getMenuName())
+ .eq(StringUtils.isNotBlank(menu.getVisible()), SysMenu::getVisible, menu.getVisible())
+ .eq(StringUtils.isNotBlank(menu.getStatus()), SysMenu::getStatus, menu.getStatus())
+ .orderByAsc(SysMenu::getParentId)
+ .orderByAsc(SysMenu::getOrderNum));
} else {
menu.getParams().put("userId", userId);
menuList = baseMapper.selectMenuListByUserId(menu);
@@ -114,7 +114,7 @@ public class SysMenuServiceImpl extends ServicePlusImpl selectMenuListByRoleId(Long roleId) {
+ public List selectMenuListByRoleId(Long roleId) {
SysRole role = roleMapper.selectById(roleId);
return baseMapper.selectMenuListByRoleId(roleId, role.isMenuCheckStrictly());
}
@@ -170,32 +170,6 @@ public class SysMenuServiceImpl extends ServicePlusImpl buildMenuTree(List menus) {
- List returnList = new ArrayList();
- List tempList = new ArrayList();
- for (SysMenu dept : menus) {
- tempList.add(dept.getMenuId());
- }
- for (SysMenu menu : menus) {
- // 如果是顶级节点, 遍历该父节点的所有子节点
- if (!tempList.contains(menu.getParentId())) {
- recursionFn(menus, menu);
- returnList.add(menu);
- }
- }
- if (returnList.isEmpty()) {
- returnList = menus;
- }
- return returnList;
- }
-
/**
* 构建前端所需要下拉树结构
*
@@ -203,9 +177,12 @@ public class SysMenuServiceImpl extends ServicePlusImpl buildMenuTreeSelect(List menus) {
- List menuTrees = buildMenuTree(menus);
- return menuTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
+ public List> buildMenuTreeSelect(List menus) {
+ return TreeBuildUtils.build(menus, (menu, tree) ->
+ tree.setId(menu.getMenuId())
+ .setParentId(menu.getParentId())
+ .setName(menu.getMenuName())
+ .setWeight(menu.getOrderNum()));
}
/**
@@ -285,11 +262,11 @@ public class SysMenuServiceImpl extends ServicePlusImpl()
- .eq(SysMenu::getMenuName, menu.getMenuName())
- .eq(SysMenu::getParentId, menu.getParentId())
- .last("limit 1"));
- if (StringUtils.isNotNull(info) && info.getMenuId().longValue() != menuId.longValue()) {
+ long count = count(new LambdaQueryWrapper()
+ .eq(SysMenu::getMenuName, menu.getMenuName())
+ .eq(SysMenu::getParentId, menu.getParentId())
+ .ne(SysMenu::getMenuId, menuId));
+ if (count > 0) {
return UserConstants.NOT_UNIQUE;
}
return UserConstants.UNIQUE;
@@ -324,7 +301,7 @@ public class SysMenuServiceImpl extends ServicePlusImpl selectPageOperLogList(SysOperLog operLog) {
Map params = operLog.getParams();
LambdaQueryWrapper lqw = new LambdaQueryWrapper()
- .like(StringUtils.isNotBlank(operLog.getTitle()), SysOperLog::getTitle, operLog.getTitle())
- .eq(operLog.getBusinessType() != null && operLog.getBusinessType() > 0,
- SysOperLog::getBusinessType, operLog.getBusinessType())
- .func(f -> {
- if (ArrayUtil.isNotEmpty(operLog.getBusinessTypes())) {
- f.in(SysOperLog::getBusinessType, Arrays.asList(operLog.getBusinessTypes()));
- }
- })
- .eq(operLog.getStatus() != null,
- SysOperLog::getStatus, operLog.getStatus())
- .like(StringUtils.isNotBlank(operLog.getOperName()), SysOperLog::getOperName, operLog.getOperName())
- .apply(StringUtils.isNotEmpty(params.get("beginTime")),
- "date_format(oper_time,'%y%m%d') >= date_format({0},'%y%m%d')",
- params.get("beginTime"))
- .apply(StringUtils.isNotEmpty(params.get("endTime")),
- "date_format(oper_time,'%y%m%d') <= date_format({0},'%y%m%d')",
- params.get("endTime"));
+ .like(StringUtils.isNotBlank(operLog.getTitle()), SysOperLog::getTitle, operLog.getTitle())
+ .eq(operLog.getBusinessType() != null && operLog.getBusinessType() > 0,
+ SysOperLog::getBusinessType, operLog.getBusinessType())
+ .func(f -> {
+ if (ArrayUtil.isNotEmpty(operLog.getBusinessTypes())) {
+ f.in(SysOperLog::getBusinessType, Arrays.asList(operLog.getBusinessTypes()));
+ }
+ })
+ .eq(operLog.getStatus() != null,
+ SysOperLog::getStatus, operLog.getStatus())
+ .like(StringUtils.isNotBlank(operLog.getOperName()), SysOperLog::getOperName, operLog.getOperName())
+ .between(params.get("beginTime") != null && params.get("endTime") != null,
+ SysOperLog::getOperTime, params.get("beginTime"), params.get("endTime"));
return PageUtils.buildDataInfo(page(PageUtils.buildPage("oper_id", "desc"), lqw));
}
@@ -88,24 +84,20 @@ public class SysOperLogServiceImpl extends ServicePlusImpl selectOperLogList(SysOperLog operLog) {
Map params = operLog.getParams();
return list(new LambdaQueryWrapper