diff --git a/README.md b/README.md index 5fc29ab7..a56dc6c4 100644 --- a/README.md +++ b/README.md @@ -4,12 +4,17 @@ [![License](https://img.shields.io/badge/License-MIT-blue.svg)](https://gitee.com/JavaLionLi/RuoYi-Vue-Plus/blob/master/LICENSE) [![使用IntelliJ IDEA开发维护](https://img.shields.io/badge/IntelliJ%20IDEA-提供支持-blue.svg)](https://www.jetbrains.com/?from=RuoYi-Vue-Plus)
-[![RuoYi-Vue-Plus](https://img.shields.io/badge/RuoYi_Vue_Plus-2.4.0-success.svg)](https://gitee.com/JavaLionLi/RuoYi-Vue-Plus) +[![RuoYi-Vue-Plus](https://img.shields.io/badge/RuoYi_Vue_Plus-2.5.0-success.svg)](https://gitee.com/JavaLionLi/RuoYi-Vue-Plus) [![Spring Boot](https://img.shields.io/badge/Spring%20Boot-2.4-blue.svg)]() [![JDK-8+](https://img.shields.io/badge/JDK-8+-green.svg)]() [![JDK-11](https://img.shields.io/badge/JDK-11-green.svg)]() -基于 RuoYi-Vue 集成 Mybatis-Plus Lombok Hutool 等便捷开发工具 适配重写相关业务 便于开发 定期与 RuoYi-Vue 同步 +RuoYi-Vue-Plus 是基于 RuoYi-Vue 针对 `分布式集群` 场景升级 定期与 RuoYi-Vue 同步 + +集成 Lock4j dynamic-datasource 等分布式场景解决方案 + +集成 Mybatis-Plus Lombok Hutool 等便捷开发工具 适配重写相关业务 便于开发 + * 前端开发框架 Vue、Element UI * 后端开发框架 Spring Boot、Redis * 容器框架 Undertow 基于 Netty 的高性能容器 @@ -27,6 +32,7 @@ * 多数据源框架 dynamic-datasource 支持主从与多种类数据库异构 * Redis客户端 采用 Redisson 性能更强 * 分布式锁 Lock4j 注解锁、工具锁 多种多样 +* 部署方式 Docker 容器编排 一键部署业务集群 ## 参考文档 @@ -34,6 +40,8 @@
>[初始化项目 必看](https://gitee.com/JavaLionLi/RuoYi-Vue-Plus/wikis/关于初始化项目?sort_id=4164117) > +>[部署项目 必看](https://gitee.com/JavaLionLi/RuoYi-Vue-Plus/wikis/关于应用部署?sort_id=4219382) +> >[参考文档 Wiki](https://gitee.com/JavaLionLi/RuoYi-Vue-Plus/wikis/pages) ## 提问四部曲 @@ -58,6 +66,12 @@ ### 四、加群 以上三点已经能解决大家绝大部分问题了,如果还有问题没能通过这几种方式解决,那么加群,大家一起在群里探讨一下 +## 贡献代码 + +欢迎各路英雄豪杰 `PR` 代码 请提交到 `dev` 开发分支 统一测试发版 + +框架定位为 `通用后台管理系统(分布式集群强化)` 原则上不接受业务 `PR` + ## 修改RuoYi功能 ### 依赖改动 @@ -74,6 +88,7 @@ * 移除 fastjson 统一使用 jackson 序列化 * 集成 dynamic-datasource 多数据源(默认支持MySQL,其他种类需自行适配) * 集成 Lock4j 实现分布式 注解锁、工具锁 多种多样 +* 增加 Docker 容器编排 打包插件与部署脚本 ### 代码改动 @@ -90,7 +105,7 @@ ### 其他 -* 同步升级 RuoYi-Vue 3.5.0 +* 同步升级 RuoYi-Vue * GitHub 地址 [RuoYi-Vue-Plus-github](https://github.com/JavaLionLi/RuoYi-Vue-Plus) * 单模块 fast 分支 [RuoYi-Vue-Plus-fast](https://gitee.com/JavaLionLi/RuoYi-Vue-Plus/tree/fast/) * Oracle 模块 oracle 分支 [RuoYi-Vue-Plus-oracle](https://gitee.com/JavaLionLi/RuoYi-Vue-Plus/tree/oracle/) diff --git a/docker/deploy.sh b/docker/deploy.sh new file mode 100644 index 00000000..3b6e6965 --- /dev/null +++ b/docker/deploy.sh @@ -0,0 +1,92 @@ +#!/bin/bash + +#使用说明,用来提示输入参数 +usage() { + echo "Usage: sh 执行脚本.sh [port|mount|monitor|base|start|stop|stopall|rm|rmiNoneTag]" + exit 1 +} + +#开启所需端口 +port(){ + firewall-cmd --add-port=3306/tcp --permanent + firewall-cmd --add-port=6379/tcp --permanent + service firewalld restart +} + +##放置挂载文件 +mount(){ + #挂载配置文件 + if test ! -f "/docker/nginx/conf/nginx.conf" ;then + mkdir -p /docker/nginx/conf + cp nginx/nginx.conf /docker/nginx/conf/nginx.conf + fi +} + +#启动基础模块 +base(){ + docker-compose up -d mysql nginx-web redis +} + +#启动基础模块 +monitor(){ + docker-compose up -d ruoyi-monitor-admin +} + +#启动程序模块 +start(){ + docker-compose up -d ruoyi-server1 ruoyi-server2 +} + +#停止程序模块 +stop(){ + docker-compose stop ruoyi-server1 ruoyi-server2 +} + +#关闭所有模块 +stopall(){ + docker-compose stop +} + +#删除所有模块 +rm(){ + docker-compose rm +} + +#删除Tag为空的镜像 +rmiNoneTag(){ + docker images|grep none|awk '{print $3}'|xargs docker rmi -f +} + +#根据输入参数,选择执行对应方法,不输入则执行使用说明 +case "$1" in +"port") + port +;; +"mount") + mount +;; +"base") + base +;; +"monitor") + monitor +;; +"start") + start +;; +"stop") + stop +;; +"stopall") + stopall +;; +"rm") + rm +;; +"rmiNoneTag") + rmiNoneTag +;; +*) + usage +;; +esac diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml new file mode 100644 index 00000000..d40ae29e --- /dev/null +++ b/docker/docker-compose.yml @@ -0,0 +1,119 @@ +version: '3' + +services: + mysql: + image: mysql:8.0.24 + container_name: mysql + environment: + # 时区上海 + TZ: Asia/Shanghai + # root 密码 + MYSQL_ROOT_PASSWORD: root + # 初始化数据库(后续的初始化sql会在这个库执行) + MYSQL_DATABASE: ry-vue + ports: + - 3306:3306 + volumes: + # 数据挂载 + - /docker/mysql/data/:/var/lib/mysql/ + # 配置挂载 + - /docker/mysql/conf/:/etc/mysql/conf.d/ + command: + # 将mysql8.0默认密码策略 修改为 原先 策略 (mysql8.0对其默认策略做了更改 会导致密码无法匹配) + --default-authentication-plugin=mysql_native_password + --character-set-server=utf8mb4 + --collation-server=utf8mb4_general_ci + --explicit_defaults_for_timestamp=true + --lower_case_table_names=1 + privileged: true + restart: always + networks: + ruoyi_net: + ipv4_address: 172.30.0.36 + + nginx-web: + # 如果需要指定版本 就把 latest 换成版本号 + image: nginx:latest + container_name: nginx-web + ports: + - 80:80 + - 443:443 + volumes: + # 证书映射 + - /docker/nginx/cert:/etc/nginx/cert + # 配置文件映射 + - /docker/nginx/conf/nginx.conf:/etc/nginx/nginx.conf + # 页面目录 + - /docker/nginx/html:/usr/share/nginx/html + # 日志目录 + - /docker/nginx/log:/var/log/nginx + # 主机本机时间文件映射 与本机时间同步 + - /etc/localtime:/etc/localtime:ro + privileged: true + restart: always + networks: + - ruoyi_net + + redis: + image: redis:6.2.1 + container_name: redis + ports: + - 6379:6379 + environment: + # 设置环境变量 时区上海 编码UTF-8 + TZ: Asia/Shanghai + LANG: en_US.UTF-8 + volumes: + # 配置文件 + - /docker/redis/conf/redis.conf:/redis.conf:rw + # 数据文件 + - /docker/redis/data:/data:rw + command: "redis-server --appendonly yes" + privileged: true + restart: always + networks: + ruoyi_net: + ipv4_address: 172.30.0.48 + + ruoyi-server1: + image: "ruoyi/ruoyi-server:2.5.0" + environment: + - TZ=Asia/Shanghai + volumes: + # 配置文件 + - /docker/server1/logs/:/ruoyi/server/logs/ + privileged: true + restart: always + networks: + ruoyi_net: + ipv4_address: 172.30.0.60 + + ruoyi-server2: + image: "ruoyi/ruoyi-server:2.5.0" + environment: + - TZ=Asia/Shanghai + volumes: + # 配置文件 + - /docker/server2/logs/:/ruoyi/server/logs/ + privileged: true + restart: always + networks: + ruoyi_net: + ipv4_address: 172.30.0.61 + + ruoyi-monitor-admin: + image: "ruoyi/ruoyi-monitor-admin:2.5.0" + environment: + - TZ=Asia/Shanghai + privileged: true + restart: always + networks: + ruoyi_net: + ipv4_address: 172.30.0.90 + +networks: + ruoyi_net: + driver: bridge + ipam: + config: + - subnet: 172.30.0.0/16 diff --git a/docker/nginx/nginx.conf b/docker/nginx/nginx.conf new file mode 100644 index 00000000..66ac29e3 --- /dev/null +++ b/docker/nginx/nginx.conf @@ -0,0 +1,77 @@ +worker_processes 1; + +error_log /var/log/nginx/error.log warn; +pid /var/run/nginx.pid; + +events { + worker_connections 1024; +} + +http { + include mime.types; + default_type application/octet-stream; + sendfile on; + keepalive_timeout 65; + # 限制body大小 + client_max_body_size 100m; + + log_format main '$remote_addr - $remote_user [$time_local] "$request" ' + '$status $body_bytes_sent "$http_referer" ' + '"$http_user_agent" "$http_x_forwarded_for"'; + + access_log /var/log/nginx/access.log main; + + upstream server { + server 172.30.0.60:8080; + server 172.30.0.61:8080; + } + + upstream monitor-admin { + server 172.30.0.90:9090; + } + + server { + listen 80; + server_name localhost; + + # https配置参考 start + #listen 443 ssl; + + # 证书直接存放 /docker/nginx/cert/ 目录下即可 更改证书名称即可 无需更改证书路径 + #ssl on; + #ssl_certificate /etc/nginx/cert/xxx.local.crt; # /etc/nginx/cert/ 为docker映射路径 不允许更改 + #ssl_certificate_key /etc/nginx/cert/xxx.local.key; # /etc/nginx/cert/ 为docker映射路径 不允许更改 + #ssl_session_timeout 5m; + #ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4; + #ssl_protocols TLSv1 TLSv1.1 TLSv1.2; + #ssl_prefer_server_ciphers on; + # https配置参考 end + + location / { + root /usr/share/nginx/html; + try_files $uri $uri/ /index.html; + index index.html index.htm; + } + + location /prod-api/ { + proxy_set_header Host $http_host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header REMOTE-HOST $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_pass http://server/; + } + + location /admin/ { + proxy_set_header Host $http_host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header REMOTE-HOST $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_pass http://monitor-admin/admin/; + } + + error_page 500 502 503 504 /50x.html; + location = /50x.html { + root html; + } + } +} diff --git a/pom.xml b/pom.xml index 2a8521c4..d56898ba 100644 --- a/pom.xml +++ b/pom.xml @@ -6,32 +6,38 @@ com.ruoyi ruoyi-vue-plus - ${ruoyi-vue-plus.version} + 2.5.0 RuoYi-Vue-Plus https://gitee.com/JavaLionLi/RuoYi-Vue-Plus RuoYi-Vue-Plus后台管理系统 - 2.4.0 - 2.4.7 + 2.5.0 + 2.4.8 UTF-8 UTF-8 1.8 3.1.1 1.2.6 - 3.0.2 + 3.0.3 4.1.2 1.7 0.9.1 3.4.3 - 5.7.2 + 5.7.4 3.0.3 11.0 - 2.4.1 - 3.15.2 + 2.4.3 + 3.16.0 2.2.1 3.4.0 + + + localhost + http://${docker.registry.url}:2375 + ruoyi + 1.2.0 @@ -192,6 +198,7 @@ ruoyi-generator ruoyi-common ruoyi-demo + ruoyi-extend pom diff --git a/ruoyi-admin/Dockerfile b/ruoyi-admin/Dockerfile new file mode 100644 index 00000000..88f4932b --- /dev/null +++ b/ruoyi-admin/Dockerfile @@ -0,0 +1,14 @@ +FROM anapsix/alpine-java:8_server-jre_unlimited + +MAINTAINER Lion Li + +RUN mkdir -p /ruoyi/server +RUN mkdir -p /ruoyi/server/logs + +WORKDIR /ruoyi/server + +EXPOSE 8080 + +ADD ./target/ruoyi-admin.jar ./app.jar + +ENTRYPOINT ["java", "-Djava.security.egd=file:/dev/./urandom", "-jar", "app.jar"] diff --git a/ruoyi-admin/pom.xml b/ruoyi-admin/pom.xml index 031427fc..74502132 100644 --- a/ruoyi-admin/pom.xml +++ b/ruoyi-admin/pom.xml @@ -5,7 +5,7 @@ ruoyi-vue-plus com.ruoyi - ${ruoyi-vue-plus.version} + 2.5.0 4.0.0 jar @@ -24,7 +24,7 @@ true - + mysql mysql-connector-java @@ -82,7 +82,26 @@ false ${project.artifactId} - + + + com.spotify + docker-maven-plugin + ${docker.plugin.version} + + ${docker.namespace}/ruoyi-server:${project.version} + ${project.basedir} + ${docker.registry.host} + ${docker.registry.url} + ${docker.registry.url} + + + / + ${project.build.directory} + ${project.build.finalName}.jar + + + + diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysIndexController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysIndexController.java new file mode 100644 index 00000000..a29620c4 --- /dev/null +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysIndexController.java @@ -0,0 +1,29 @@ +package com.ruoyi.web.controller.system; + +import cn.hutool.core.util.StrUtil; +import com.ruoyi.common.config.RuoYiConfig; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +/** + * 首页 + * + * @author ruoyi + */ +@RestController +public class SysIndexController +{ + /** 系统基础配置 */ + @Autowired + private RuoYiConfig ruoyiConfig; + + /** + * 访问首页,提示语 + */ + @RequestMapping("/") + public String index() + { + return StrUtil.format("欢迎使用{}后台管理框架,当前版本:v{},请通过前端地址访问。", ruoyiConfig.getName(), ruoyiConfig.getVersion()); + } +} diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysMenuController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysMenuController.java index 00f14642..f4185413 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysMenuController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysMenuController.java @@ -1,8 +1,6 @@ package com.ruoyi.web.controller.system; -import cn.hutool.core.util.StrUtil; import com.ruoyi.common.annotation.Log; -import com.ruoyi.common.constant.Constants; import com.ruoyi.common.constant.UserConstants; import com.ruoyi.common.core.controller.BaseController; import com.ruoyi.common.core.domain.AjaxResult; @@ -11,6 +9,7 @@ import com.ruoyi.common.core.domain.model.LoginUser; import com.ruoyi.common.enums.BusinessType; import com.ruoyi.common.utils.SecurityUtils; import com.ruoyi.common.utils.ServletUtils; +import com.ruoyi.common.utils.StringUtils; import com.ruoyi.framework.web.service.TokenService; import com.ruoyi.system.service.ISysMenuService; import org.springframework.beans.factory.annotation.Autowired; @@ -98,8 +97,7 @@ public class SysMenuController extends BaseController { return AjaxResult.error("新增菜单'" + menu.getMenuName() + "'失败,菜单名称已存在"); } - else if (UserConstants.YES_FRAME.equals(menu.getIsFrame()) - && !StrUtil.startWithAny(menu.getPath(), Constants.HTTP, Constants.HTTPS)) + else if (UserConstants.YES_FRAME.equals(menu.getIsFrame()) && !StringUtils.ishttp(menu.getPath())) { return AjaxResult.error("新增菜单'" + menu.getMenuName() + "'失败,地址必须以http(s)://开头"); } @@ -119,8 +117,7 @@ public class SysMenuController extends BaseController { return AjaxResult.error("修改菜单'" + menu.getMenuName() + "'失败,菜单名称已存在"); } - else if (UserConstants.YES_FRAME.equals(menu.getIsFrame()) - && !StrUtil.startWithAny(menu.getPath(), Constants.HTTP, Constants.HTTPS)) + else if (UserConstants.YES_FRAME.equals(menu.getIsFrame()) && !StringUtils.ishttp(menu.getPath())) { return AjaxResult.error("修改菜单'" + menu.getMenuName() + "'失败,地址必须以http(s)://开头"); } diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysRoleController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysRoleController.java index 70e640e8..5701aa1a 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysRoleController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysRoleController.java @@ -6,6 +6,7 @@ import com.ruoyi.common.constant.UserConstants; import com.ruoyi.common.core.controller.BaseController; import com.ruoyi.common.core.domain.AjaxResult; 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.page.TableDataInfo; import com.ruoyi.common.enums.BusinessType; @@ -14,6 +15,7 @@ import com.ruoyi.common.utils.ServletUtils; import com.ruoyi.common.utils.poi.ExcelUtil; import com.ruoyi.framework.web.service.SysPermissionService; import com.ruoyi.framework.web.service.TokenService; +import com.ruoyi.system.domain.SysUserRole; import com.ruoyi.system.service.ISysRoleService; import com.ruoyi.system.service.ISysUserService; import org.springframework.beans.factory.annotation.Autowired; @@ -25,7 +27,7 @@ import java.util.List; /** * 角色信息 - * + * * @author ruoyi */ @RestController @@ -171,4 +173,57 @@ public class SysRoleController extends BaseController { return AjaxResult.success(roleService.selectRoleAll()); } + + /** + * 查询已分配用户角色列表 + */ + @PreAuthorize("@ss.hasPermi('system:role:list')") + @GetMapping("/authUser/allocatedList") + public TableDataInfo allocatedList(SysUser user) + { + return userService.selectAllocatedList(user); + } + + /** + * 查询未分配用户角色列表 + */ + @PreAuthorize("@ss.hasPermi('system:role:list')") + @GetMapping("/authUser/unallocatedList") + public TableDataInfo unallocatedList(SysUser user) + { + return userService.selectUnallocatedList(user); + } + + /** + * 取消授权用户 + */ + @PreAuthorize("@ss.hasPermi('system:role:edit')") + @Log(title = "角色管理", businessType = BusinessType.GRANT) + @PutMapping("/authUser/cancel") + public AjaxResult cancelAuthUser(@RequestBody SysUserRole userRole) + { + return toAjax(roleService.deleteAuthUser(userRole)); + } + + /** + * 批量取消授权用户 + */ + @PreAuthorize("@ss.hasPermi('system:role:edit')") + @Log(title = "角色管理", businessType = BusinessType.GRANT) + @PutMapping("/authUser/cancelAll") + public AjaxResult cancelAuthUserAll(Long roleId, Long[] userIds) + { + return toAjax(roleService.deleteAuthUsers(roleId, userIds)); + } + + /** + * 批量选择用户授权 + */ + @PreAuthorize("@ss.hasPermi('system:role:edit')") + @Log(title = "角色管理", businessType = BusinessType.GRANT) + @PutMapping("/authUser/selectAll") + public AjaxResult selectAuthUserAll(Long roleId, Long[] userIds) + { + return toAjax(roleService.insertAuthUsers(roleId, userIds)); + } } diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysUserController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysUserController.java index 079c15ac..a67615f3 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysUserController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysUserController.java @@ -196,4 +196,31 @@ public class SysUserController extends BaseController user.setUpdateBy(SecurityUtils.getUsername()); return toAjax(userService.updateUserStatus(user)); } + + /** + * 根据用户编号获取授权角色 + */ + @PreAuthorize("@ss.hasPermi('system:user:query')") + @GetMapping("/authRole/{userId}") + public AjaxResult authRole(@PathVariable("userId") Long userId) + { + SysUser user = userService.selectUserById(userId); + List roles = roleService.selectRolesByUserId(userId); + Map ajax = new HashMap<>(); + ajax.put("user", user); + ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList())); + return AjaxResult.success(ajax); + } + + /** + * 用户授权角色 + */ + @PreAuthorize("@ss.hasPermi('system:user:edit')") + @Log(title = "用户管理", businessType = BusinessType.GRANT) + @PutMapping("/authRole") + public AjaxResult insertAuthRole(Long userId, Long[] roleIds) + { + userService.insertUserAuth(userId, roleIds); + return success(); + } } diff --git a/ruoyi-admin/src/main/resources/application-dev.yml b/ruoyi-admin/src/main/resources/application-dev.yml index 35901b51..62312f6e 100644 --- a/ruoyi-admin/src/main/resources/application-dev.yml +++ b/ruoyi-admin/src/main/resources/application-dev.yml @@ -110,3 +110,30 @@ redisson: subscriptionsPerConnection: 5 # DNS监测时间间隔,单位:毫秒 dnsMonitoringInterval: 5000 + +--- # 监控配置 +spring: + boot: + admin: + # Spring Boot Admin Client 客户端的相关配置 + client: + # 设置 Spring Boot Admin Server 地址 + url: http://localhost:9090/admin + instance: + prefer-ip: true # 注册实例时,优先使用 IP + username: ruoyi + password: 123456 + +# Actuator 监控端点的配置项 +management: + endpoints: + web: + # Actuator 提供的 API 接口的根目录。默认为 /actuator + base-path: /actuator + exposure: + # 需要开放的端点。默认值只打开 health 和 info 两个端点。通过设置 * ,可以开放所有端点。 + # 生产环境不建议放开所有 根据项目需求放开即可 + include: '*' + endpoint: + logfile: + external-file: ./logs/sys-console.log diff --git a/ruoyi-admin/src/main/resources/application-prod.yml b/ruoyi-admin/src/main/resources/application-prod.yml index 35901b51..2c9d4e57 100644 --- a/ruoyi-admin/src/main/resources/application-prod.yml +++ b/ruoyi-admin/src/main/resources/application-prod.yml @@ -12,7 +12,7 @@ spring: # 主库数据源 master: driverClassName: com.mysql.cj.jdbc.Driver - url: jdbc:mysql://localhost:3306/ry-vue?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&autoReconnect=true + url: jdbc:mysql://172.30.0.36:3306/ry-vue?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&autoReconnect=true username: root password: root # 从库数据源 @@ -66,7 +66,7 @@ spring: # redis 配置 redis: # 地址 - host: localhost + host: 172.30.0.48 # 端口,默认为6379 port: 6379 # 数据库索引 @@ -110,3 +110,30 @@ redisson: subscriptionsPerConnection: 5 # DNS监测时间间隔,单位:毫秒 dnsMonitoringInterval: 5000 + +--- # 监控配置 +spring: + boot: + admin: + # Spring Boot Admin Client 客户端的相关配置 + client: + # 设置 Spring Boot Admin Server 地址 + url: http://172.30.0.90:9090/admin + instance: + prefer-ip: true # 注册实例时,优先使用 IP + username: ruoyi + password: 123456 + +# Actuator 监控端点的配置项 +management: + endpoints: + web: + # Actuator 提供的 API 接口的根目录。默认为 /actuator + base-path: /actuator + exposure: + # 需要开放的端点。默认值只打开 health 和 info 两个端点。通过设置 * ,可以开放所有端点。 + # 生产环境不建议放开所有 根据项目需求放开即可 + include: health,info + endpoint: + logfile: + external-file: ./logs/sys-console.log diff --git a/ruoyi-admin/src/main/resources/application.yml b/ruoyi-admin/src/main/resources/application.yml index e153d194..b88929dd 100644 --- a/ruoyi-admin/src/main/resources/application.yml +++ b/ruoyi-admin/src/main/resources/application.yml @@ -64,6 +64,8 @@ logging: # Spring配置 spring: + application: + name: ${ruoyi.name} # 资源信息 messages: # 国际化资源文件路径 @@ -110,6 +112,8 @@ token: # MyBatisPlus配置 # https://baomidou.com/config/ mybatis-plus: + # 不支持多包, 如有需要可在注解配置 或 提升扫包等级 + # 例如 com.**.**.mapper mapperPackage: com.ruoyi.**.mapper # 对应的 XML 文件位置 mapperLocations: classpath*:mapper/**/*Mapper.xml @@ -156,7 +160,9 @@ mybatis-plus: # STATEMENT 关闭一级缓存 localCacheScope: SESSION # 开启Mybatis二级缓存,默认为 true - cacheEnabled: true + cacheEnabled: false + # 更详细的日志输出 会有性能损耗 + # logImpl: org.apache.ibatis.logging.stdout.StdOutImpl global-config: # 是否打印 Logo banner banner: true @@ -203,7 +209,7 @@ swagger: # 请求前缀 pathMapping: /dev-api # 标题 - title: '标题:RuoYi-Vue-Plus后台管理系统_接口文档' + title: '标题:${ruoyi.name}后台管理系统_接口文档' # 描述 description: '描述:用于管理集团旗下公司的人员信息,具体包括XXX,XXX模块...' # 版本 @@ -244,6 +250,8 @@ thread-pool: # feign 相关配置 feign: + # 不支持多包, 如有需要可在注解配置 或 提升扫包等级 + # 例如 com.**.**.feign package: com.ruoyi.**.feign # 开启压缩 compression: @@ -256,6 +264,21 @@ feign: circuitbreaker: enabled: true +--- # redisson 缓存配置 +redisson: + cacheGroup: + # 用例: @Cacheable(cacheNames="groupId", key="#XXX") 方可使用缓存组配置 + - groupId: redissonCacheMap + # 组过期时间(脚本监控) + ttl: 60000 + # 组最大空闲时间(脚本监控) + maxIdleTime: 60000 + # 组最大长度 + maxSize: 0 + - groupId: testCache + ttl: 1000 + maxIdleTime: 500 + --- # 分布式锁 lock4j 全局配置 lock4j: # 获取分布式锁超时时间,默认为 3000 毫秒 @@ -293,31 +316,3 @@ spring: tablePrefix: QRTZ_ # sqlserver 启用 # selectWithLockSQL: SELECT * FROM {0}LOCKS UPDLOCK WHERE LOCK_NAME = ? - ---- # 监控配置 -spring: - application: - name: ruoyi-vue-plus - boot: - admin: - # Spring Boot Admin Client 客户端的相关配置 - client: - # 设置 Spring Boot Admin Server 地址 - url: http://localhost:${server.port}${spring.boot.admin.context-path} - instance: - prefer-ip: true # 注册实例时,优先使用 IP - # Spring Boot Admin Server 服务端的相关配置 - context-path: /admin # 配置 Spring - -# Actuator 监控端点的配置项 -management: - endpoints: - web: - # Actuator 提供的 API 接口的根目录。默认为 /actuator - base-path: /actuator - exposure: - # 需要开放的端点。默认值只打开 health 和 info 两个端点。通过设置 * ,可以开放所有端点。 - include: '*' - endpoint: - logfile: - external-file: ./logs/sys-console.log diff --git a/ruoyi-admin/src/main/resources/i18n/messages_en_US.properties b/ruoyi-admin/src/main/resources/i18n/messages_en_US.properties new file mode 100644 index 00000000..41870654 --- /dev/null +++ b/ruoyi-admin/src/main/resources/i18n/messages_en_US.properties @@ -0,0 +1,33 @@ +#错误消息 +not.null= +user.jcaptcha.error= +user.jcaptcha.expire= +user.not.exists= +user.password.not.match= +user.password.retry.limit.count= +user.password.retry.limit.exceed= +user.password.delete= +user.blocked= +role.blocked= +user.logout.success= +length.not.valid= +user.username.not.valid= +user.password.not.valid= +user.email.not.valid= +user.mobile.phone.number.not.valid= +user.login.success= +user.notfound= +user.forcelogout= +user.unknown.error= + +##文件上传消息 +upload.exceed.maxSize= +upload.filename.exceed.length= + +##权限 +no.permission= +no.create.permission= +no.update.permission= +no.delete.permission= +no.export.permission= +no.view.permission= diff --git a/ruoyi-admin/src/main/resources/i18n/messages_zh_CN.properties b/ruoyi-admin/src/main/resources/i18n/messages_zh_CN.properties new file mode 100644 index 00000000..d63aa1f8 --- /dev/null +++ b/ruoyi-admin/src/main/resources/i18n/messages_zh_CN.properties @@ -0,0 +1,36 @@ +#错误消息 +not.null=* 必须填写 +user.jcaptcha.error=验证码错误 +user.jcaptcha.expire=验证码已失效 +user.not.exists=用户不存在/密码错误 +user.password.not.match=用户不存在/密码错误 +user.password.retry.limit.count=密码输入错误{0}次 +user.password.retry.limit.exceed=密码输入错误{0}次,帐户锁定10分钟 +user.password.delete=对不起,您的账号已被删除 +user.blocked=用户已封禁,请联系管理员 +role.blocked=角色已封禁,请联系管理员 +user.logout.success=退出成功 + +length.not.valid=长度必须在{min}到{max}个字符之间 + +user.username.not.valid=* 2到20个汉字、字母、数字或下划线组成,且必须以非数字开头 +user.password.not.valid=* 5-50个字符 + +user.email.not.valid=邮箱格式错误 +user.mobile.phone.number.not.valid=手机号格式错误 +user.login.success=登录成功 +user.notfound=请重新登录 +user.forcelogout=管理员强制退出,请重新登录 +user.unknown.error=未知错误,请重新登录 + +##文件上传消息 +upload.exceed.maxSize=上传的文件大小超出限制的文件大小!
允许的文件最大大小是:{0}MB! +upload.filename.exceed.length=上传的文件名最长{0}个字符 + +##权限 +no.permission=您没有数据的权限,请联系管理员添加权限 [{0}] +no.create.permission=您没有创建数据的权限,请联系管理员添加权限 [{0}] +no.update.permission=您没有修改数据的权限,请联系管理员添加权限 [{0}] +no.delete.permission=您没有删除数据的权限,请联系管理员添加权限 [{0}] +no.export.permission=您没有导出数据的权限,请联系管理员添加权限 [{0}] +no.view.permission=您没有查看数据的权限,请联系管理员添加权限 [{0}] diff --git a/ruoyi-common/pom.xml b/ruoyi-common/pom.xml index e2cbd39f..28af3046 100644 --- a/ruoyi-common/pom.xml +++ b/ruoyi-common/pom.xml @@ -5,7 +5,7 @@ ruoyi-vue-plus com.ruoyi - ${ruoyi-vue-plus.version} + 2.5.0 4.0.0 @@ -116,10 +116,6 @@ feign-okhttp
- - de.codecentric - spring-boot-admin-starter-server - de.codecentric spring-boot-admin-starter-client diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/constant/UserConstants.java b/ruoyi-common/src/main/java/com/ruoyi/common/constant/UserConstants.java index 56b46ba8..eda4ab6a 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/constant/UserConstants.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/constant/UserConstants.java @@ -2,7 +2,7 @@ package com.ruoyi.common.constant; /** * 用户常量信息 - * + * * @author ruoyi */ public class UserConstants @@ -57,6 +57,9 @@ public class UserConstants /** ParentView组件标识 */ public final static String PARENT_VIEW = "ParentView"; + /** InnerLink组件标识 */ + public final static String INNER_LINK = "InnerLink"; + /** 校验返回结果码 */ public final static String UNIQUE = "0"; public final static String NOT_UNIQUE = "1"; diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/entity/SysUser.java b/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/entity/SysUser.java index 110c5480..898138b0 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/entity/SysUser.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/entity/SysUser.java @@ -148,6 +148,10 @@ public class SysUser implements Serializable @TableField(exist = false) private Long[] postIds; + /** 角色ID */ + @TableField(exist = false) + private Long roleId; + public SysUser(Long userId) { this.userId = userId; diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/core/mybatisplus/cache/MybatisPlusRedisCache.java b/ruoyi-common/src/main/java/com/ruoyi/common/core/mybatisplus/cache/MybatisPlusRedisCache.java index 0e21d70e..633a0b5a 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/core/mybatisplus/cache/MybatisPlusRedisCache.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/core/mybatisplus/cache/MybatisPlusRedisCache.java @@ -15,6 +15,9 @@ import java.util.concurrent.locks.ReentrantReadWriteLock; /** * mybatis-redis 二级缓存 * + * 使用方法 配置文件开启 mybatis-plus 二级缓存 + * 在 XxxMapper.java 类上添加注解 @CacheNamespace(implementation = MybatisPlusRedisCache.class, eviction = MybatisPlusRedisCache.class) + * * @author Lion Li */ @Slf4j diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/core/mybatisplus/methods/InsertAll.java b/ruoyi-common/src/main/java/com/ruoyi/common/core/mybatisplus/methods/InsertAll.java index 9c8c0f74..ec57621b 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/core/mybatisplus/methods/InsertAll.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/core/mybatisplus/methods/InsertAll.java @@ -1,13 +1,17 @@ package com.ruoyi.common.core.mybatisplus.methods; import cn.hutool.core.util.StrUtil; +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.core.enums.SqlMethod; +import com.baomidou.mybatisplus.core.injector.AbstractMethod; +import com.baomidou.mybatisplus.core.metadata.TableInfo; +import com.baomidou.mybatisplus.core.metadata.TableInfoHelper; +import org.apache.ibatis.executor.keygen.Jdbc3KeyGenerator; +import org.apache.ibatis.executor.keygen.KeyGenerator; import org.apache.ibatis.executor.keygen.NoKeyGenerator; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.mapping.SqlSource; -import com.baomidou.mybatisplus.core.injector.AbstractMethod; -import com.baomidou.mybatisplus.core.metadata.TableInfo; - /** * 单sql批量插入 * @@ -20,9 +24,28 @@ public class InsertAll extends AbstractMethod { final String sql = ""; final String fieldSql = prepareFieldSql(tableInfo); final String valueSql = prepareValuesSqlForMysqlBatch(tableInfo); + KeyGenerator keyGenerator = new NoKeyGenerator(); + SqlMethod sqlMethod = SqlMethod.INSERT_ONE; + String keyProperty = null; + String keyColumn = null; + // 表包含主键处理逻辑,如果不包含主键当普通字段处理 + if (StrUtil.isNotBlank(tableInfo.getKeyProperty())) { + if (tableInfo.getIdType() == IdType.AUTO) { + /** 自增主键 */ + keyGenerator = new Jdbc3KeyGenerator(); + keyProperty = tableInfo.getKeyProperty(); + keyColumn = tableInfo.getKeyColumn(); + } else { + if (null != tableInfo.getKeySequence()) { + keyGenerator = TableInfoHelper.genKeyGenerator(getMethod(sqlMethod), tableInfo, builderAssistant); + keyProperty = tableInfo.getKeyProperty(); + keyColumn = tableInfo.getKeyColumn(); + } + } + } final String sqlResult = String.format(sql, tableInfo.getTableName(), fieldSql, valueSql); SqlSource sqlSource = languageDriver.createSqlSource(configuration, sqlResult, modelClass); - return this.addInsertMappedStatement(mapperClass, modelClass, "insertAll", sqlSource, new NoKeyGenerator(), null, null); + return this.addInsertMappedStatement(mapperClass, modelClass, "insertAll", sqlSource, keyGenerator, keyProperty, keyColumn); } private String prepareFieldSql(TableInfo tableInfo) { diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/core/redis/RedisCache.java b/ruoyi-common/src/main/java/com/ruoyi/common/core/redis/RedisCache.java index 3c8bc923..f46a2157 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/core/redis/RedisCache.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/core/redis/RedisCache.java @@ -205,9 +205,9 @@ public class RedisCache { * @param hKeys Hash键集合 * @return Hash对象集合 */ - public List getMultiCacheMapValue(final String key, final Collection hKeys) { - RListMultimap rListMultimap = redissonClient.getListMultimap(key); - return rListMultimap.getAll(hKeys); + public Map getMultiCacheMapValue(final String key, final Set hKeys) { + RMap rMap = redissonClient.getMap(key); + return rMap.getAll(hKeys); } /** diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/utils/DictUtils.java b/ruoyi-common/src/main/java/com/ruoyi/common/utils/DictUtils.java index 7da0c669..5d1fef18 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/utils/DictUtils.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/utils/DictUtils.java @@ -88,7 +88,7 @@ public class DictUtils StringBuilder propertyString = new StringBuilder(); List datas = getDictCache(dictType); - if (StrUtil.containsAny(separator, dictValue) && CollUtil.isNotEmpty(datas)) + if (StrUtil.containsAny(dictValue, separator) && CollUtil.isNotEmpty(datas)) { for (SysDictData dict : datas) { @@ -128,7 +128,7 @@ public class DictUtils StringBuilder propertyString = new StringBuilder(); List datas = getDictCache(dictType); - if (StrUtil.containsAny(separator, dictLabel) && CollUtil.isNotEmpty(datas)) + if (StrUtil.containsAny(dictLabel, separator) && CollUtil.isNotEmpty(datas)) { for (SysDictData dict : datas) { diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/utils/StringUtils.java b/ruoyi-common/src/main/java/com/ruoyi/common/utils/StringUtils.java new file mode 100644 index 00000000..f3f29f46 --- /dev/null +++ b/ruoyi-common/src/main/java/com/ruoyi/common/utils/StringUtils.java @@ -0,0 +1,28 @@ +package com.ruoyi.common.utils; + +import cn.hutool.core.util.StrUtil; +import com.ruoyi.common.constant.Constants; + +/** + * 字符串工具类 + * + * @author ruoyi + */ +public class StringUtils extends org.apache.commons.lang3.StringUtils { + /** 空字符串 */ + private static final String NULLSTR = ""; + + /** 下划线 */ + private static final char SEPARATOR = '_'; + + /** + * 是否为http(s)://开头 + * + * @param link 链接 + * @return 结果 + */ + public static boolean ishttp(String link) { + return StrUtil.startWithAny(link, Constants.HTTP, Constants.HTTPS); + } + +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/utils/poi/ExcelUtil.java b/ruoyi-common/src/main/java/com/ruoyi/common/utils/poi/ExcelUtil.java index 619ec80c..96843d18 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/utils/poi/ExcelUtil.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/utils/poi/ExcelUtil.java @@ -1,1072 +1,1072 @@ -package com.ruoyi.common.utils.poi; - -import cn.hutool.core.convert.Convert; -import cn.hutool.core.lang.Validator; -import cn.hutool.core.util.StrUtil; -import com.ruoyi.common.annotation.Excel; -import com.ruoyi.common.annotation.Excel.ColumnType; -import com.ruoyi.common.annotation.Excel.Type; -import com.ruoyi.common.annotation.Excels; -import com.ruoyi.common.config.RuoYiConfig; -import com.ruoyi.common.core.domain.AjaxResult; -import com.ruoyi.common.exception.CustomException; -import com.ruoyi.common.utils.DateUtils; -import com.ruoyi.common.utils.DictUtils; -import com.ruoyi.common.utils.file.FileTypeUtils; -import com.ruoyi.common.utils.file.ImageUtils; -import com.ruoyi.common.utils.reflect.ReflectUtils; -import org.apache.poi.ss.usermodel.*; -import org.apache.poi.ss.util.CellRangeAddressList; -import org.apache.poi.xssf.streaming.SXSSFWorkbook; -import org.apache.poi.xssf.usermodel.XSSFClientAnchor; -import org.apache.poi.xssf.usermodel.XSSFDataValidation; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.*; -import java.lang.reflect.Field; -import java.math.BigDecimal; -import java.text.DecimalFormat; -import java.util.*; -import java.util.stream.Collectors; - -/** - * Excel相关处理 - * - * @author ruoyi - */ -public class ExcelUtil -{ - private static final Logger log = LoggerFactory.getLogger(ExcelUtil.class); - - /** - * Excel sheet最大行数,默认65536 - */ - public static final int sheetSize = 65536; - - /** - * 工作表名称 - */ - private String sheetName; - - /** - * 导出类型(EXPORT:导出数据;IMPORT:导入模板) - */ - private Type type; - - /** - * 工作薄对象 - */ - private Workbook wb; - - /** - * 工作表对象 - */ - private Sheet sheet; - - /** - * 样式列表 - */ - private Map styles; - - /** - * 导入导出数据列表 - */ - private List list; - - /** - * 注解列表 - */ - private List fields; - - /** - * 最大高度 - */ - private short maxHeight; - - /** - * 统计列表 - */ - private Map statistics = new HashMap(); - - /** - * 数字格式 - */ - private static final DecimalFormat DOUBLE_FORMAT = new DecimalFormat("######0.00"); - - /** - * 实体对象 - */ - public Class clazz; - - public ExcelUtil(Class clazz) - { - this.clazz = clazz; - } - - public void init(List list, String sheetName, Type type) - { - if (list == null) - { - list = new ArrayList(); - } - this.list = list; - this.sheetName = sheetName; - this.type = type; - createExcelField(); - createWorkbook(); - } - - /** - * 对excel表单默认第一个索引名转换成list - * - * @param is 输入流 - * @return 转换后集合 - */ - public List importExcel(InputStream is) throws Exception - { - return importExcel(StrUtil.EMPTY, is); - } - - /** - * 对excel表单指定表格索引名转换成list - * - * @param sheetName 表格索引名 - * @param is 输入流 - * @return 转换后集合 - */ - public List importExcel(String sheetName, InputStream is) throws Exception - { - this.type = Type.IMPORT; - this.wb = WorkbookFactory.create(is); - List list = new ArrayList(); - Sheet sheet = null; - if (Validator.isNotEmpty(sheetName)) - { - // 如果指定sheet名,则取指定sheet中的内容. - sheet = wb.getSheet(sheetName); - } - else - { - // 如果传入的sheet名不存在则默认指向第1个sheet. - sheet = wb.getSheetAt(0); - } - - if (sheet == null) - { - throw new IOException("文件sheet不存在"); - } - - int rows = sheet.getPhysicalNumberOfRows(); - - if (rows > 0) - { - // 定义一个map用于存放excel列的序号和field. - Map cellMap = new HashMap(); - // 获取表头 - Row heard = sheet.getRow(0); - for (int i = 0; i < heard.getPhysicalNumberOfCells(); i++) - { - Cell cell = heard.getCell(i); - if (Validator.isNotNull(cell)) - { - String value = this.getCellValue(heard, i).toString(); - cellMap.put(value, i); - } - else - { - cellMap.put(null, i); - } - } - // 有数据时才处理 得到类的所有field. - Field[] allFields = clazz.getDeclaredFields(); - // 定义一个map用于存放列的序号和field. - Map fieldsMap = new HashMap(); - for (int col = 0; col < allFields.length; col++) - { - Field field = allFields[col]; - Excel attr = field.getAnnotation(Excel.class); - if (attr != null && (attr.type() == Type.ALL || attr.type() == type)) - { - // 设置类的私有字段属性可访问. - field.setAccessible(true); - Integer column = cellMap.get(attr.name()); - if (column != null) - { - fieldsMap.put(column, field); - } - } - } - for (int i = 1; i < rows; i++) - { - // 从第2行开始取数据,默认第一行是表头. - Row row = sheet.getRow(i); - if(row == null) - { - continue; - } - T entity = null; - for (Map.Entry entry : fieldsMap.entrySet()) - { - Object val = this.getCellValue(row, entry.getKey()); - - // 如果不存在实例则新建. - entity = (entity == null ? clazz.newInstance() : entity); - // 从map中得到对应列的field. - Field field = fieldsMap.get(entry.getKey()); - // 取得类型,并根据对象类型设置值. - Class fieldType = field.getType(); - if (String.class == fieldType) - { - String s = Convert.toStr(val); - if (StrUtil.endWith(s, ".0")) - { - val = StrUtil.subBefore(s, ".0",false); - } - else - { - String dateFormat = field.getAnnotation(Excel.class).dateFormat(); - if (Validator.isNotEmpty(dateFormat)) - { - val = DateUtils.parseDateToStr(dateFormat, (Date) val); - } - else - { - val = Convert.toStr(val); - } - } - } - else if ((Integer.TYPE == fieldType || Integer.class == fieldType) && Validator.isNumber(Convert.toStr(val))) - { - val = Convert.toInt(val); - } - else if (Long.TYPE == fieldType || Long.class == fieldType) - { - val = Convert.toLong(val); - } - else if (Double.TYPE == fieldType || Double.class == fieldType) - { - val = Convert.toDouble(val); - } - else if (Float.TYPE == fieldType || Float.class == fieldType) - { - val = Convert.toFloat(val); - } - else if (BigDecimal.class == fieldType) - { - val = Convert.toBigDecimal(val); - } - else if (Date.class == fieldType) - { - if (val instanceof String) - { - val = DateUtils.parseDate(val); - } - else if (val instanceof Double) - { - val = DateUtil.getJavaDate((Double) val); - } - } - else if (Boolean.TYPE == fieldType || Boolean.class == fieldType) - { - val = Convert.toBool(val, false); - } - if (Validator.isNotNull(fieldType)) - { - Excel attr = field.getAnnotation(Excel.class); - String propertyName = field.getName(); - if (Validator.isNotEmpty(attr.targetAttr())) - { - propertyName = field.getName() + "." + attr.targetAttr(); - } - else if (Validator.isNotEmpty(attr.readConverterExp())) - { - val = reverseByExp(Convert.toStr(val), attr.readConverterExp(), attr.separator()); - } - else if (Validator.isNotEmpty(attr.dictType())) - { - val = reverseDictByExp(Convert.toStr(val), attr.dictType(), attr.separator()); - } - ReflectUtils.invokeSetter(entity, propertyName, val); - } - } - list.add(entity); - } - } - return list; - } - - /** - * 对list数据源将其里面的数据导入到excel表单 - * - * @param list 导出数据集合 - * @param sheetName 工作表的名称 - * @return 结果 - */ - public AjaxResult exportExcel(List list, String sheetName) - { - this.init(list, sheetName, Type.EXPORT); - return exportExcel(); - } - - /** - * 对list数据源将其里面的数据导入到excel表单 - * - * @param sheetName 工作表的名称 - * @return 结果 - */ - public AjaxResult importTemplateExcel(String sheetName) - { - this.init(null, sheetName, Type.IMPORT); - return exportExcel(); - } - - /** - * 对list数据源将其里面的数据导入到excel表单 - * - * @return 结果 - */ - public AjaxResult exportExcel() - { - OutputStream out = null; - try - { - // 取出一共有多少个sheet. - double sheetNo = Math.ceil(list.size() / sheetSize); - for (int index = 0; index <= sheetNo; index++) - { - createSheet(sheetNo, index); - - // 产生一行 - Row row = sheet.createRow(0); - int column = 0; - // 写入各个字段的列头名称 - for (Object[] os : fields) - { - Excel excel = (Excel) os[1]; - this.createCell(excel, row, column++); - } - if (Type.EXPORT.equals(type)) - { - fillExcelData(index, row); - addStatisticsRow(); - } - } - String filename = encodingFilename(sheetName); - out = new FileOutputStream(getAbsoluteFile(filename)); - wb.write(out); - return AjaxResult.success(filename); - } - catch (Exception e) - { - log.error("导出Excel异常{}", e.getMessage()); - throw new CustomException("导出Excel失败,请联系网站管理员!"); - } - finally - { - if (wb != null) - { - try - { - wb.close(); - } - catch (IOException e1) - { - e1.printStackTrace(); - } - } - if (out != null) - { - try - { - out.close(); - } - catch (IOException e1) - { - e1.printStackTrace(); - } - } - } - } - - /** - * 填充excel数据 - * - * @param index 序号 - * @param row 单元格行 - */ - public void fillExcelData(int index, Row row) - { - int startNo = index * sheetSize; - int endNo = Math.min(startNo + sheetSize, list.size()); - for (int i = startNo; i < endNo; i++) - { - row = sheet.createRow(i + 1 - startNo); - // 得到导出对象. - T vo = (T) list.get(i); - int column = 0; - for (Object[] os : fields) - { - Field field = (Field) os[0]; - Excel excel = (Excel) os[1]; - // 设置实体类私有属性可访问 - field.setAccessible(true); - this.addCell(excel, row, vo, field, column++); - } - } - } - - /** - * 创建表格样式 - * - * @param wb 工作薄对象 - * @return 样式列表 - */ - private Map createStyles(Workbook wb) - { - // 写入各条记录,每条记录对应excel表中的一行 - Map styles = new HashMap(); - CellStyle style = wb.createCellStyle(); - style.setAlignment(HorizontalAlignment.CENTER); - style.setVerticalAlignment(VerticalAlignment.CENTER); - style.setBorderRight(BorderStyle.THIN); - style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex()); - style.setBorderLeft(BorderStyle.THIN); - style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex()); - style.setBorderTop(BorderStyle.THIN); - style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex()); - style.setBorderBottom(BorderStyle.THIN); - style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex()); - Font dataFont = wb.createFont(); - dataFont.setFontName("Arial"); - dataFont.setFontHeightInPoints((short) 10); - style.setFont(dataFont); - styles.put("data", style); - - style = wb.createCellStyle(); - style.cloneStyleFrom(styles.get("data")); - style.setAlignment(HorizontalAlignment.CENTER); - style.setVerticalAlignment(VerticalAlignment.CENTER); - style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex()); - style.setFillPattern(FillPatternType.SOLID_FOREGROUND); - Font headerFont = wb.createFont(); - headerFont.setFontName("Arial"); - headerFont.setFontHeightInPoints((short) 10); - headerFont.setBold(true); - headerFont.setColor(IndexedColors.WHITE.getIndex()); - style.setFont(headerFont); - styles.put("header", style); - - style = wb.createCellStyle(); - style.setAlignment(HorizontalAlignment.CENTER); - style.setVerticalAlignment(VerticalAlignment.CENTER); - Font totalFont = wb.createFont(); - totalFont.setFontName("Arial"); - totalFont.setFontHeightInPoints((short) 10); - style.setFont(totalFont); - styles.put("total", style); - - style = wb.createCellStyle(); - style.cloneStyleFrom(styles.get("data")); - style.setAlignment(HorizontalAlignment.LEFT); - styles.put("data1", style); - - style = wb.createCellStyle(); - style.cloneStyleFrom(styles.get("data")); - style.setAlignment(HorizontalAlignment.CENTER); - styles.put("data2", style); - - style = wb.createCellStyle(); - style.cloneStyleFrom(styles.get("data")); - style.setAlignment(HorizontalAlignment.RIGHT); - styles.put("data3", style); - - return styles; - } - - /** - * 创建单元格 - */ - public Cell createCell(Excel attr, Row row, int column) - { - // 创建列 - Cell cell = row.createCell(column); - // 写入列信息 - cell.setCellValue(attr.name()); - setDataValidation(attr, row, column); - cell.setCellStyle(styles.get("header")); - return cell; - } - - /** - * 设置单元格信息 - * - * @param value 单元格值 - * @param attr 注解相关 - * @param cell 单元格信息 - */ - public void setCellVo(Object value, Excel attr, Cell cell) - { - if (ColumnType.STRING == attr.cellType()) - { - cell.setCellValue(Validator.isNull(value) ? attr.defaultValue() : value + attr.suffix()); - } - else if (ColumnType.NUMERIC == attr.cellType()) - { - if (Validator.isNotNull(value)) - { - cell.setCellValue(StrUtil.contains(Convert.toStr(value), ".") ? Convert.toDouble(value) : Convert.toInt(value)); - } - } - else if (ColumnType.IMAGE == attr.cellType()) - { - ClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, (short) cell.getColumnIndex(), cell.getRow().getRowNum(), (short) (cell.getColumnIndex() + 1), - cell.getRow().getRowNum() + 1); - String imagePath = Convert.toStr(value); - if (Validator.isNotEmpty(imagePath)) - { - byte[] data = ImageUtils.getImage(imagePath); - getDrawingPatriarch(cell.getSheet()).createPicture(anchor, - cell.getSheet().getWorkbook().addPicture(data, getImageType(data))); - } - } - } - - /** - * 获取画布 - */ - public static Drawing getDrawingPatriarch(Sheet sheet) - { - if (sheet.getDrawingPatriarch() == null) - { - sheet.createDrawingPatriarch(); - } - return sheet.getDrawingPatriarch(); - } - - /** - * 获取图片类型,设置图片插入类型 - */ - public int getImageType(byte[] value) - { - String type = FileTypeUtils.getFileExtendName(value); - if ("JPG".equalsIgnoreCase(type)) - { - return Workbook.PICTURE_TYPE_JPEG; - } - else if ("PNG".equalsIgnoreCase(type)) - { - return Workbook.PICTURE_TYPE_PNG; - } - return Workbook.PICTURE_TYPE_JPEG; - } - - /** - * 创建表格样式 - */ - public void setDataValidation(Excel attr, Row row, int column) - { - if (attr.name().indexOf("注:") >= 0) - { - sheet.setColumnWidth(column, 6000); - } - else - { - // 设置列宽 - sheet.setColumnWidth(column, (int) ((attr.width() + 0.72) * 256)); - } - // 如果设置了提示信息则鼠标放上去提示. - if (Validator.isNotEmpty(attr.prompt())) - { - // 这里默认设了2-101列提示. - setXSSFPrompt(sheet, "", attr.prompt(), 1, 100, column, column); - } - // 如果设置了combo属性则本列只能选择不能输入 - if (attr.combo().length > 0) - { - // 这里默认设了2-101列只能选择不能输入. - setXSSFValidation(sheet, attr.combo(), 1, 100, column, column); - } - } - - /** - * 添加单元格 - */ - public Cell addCell(Excel attr, Row row, T vo, Field field, int column) - { - Cell cell = null; - try - { - // 设置行高 - row.setHeight(maxHeight); - // 根据Excel中设置情况决定是否导出,有些情况需要保持为空,希望用户填写这一列. - if (attr.isExport()) - { - // 创建cell - cell = row.createCell(column); - int align = attr.align().value(); - cell.setCellStyle(styles.get("data" + (align >= 1 && align <= 3 ? align : ""))); - - // 用于读取对象中的属性 - Object value = getTargetValue(vo, field, attr); - String dateFormat = attr.dateFormat(); - String readConverterExp = attr.readConverterExp(); - String separator = attr.separator(); - String dictType = attr.dictType(); - if (Validator.isNotEmpty(dateFormat) && Validator.isNotNull(value)) - { - cell.setCellValue(DateUtils.parseDateToStr(dateFormat, (Date) value)); - } - else if (Validator.isNotEmpty(readConverterExp) && Validator.isNotNull(value)) - { - cell.setCellValue(convertByExp(Convert.toStr(value), readConverterExp, separator)); - } - else if (Validator.isNotEmpty(dictType) && Validator.isNotNull(value)) - { - cell.setCellValue(convertDictByExp(Convert.toStr(value), dictType, separator)); - } - else if (value instanceof BigDecimal && -1 != attr.scale()) - { - cell.setCellValue((((BigDecimal) value).setScale(attr.scale(), attr.roundingMode())).toString()); - } - else - { - // 设置列类型 - setCellVo(value, attr, cell); - } - addStatisticsData(column, Convert.toStr(value), attr); - } - } - catch (Exception e) - { - log.error("导出Excel失败{}", e); - } - return cell; - } - - /** - * 设置 POI XSSFSheet 单元格提示 - * - * @param sheet 表单 - * @param promptTitle 提示标题 - * @param promptContent 提示内容 - * @param firstRow 开始行 - * @param endRow 结束行 - * @param firstCol 开始列 - * @param endCol 结束列 - */ - public void setXSSFPrompt(Sheet sheet, String promptTitle, String promptContent, int firstRow, int endRow, - int firstCol, int endCol) - { - DataValidationHelper helper = sheet.getDataValidationHelper(); - DataValidationConstraint constraint = helper.createCustomConstraint("DD1"); - CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol); - DataValidation dataValidation = helper.createValidation(constraint, regions); - dataValidation.createPromptBox(promptTitle, promptContent); - dataValidation.setShowPromptBox(true); - sheet.addValidationData(dataValidation); - } - - /** - * 设置某些列的值只能输入预制的数据,显示下拉框. - * - * @param sheet 要设置的sheet. - * @param textlist 下拉框显示的内容 - * @param firstRow 开始行 - * @param endRow 结束行 - * @param firstCol 开始列 - * @param endCol 结束列 - * @return 设置好的sheet. - */ - public void setXSSFValidation(Sheet sheet, String[] textlist, int firstRow, int endRow, int firstCol, int endCol) - { - DataValidationHelper helper = sheet.getDataValidationHelper(); - // 加载下拉列表内容 - DataValidationConstraint constraint = helper.createExplicitListConstraint(textlist); - // 设置数据有效性加载在哪个单元格上,四个参数分别是:起始行、终止行、起始列、终止列 - CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol); - // 数据有效性对象 - DataValidation dataValidation = helper.createValidation(constraint, regions); - // 处理Excel兼容性问题 - if (dataValidation instanceof XSSFDataValidation) - { - dataValidation.setSuppressDropDownArrow(true); - dataValidation.setShowErrorBox(true); - } - else - { - dataValidation.setSuppressDropDownArrow(false); - } - - sheet.addValidationData(dataValidation); - } - - /** - * 解析导出值 0=男,1=女,2=未知 - * - * @param propertyValue 参数值 - * @param converterExp 翻译注解 - * @param separator 分隔符 - * @return 解析后值 - */ - public static String convertByExp(String propertyValue, String converterExp, String separator) - { - StringBuilder propertyString = new StringBuilder(); - String[] convertSource = converterExp.split(","); - for (String item : convertSource) - { - String[] itemArray = item.split("="); - if (StrUtil.containsAny(separator, propertyValue)) - { - for (String value : propertyValue.split(separator)) - { - if (itemArray[0].equals(value)) - { - propertyString.append(itemArray[1] + separator); - break; - } - } - } - else - { - if (itemArray[0].equals(propertyValue)) - { - return itemArray[1]; - } - } - } - return StrUtil.strip(propertyString.toString(), null,separator); - } - - /** - * 反向解析值 男=0,女=1,未知=2 - * - * @param propertyValue 参数值 - * @param converterExp 翻译注解 - * @param separator 分隔符 - * @return 解析后值 - */ - public static String reverseByExp(String propertyValue, String converterExp, String separator) - { - StringBuilder propertyString = new StringBuilder(); - String[] convertSource = converterExp.split(","); - for (String item : convertSource) - { - String[] itemArray = item.split("="); - if (StrUtil.containsAny(separator, propertyValue)) - { - for (String value : propertyValue.split(separator)) - { - if (itemArray[1].equals(value)) - { - propertyString.append(itemArray[0] + separator); - break; - } - } - } - else - { - if (itemArray[1].equals(propertyValue)) - { - return itemArray[0]; - } - } - } - return StrUtil.strip(propertyString.toString(), null,separator); - } - - /** - * 解析字典值 - * - * @param dictValue 字典值 - * @param dictType 字典类型 - * @param separator 分隔符 - * @return 字典标签 - */ - public static String convertDictByExp(String dictValue, String dictType, String separator) - { - return DictUtils.getDictLabel(dictType, dictValue, separator); - } - - /** - * 反向解析值字典值 - * - * @param dictLabel 字典标签 - * @param dictType 字典类型 - * @param separator 分隔符 - * @return 字典值 - */ - public static String reverseDictByExp(String dictLabel, String dictType, String separator) - { - return DictUtils.getDictValue(dictType, dictLabel, separator); - } - - /** - * 合计统计信息 - */ - private void addStatisticsData(Integer index, String text, Excel entity) - { - if (entity != null && entity.isStatistics()) - { - Double temp = 0D; - if (!statistics.containsKey(index)) - { - statistics.put(index, temp); - } - try - { - temp = Double.valueOf(text); - } - catch (NumberFormatException e) - { - } - statistics.put(index, statistics.get(index) + temp); - } - } - - /** - * 创建统计行 - */ - public void addStatisticsRow() - { - if (statistics.size() > 0) - { - Cell cell = null; - Row row = sheet.createRow(sheet.getLastRowNum() + 1); - Set keys = statistics.keySet(); - cell = row.createCell(0); - cell.setCellStyle(styles.get("total")); - cell.setCellValue("合计"); - - for (Integer key : keys) - { - cell = row.createCell(key); - cell.setCellStyle(styles.get("total")); - cell.setCellValue(DOUBLE_FORMAT.format(statistics.get(key))); - } - statistics.clear(); - } - } - - /** - * 编码文件名 - */ - public String encodingFilename(String filename) - { - filename = UUID.randomUUID().toString() + "_" + filename + ".xlsx"; - return filename; - } - - /** - * 获取下载路径 - * - * @param filename 文件名称 - */ - public String getAbsoluteFile(String filename) - { - String downloadPath = RuoYiConfig.getDownloadPath() + filename; - File desc = new File(downloadPath); - if (!desc.getParentFile().exists()) - { - desc.getParentFile().mkdirs(); - } - return downloadPath; - } - - /** - * 获取bean中的属性值 - * - * @param vo 实体对象 - * @param field 字段 - * @param excel 注解 - * @return 最终的属性值 - * @throws Exception - */ - private Object getTargetValue(T vo, Field field, Excel excel) throws Exception - { - Object o = field.get(vo); - if (Validator.isNotEmpty(excel.targetAttr())) - { - String target = excel.targetAttr(); - if (target.contains(".")) - { - String[] targets = target.split("[.]"); - for (String name : targets) - { - o = getValue(o, name); - } - } - else - { - o = getValue(o, target); - } - } - return o; - } - - /** - * 以类的属性的get方法方法形式获取值 - * - * @param o - * @param name - * @return value - * @throws Exception - */ - private Object getValue(Object o, String name) throws Exception - { - if (Validator.isNotNull(o) && Validator.isNotEmpty(name)) - { - Class clazz = o.getClass(); - Field field = clazz.getDeclaredField(name); - field.setAccessible(true); - o = field.get(o); - } - return o; - } - - /** - * 得到所有定义字段 - */ - private void createExcelField() - { - this.fields = new ArrayList(); - List tempFields = new ArrayList<>(); - tempFields.addAll(Arrays.asList(clazz.getSuperclass().getDeclaredFields())); - tempFields.addAll(Arrays.asList(clazz.getDeclaredFields())); - for (Field field : tempFields) - { - // 单注解 - if (field.isAnnotationPresent(Excel.class)) - { - putToField(field, field.getAnnotation(Excel.class)); - } - - // 多注解 - if (field.isAnnotationPresent(Excels.class)) - { - Excels attrs = field.getAnnotation(Excels.class); - Excel[] excels = attrs.value(); - for (Excel excel : excels) - { - putToField(field, excel); - } - } - } - this.fields = this.fields.stream().sorted(Comparator.comparing(objects -> ((Excel) objects[1]).sort())).collect(Collectors.toList()); - this.maxHeight = getRowHeight(); - } - - /** - * 根据注解获取最大行高 - */ - public short getRowHeight() - { - double maxHeight = 0; - for (Object[] os : this.fields) - { - Excel excel = (Excel) os[1]; - maxHeight = maxHeight > excel.height() ? maxHeight : excel.height(); - } - return (short) (maxHeight * 20); - } - - /** - * 放到字段集合中 - */ - private void putToField(Field field, Excel attr) - { - if (attr != null && (attr.type() == Type.ALL || attr.type() == type)) - { - this.fields.add(new Object[] { field, attr }); - } - } - - /** - * 创建一个工作簿 - */ - public void createWorkbook() - { - this.wb = new SXSSFWorkbook(500); - } - - /** - * 创建工作表 - * - * @param sheetNo sheet数量 - * @param index 序号 - */ - public void createSheet(double sheetNo, int index) - { - this.sheet = wb.createSheet(); - this.styles = createStyles(wb); - // 设置工作表的名称. - if (sheetNo == 0) - { - wb.setSheetName(index, sheetName); - } - else - { - wb.setSheetName(index, sheetName + index); - } - } - - /** - * 获取单元格值 - * - * @param row 获取的行 - * @param column 获取单元格列号 - * @return 单元格值 - */ - public Object getCellValue(Row row, int column) - { - if (row == null) - { - return row; - } - Object val = ""; - try - { - Cell cell = row.getCell(column); - if (Validator.isNotNull(cell)) - { - if (cell.getCellType() == CellType.NUMERIC || cell.getCellType() == CellType.FORMULA) - { - val = cell.getNumericCellValue(); - if (DateUtil.isCellDateFormatted(cell)) - { - val = DateUtil.getJavaDate((Double) val); // POI Excel 日期格式转换 - } - else - { - if ((Double) val % 1 != 0) - { - val = new BigDecimal(val.toString()); - } - else - { - val = new DecimalFormat("0").format(val); - } - } - } - else if (cell.getCellType() == CellType.STRING) - { - val = cell.getStringCellValue(); - } - else if (cell.getCellType() == CellType.BOOLEAN) - { - val = cell.getBooleanCellValue(); - } - else if (cell.getCellType() == CellType.ERROR) - { - val = cell.getErrorCellValue(); - } - - } - } - catch (Exception e) - { - return val; - } - return val; - } -} \ No newline at end of file +package com.ruoyi.common.utils.poi; + +import cn.hutool.core.convert.Convert; +import cn.hutool.core.lang.Validator; +import cn.hutool.core.util.StrUtil; +import com.ruoyi.common.annotation.Excel; +import com.ruoyi.common.annotation.Excel.ColumnType; +import com.ruoyi.common.annotation.Excel.Type; +import com.ruoyi.common.annotation.Excels; +import com.ruoyi.common.config.RuoYiConfig; +import com.ruoyi.common.core.domain.AjaxResult; +import com.ruoyi.common.exception.CustomException; +import com.ruoyi.common.utils.DateUtils; +import com.ruoyi.common.utils.DictUtils; +import com.ruoyi.common.utils.file.FileTypeUtils; +import com.ruoyi.common.utils.file.ImageUtils; +import com.ruoyi.common.utils.reflect.ReflectUtils; +import org.apache.poi.ss.usermodel.*; +import org.apache.poi.ss.util.CellRangeAddressList; +import org.apache.poi.xssf.streaming.SXSSFWorkbook; +import org.apache.poi.xssf.usermodel.XSSFClientAnchor; +import org.apache.poi.xssf.usermodel.XSSFDataValidation; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.*; +import java.lang.reflect.Field; +import java.math.BigDecimal; +import java.text.DecimalFormat; +import java.util.*; +import java.util.stream.Collectors; + +/** + * Excel相关处理 + * + * @author ruoyi + */ +public class ExcelUtil +{ + private static final Logger log = LoggerFactory.getLogger(ExcelUtil.class); + + /** + * Excel sheet最大行数,默认65536 + */ + public static final int sheetSize = 65536; + + /** + * 工作表名称 + */ + private String sheetName; + + /** + * 导出类型(EXPORT:导出数据;IMPORT:导入模板) + */ + private Type type; + + /** + * 工作薄对象 + */ + private Workbook wb; + + /** + * 工作表对象 + */ + private Sheet sheet; + + /** + * 样式列表 + */ + private Map styles; + + /** + * 导入导出数据列表 + */ + private List list; + + /** + * 注解列表 + */ + private List fields; + + /** + * 最大高度 + */ + private short maxHeight; + + /** + * 统计列表 + */ + private Map statistics = new HashMap(); + + /** + * 数字格式 + */ + private static final DecimalFormat DOUBLE_FORMAT = new DecimalFormat("######0.00"); + + /** + * 实体对象 + */ + public Class clazz; + + public ExcelUtil(Class clazz) + { + this.clazz = clazz; + } + + public void init(List list, String sheetName, Type type) + { + if (list == null) + { + list = new ArrayList(); + } + this.list = list; + this.sheetName = sheetName; + this.type = type; + createExcelField(); + createWorkbook(); + } + + /** + * 对excel表单默认第一个索引名转换成list + * + * @param is 输入流 + * @return 转换后集合 + */ + public List importExcel(InputStream is) throws Exception + { + return importExcel(StrUtil.EMPTY, is); + } + + /** + * 对excel表单指定表格索引名转换成list + * + * @param sheetName 表格索引名 + * @param is 输入流 + * @return 转换后集合 + */ + public List importExcel(String sheetName, InputStream is) throws Exception + { + this.type = Type.IMPORT; + this.wb = WorkbookFactory.create(is); + List list = new ArrayList(); + Sheet sheet = null; + if (Validator.isNotEmpty(sheetName)) + { + // 如果指定sheet名,则取指定sheet中的内容. + sheet = wb.getSheet(sheetName); + } + else + { + // 如果传入的sheet名不存在则默认指向第1个sheet. + sheet = wb.getSheetAt(0); + } + + if (sheet == null) + { + throw new IOException("文件sheet不存在"); + } + + int rows = sheet.getPhysicalNumberOfRows(); + + if (rows > 0) + { + // 定义一个map用于存放excel列的序号和field. + Map cellMap = new HashMap(); + // 获取表头 + Row heard = sheet.getRow(0); + for (int i = 0; i < heard.getPhysicalNumberOfCells(); i++) + { + Cell cell = heard.getCell(i); + if (Validator.isNotNull(cell)) + { + String value = this.getCellValue(heard, i).toString(); + cellMap.put(value, i); + } + else + { + cellMap.put(null, i); + } + } + // 有数据时才处理 得到类的所有field. + Field[] allFields = clazz.getDeclaredFields(); + // 定义一个map用于存放列的序号和field. + Map fieldsMap = new HashMap(); + for (int col = 0; col < allFields.length; col++) + { + Field field = allFields[col]; + Excel attr = field.getAnnotation(Excel.class); + if (attr != null && (attr.type() == Type.ALL || attr.type() == type)) + { + // 设置类的私有字段属性可访问. + field.setAccessible(true); + Integer column = cellMap.get(attr.name()); + if (column != null) + { + fieldsMap.put(column, field); + } + } + } + for (int i = 1; i < rows; i++) + { + // 从第2行开始取数据,默认第一行是表头. + Row row = sheet.getRow(i); + if(row == null) + { + continue; + } + T entity = null; + for (Map.Entry entry : fieldsMap.entrySet()) + { + Object val = this.getCellValue(row, entry.getKey()); + + // 如果不存在实例则新建. + entity = (entity == null ? clazz.newInstance() : entity); + // 从map中得到对应列的field. + Field field = fieldsMap.get(entry.getKey()); + // 取得类型,并根据对象类型设置值. + Class fieldType = field.getType(); + if (String.class == fieldType) + { + String s = Convert.toStr(val); + if (StrUtil.endWith(s, ".0")) + { + val = StrUtil.subBefore(s, ".0",false); + } + else + { + String dateFormat = field.getAnnotation(Excel.class).dateFormat(); + if (Validator.isNotEmpty(dateFormat)) + { + val = DateUtils.parseDateToStr(dateFormat, (Date) val); + } + else + { + val = Convert.toStr(val); + } + } + } + else if ((Integer.TYPE == fieldType || Integer.class == fieldType) && Validator.isNumber(Convert.toStr(val))) + { + val = Convert.toInt(val); + } + else if (Long.TYPE == fieldType || Long.class == fieldType) + { + val = Convert.toLong(val); + } + else if (Double.TYPE == fieldType || Double.class == fieldType) + { + val = Convert.toDouble(val); + } + else if (Float.TYPE == fieldType || Float.class == fieldType) + { + val = Convert.toFloat(val); + } + else if (BigDecimal.class == fieldType) + { + val = Convert.toBigDecimal(val); + } + else if (Date.class == fieldType) + { + if (val instanceof String) + { + val = DateUtils.parseDate(val); + } + else if (val instanceof Double) + { + val = DateUtil.getJavaDate((Double) val); + } + } + else if (Boolean.TYPE == fieldType || Boolean.class == fieldType) + { + val = Convert.toBool(val, false); + } + if (Validator.isNotNull(fieldType)) + { + Excel attr = field.getAnnotation(Excel.class); + String propertyName = field.getName(); + if (Validator.isNotEmpty(attr.targetAttr())) + { + propertyName = field.getName() + "." + attr.targetAttr(); + } + else if (Validator.isNotEmpty(attr.readConverterExp())) + { + val = reverseByExp(Convert.toStr(val), attr.readConverterExp(), attr.separator()); + } + else if (Validator.isNotEmpty(attr.dictType())) + { + val = reverseDictByExp(Convert.toStr(val), attr.dictType(), attr.separator()); + } + ReflectUtils.invokeSetter(entity, propertyName, val); + } + } + list.add(entity); + } + } + return list; + } + + /** + * 对list数据源将其里面的数据导入到excel表单 + * + * @param list 导出数据集合 + * @param sheetName 工作表的名称 + * @return 结果 + */ + public AjaxResult exportExcel(List list, String sheetName) + { + this.init(list, sheetName, Type.EXPORT); + return exportExcel(); + } + + /** + * 对list数据源将其里面的数据导入到excel表单 + * + * @param sheetName 工作表的名称 + * @return 结果 + */ + public AjaxResult importTemplateExcel(String sheetName) + { + this.init(null, sheetName, Type.IMPORT); + return exportExcel(); + } + + /** + * 对list数据源将其里面的数据导入到excel表单 + * + * @return 结果 + */ + public AjaxResult exportExcel() + { + OutputStream out = null; + try + { + // 取出一共有多少个sheet. + double sheetNo = Math.ceil(list.size() / sheetSize); + for (int index = 0; index <= sheetNo; index++) + { + createSheet(sheetNo, index); + + // 产生一行 + Row row = sheet.createRow(0); + int column = 0; + // 写入各个字段的列头名称 + for (Object[] os : fields) + { + Excel excel = (Excel) os[1]; + this.createCell(excel, row, column++); + } + if (Type.EXPORT.equals(type)) + { + fillExcelData(index, row); + addStatisticsRow(); + } + } + String filename = encodingFilename(sheetName); + out = new FileOutputStream(getAbsoluteFile(filename)); + wb.write(out); + return AjaxResult.success(filename); + } + catch (Exception e) + { + log.error("导出Excel异常{}", e.getMessage()); + throw new CustomException("导出Excel失败,请联系网站管理员!"); + } + finally + { + if (wb != null) + { + try + { + wb.close(); + } + catch (IOException e1) + { + e1.printStackTrace(); + } + } + if (out != null) + { + try + { + out.close(); + } + catch (IOException e1) + { + e1.printStackTrace(); + } + } + } + } + + /** + * 填充excel数据 + * + * @param index 序号 + * @param row 单元格行 + */ + public void fillExcelData(int index, Row row) + { + int startNo = index * sheetSize; + int endNo = Math.min(startNo + sheetSize, list.size()); + for (int i = startNo; i < endNo; i++) + { + row = sheet.createRow(i + 1 - startNo); + // 得到导出对象. + T vo = (T) list.get(i); + int column = 0; + for (Object[] os : fields) + { + Field field = (Field) os[0]; + Excel excel = (Excel) os[1]; + // 设置实体类私有属性可访问 + field.setAccessible(true); + this.addCell(excel, row, vo, field, column++); + } + } + } + + /** + * 创建表格样式 + * + * @param wb 工作薄对象 + * @return 样式列表 + */ + private Map createStyles(Workbook wb) + { + // 写入各条记录,每条记录对应excel表中的一行 + Map styles = new HashMap(); + CellStyle style = wb.createCellStyle(); + style.setAlignment(HorizontalAlignment.CENTER); + style.setVerticalAlignment(VerticalAlignment.CENTER); + style.setBorderRight(BorderStyle.THIN); + style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex()); + style.setBorderLeft(BorderStyle.THIN); + style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex()); + style.setBorderTop(BorderStyle.THIN); + style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex()); + style.setBorderBottom(BorderStyle.THIN); + style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex()); + Font dataFont = wb.createFont(); + dataFont.setFontName("Arial"); + dataFont.setFontHeightInPoints((short) 10); + style.setFont(dataFont); + styles.put("data", style); + + style = wb.createCellStyle(); + style.cloneStyleFrom(styles.get("data")); + style.setAlignment(HorizontalAlignment.CENTER); + style.setVerticalAlignment(VerticalAlignment.CENTER); + style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex()); + style.setFillPattern(FillPatternType.SOLID_FOREGROUND); + Font headerFont = wb.createFont(); + headerFont.setFontName("Arial"); + headerFont.setFontHeightInPoints((short) 10); + headerFont.setBold(true); + headerFont.setColor(IndexedColors.WHITE.getIndex()); + style.setFont(headerFont); + styles.put("header", style); + + style = wb.createCellStyle(); + style.setAlignment(HorizontalAlignment.CENTER); + style.setVerticalAlignment(VerticalAlignment.CENTER); + Font totalFont = wb.createFont(); + totalFont.setFontName("Arial"); + totalFont.setFontHeightInPoints((short) 10); + style.setFont(totalFont); + styles.put("total", style); + + style = wb.createCellStyle(); + style.cloneStyleFrom(styles.get("data")); + style.setAlignment(HorizontalAlignment.LEFT); + styles.put("data1", style); + + style = wb.createCellStyle(); + style.cloneStyleFrom(styles.get("data")); + style.setAlignment(HorizontalAlignment.CENTER); + styles.put("data2", style); + + style = wb.createCellStyle(); + style.cloneStyleFrom(styles.get("data")); + style.setAlignment(HorizontalAlignment.RIGHT); + styles.put("data3", style); + + return styles; + } + + /** + * 创建单元格 + */ + public Cell createCell(Excel attr, Row row, int column) + { + // 创建列 + Cell cell = row.createCell(column); + // 写入列信息 + cell.setCellValue(attr.name()); + setDataValidation(attr, row, column); + cell.setCellStyle(styles.get("header")); + return cell; + } + + /** + * 设置单元格信息 + * + * @param value 单元格值 + * @param attr 注解相关 + * @param cell 单元格信息 + */ + public void setCellVo(Object value, Excel attr, Cell cell) + { + if (ColumnType.STRING == attr.cellType()) + { + cell.setCellValue(Validator.isNull(value) ? attr.defaultValue() : value + attr.suffix()); + } + else if (ColumnType.NUMERIC == attr.cellType()) + { + if (Validator.isNotNull(value)) + { + cell.setCellValue(StrUtil.contains(Convert.toStr(value), ".") ? Convert.toDouble(value) : Convert.toInt(value)); + } + } + else if (ColumnType.IMAGE == attr.cellType()) + { + ClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, (short) cell.getColumnIndex(), cell.getRow().getRowNum(), (short) (cell.getColumnIndex() + 1), + cell.getRow().getRowNum() + 1); + String imagePath = Convert.toStr(value); + if (Validator.isNotEmpty(imagePath)) + { + byte[] data = ImageUtils.getImage(imagePath); + getDrawingPatriarch(cell.getSheet()).createPicture(anchor, + cell.getSheet().getWorkbook().addPicture(data, getImageType(data))); + } + } + } + + /** + * 获取画布 + */ + public static Drawing getDrawingPatriarch(Sheet sheet) + { + if (sheet.getDrawingPatriarch() == null) + { + sheet.createDrawingPatriarch(); + } + return sheet.getDrawingPatriarch(); + } + + /** + * 获取图片类型,设置图片插入类型 + */ + public int getImageType(byte[] value) + { + String type = FileTypeUtils.getFileExtendName(value); + if ("JPG".equalsIgnoreCase(type)) + { + return Workbook.PICTURE_TYPE_JPEG; + } + else if ("PNG".equalsIgnoreCase(type)) + { + return Workbook.PICTURE_TYPE_PNG; + } + return Workbook.PICTURE_TYPE_JPEG; + } + + /** + * 创建表格样式 + */ + public void setDataValidation(Excel attr, Row row, int column) + { + if (attr.name().indexOf("注:") >= 0) + { + sheet.setColumnWidth(column, 6000); + } + else + { + // 设置列宽 + sheet.setColumnWidth(column, (int) ((attr.width() + 0.72) * 256)); + } + // 如果设置了提示信息则鼠标放上去提示. + if (Validator.isNotEmpty(attr.prompt())) + { + // 这里默认设了2-101列提示. + setXSSFPrompt(sheet, "", attr.prompt(), 1, 100, column, column); + } + // 如果设置了combo属性则本列只能选择不能输入 + if (attr.combo().length > 0) + { + // 这里默认设了2-101列只能选择不能输入. + setXSSFValidation(sheet, attr.combo(), 1, 100, column, column); + } + } + + /** + * 添加单元格 + */ + public Cell addCell(Excel attr, Row row, T vo, Field field, int column) + { + Cell cell = null; + try + { + // 设置行高 + row.setHeight(maxHeight); + // 根据Excel中设置情况决定是否导出,有些情况需要保持为空,希望用户填写这一列. + if (attr.isExport()) + { + // 创建cell + cell = row.createCell(column); + int align = attr.align().value(); + cell.setCellStyle(styles.get("data" + (align >= 1 && align <= 3 ? align : ""))); + + // 用于读取对象中的属性 + Object value = getTargetValue(vo, field, attr); + String dateFormat = attr.dateFormat(); + String readConverterExp = attr.readConverterExp(); + String separator = attr.separator(); + String dictType = attr.dictType(); + if (Validator.isNotEmpty(dateFormat) && Validator.isNotNull(value)) + { + cell.setCellValue(DateUtils.parseDateToStr(dateFormat, (Date) value)); + } + else if (Validator.isNotEmpty(readConverterExp) && Validator.isNotNull(value)) + { + cell.setCellValue(convertByExp(Convert.toStr(value), readConverterExp, separator)); + } + else if (Validator.isNotEmpty(dictType) && Validator.isNotNull(value)) + { + cell.setCellValue(convertDictByExp(Convert.toStr(value), dictType, separator)); + } + else if (value instanceof BigDecimal && -1 != attr.scale()) + { + cell.setCellValue((((BigDecimal) value).setScale(attr.scale(), attr.roundingMode())).toString()); + } + else + { + // 设置列类型 + setCellVo(value, attr, cell); + } + addStatisticsData(column, Convert.toStr(value), attr); + } + } + catch (Exception e) + { + log.error("导出Excel失败{}", e); + } + return cell; + } + + /** + * 设置 POI XSSFSheet 单元格提示 + * + * @param sheet 表单 + * @param promptTitle 提示标题 + * @param promptContent 提示内容 + * @param firstRow 开始行 + * @param endRow 结束行 + * @param firstCol 开始列 + * @param endCol 结束列 + */ + public void setXSSFPrompt(Sheet sheet, String promptTitle, String promptContent, int firstRow, int endRow, + int firstCol, int endCol) + { + DataValidationHelper helper = sheet.getDataValidationHelper(); + DataValidationConstraint constraint = helper.createCustomConstraint("DD1"); + CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol); + DataValidation dataValidation = helper.createValidation(constraint, regions); + dataValidation.createPromptBox(promptTitle, promptContent); + dataValidation.setShowPromptBox(true); + sheet.addValidationData(dataValidation); + } + + /** + * 设置某些列的值只能输入预制的数据,显示下拉框. + * + * @param sheet 要设置的sheet. + * @param textlist 下拉框显示的内容 + * @param firstRow 开始行 + * @param endRow 结束行 + * @param firstCol 开始列 + * @param endCol 结束列 + * @return 设置好的sheet. + */ + public void setXSSFValidation(Sheet sheet, String[] textlist, int firstRow, int endRow, int firstCol, int endCol) + { + DataValidationHelper helper = sheet.getDataValidationHelper(); + // 加载下拉列表内容 + DataValidationConstraint constraint = helper.createExplicitListConstraint(textlist); + // 设置数据有效性加载在哪个单元格上,四个参数分别是:起始行、终止行、起始列、终止列 + CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol); + // 数据有效性对象 + DataValidation dataValidation = helper.createValidation(constraint, regions); + // 处理Excel兼容性问题 + if (dataValidation instanceof XSSFDataValidation) + { + dataValidation.setSuppressDropDownArrow(true); + dataValidation.setShowErrorBox(true); + } + else + { + dataValidation.setSuppressDropDownArrow(false); + } + + sheet.addValidationData(dataValidation); + } + + /** + * 解析导出值 0=男,1=女,2=未知 + * + * @param propertyValue 参数值 + * @param converterExp 翻译注解 + * @param separator 分隔符 + * @return 解析后值 + */ + public static String convertByExp(String propertyValue, String converterExp, String separator) + { + StringBuilder propertyString = new StringBuilder(); + String[] convertSource = converterExp.split(","); + for (String item : convertSource) + { + String[] itemArray = item.split("="); + if (StrUtil.containsAny(propertyValue, separator)) + { + for (String value : propertyValue.split(separator)) + { + if (itemArray[0].equals(value)) + { + propertyString.append(itemArray[1] + separator); + break; + } + } + } + else + { + if (itemArray[0].equals(propertyValue)) + { + return itemArray[1]; + } + } + } + return StrUtil.strip(propertyString.toString(), null,separator); + } + + /** + * 反向解析值 男=0,女=1,未知=2 + * + * @param propertyValue 参数值 + * @param converterExp 翻译注解 + * @param separator 分隔符 + * @return 解析后值 + */ + public static String reverseByExp(String propertyValue, String converterExp, String separator) + { + StringBuilder propertyString = new StringBuilder(); + String[] convertSource = converterExp.split(","); + for (String item : convertSource) + { + String[] itemArray = item.split("="); + if (StrUtil.containsAny(propertyValue, separator)) + { + for (String value : propertyValue.split(separator)) + { + if (itemArray[1].equals(value)) + { + propertyString.append(itemArray[0] + separator); + break; + } + } + } + else + { + if (itemArray[1].equals(propertyValue)) + { + return itemArray[0]; + } + } + } + return StrUtil.strip(propertyString.toString(), null,separator); + } + + /** + * 解析字典值 + * + * @param dictValue 字典值 + * @param dictType 字典类型 + * @param separator 分隔符 + * @return 字典标签 + */ + public static String convertDictByExp(String dictValue, String dictType, String separator) + { + return DictUtils.getDictLabel(dictType, dictValue, separator); + } + + /** + * 反向解析值字典值 + * + * @param dictLabel 字典标签 + * @param dictType 字典类型 + * @param separator 分隔符 + * @return 字典值 + */ + public static String reverseDictByExp(String dictLabel, String dictType, String separator) + { + return DictUtils.getDictValue(dictType, dictLabel, separator); + } + + /** + * 合计统计信息 + */ + private void addStatisticsData(Integer index, String text, Excel entity) + { + if (entity != null && entity.isStatistics()) + { + Double temp = 0D; + if (!statistics.containsKey(index)) + { + statistics.put(index, temp); + } + try + { + temp = Double.valueOf(text); + } + catch (NumberFormatException e) + { + } + statistics.put(index, statistics.get(index) + temp); + } + } + + /** + * 创建统计行 + */ + public void addStatisticsRow() + { + if (statistics.size() > 0) + { + Cell cell = null; + Row row = sheet.createRow(sheet.getLastRowNum() + 1); + Set keys = statistics.keySet(); + cell = row.createCell(0); + cell.setCellStyle(styles.get("total")); + cell.setCellValue("合计"); + + for (Integer key : keys) + { + cell = row.createCell(key); + cell.setCellStyle(styles.get("total")); + cell.setCellValue(DOUBLE_FORMAT.format(statistics.get(key))); + } + statistics.clear(); + } + } + + /** + * 编码文件名 + */ + public String encodingFilename(String filename) + { + filename = UUID.randomUUID().toString() + "_" + filename + ".xlsx"; + return filename; + } + + /** + * 获取下载路径 + * + * @param filename 文件名称 + */ + public String getAbsoluteFile(String filename) + { + String downloadPath = RuoYiConfig.getDownloadPath() + filename; + File desc = new File(downloadPath); + if (!desc.getParentFile().exists()) + { + desc.getParentFile().mkdirs(); + } + return downloadPath; + } + + /** + * 获取bean中的属性值 + * + * @param vo 实体对象 + * @param field 字段 + * @param excel 注解 + * @return 最终的属性值 + * @throws Exception + */ + private Object getTargetValue(T vo, Field field, Excel excel) throws Exception + { + Object o = field.get(vo); + if (Validator.isNotEmpty(excel.targetAttr())) + { + String target = excel.targetAttr(); + if (target.contains(".")) + { + String[] targets = target.split("[.]"); + for (String name : targets) + { + o = getValue(o, name); + } + } + else + { + o = getValue(o, target); + } + } + return o; + } + + /** + * 以类的属性的get方法方法形式获取值 + * + * @param o + * @param name + * @return value + * @throws Exception + */ + private Object getValue(Object o, String name) throws Exception + { + if (Validator.isNotNull(o) && Validator.isNotEmpty(name)) + { + Class clazz = o.getClass(); + Field field = clazz.getDeclaredField(name); + field.setAccessible(true); + o = field.get(o); + } + return o; + } + + /** + * 得到所有定义字段 + */ + private void createExcelField() + { + this.fields = new ArrayList(); + List tempFields = new ArrayList<>(); + tempFields.addAll(Arrays.asList(clazz.getSuperclass().getDeclaredFields())); + tempFields.addAll(Arrays.asList(clazz.getDeclaredFields())); + for (Field field : tempFields) + { + // 单注解 + if (field.isAnnotationPresent(Excel.class)) + { + putToField(field, field.getAnnotation(Excel.class)); + } + + // 多注解 + if (field.isAnnotationPresent(Excels.class)) + { + Excels attrs = field.getAnnotation(Excels.class); + Excel[] excels = attrs.value(); + for (Excel excel : excels) + { + putToField(field, excel); + } + } + } + this.fields = this.fields.stream().sorted(Comparator.comparing(objects -> ((Excel) objects[1]).sort())).collect(Collectors.toList()); + this.maxHeight = getRowHeight(); + } + + /** + * 根据注解获取最大行高 + */ + public short getRowHeight() + { + double maxHeight = 0; + for (Object[] os : this.fields) + { + Excel excel = (Excel) os[1]; + maxHeight = maxHeight > excel.height() ? maxHeight : excel.height(); + } + return (short) (maxHeight * 20); + } + + /** + * 放到字段集合中 + */ + private void putToField(Field field, Excel attr) + { + if (attr != null && (attr.type() == Type.ALL || attr.type() == type)) + { + this.fields.add(new Object[] { field, attr }); + } + } + + /** + * 创建一个工作簿 + */ + public void createWorkbook() + { + this.wb = new SXSSFWorkbook(500); + } + + /** + * 创建工作表 + * + * @param sheetNo sheet数量 + * @param index 序号 + */ + public void createSheet(double sheetNo, int index) + { + this.sheet = wb.createSheet(); + this.styles = createStyles(wb); + // 设置工作表的名称. + if (sheetNo == 0) + { + wb.setSheetName(index, sheetName); + } + else + { + wb.setSheetName(index, sheetName + index); + } + } + + /** + * 获取单元格值 + * + * @param row 获取的行 + * @param column 获取单元格列号 + * @return 单元格值 + */ + public Object getCellValue(Row row, int column) + { + if (row == null) + { + return row; + } + Object val = ""; + try + { + Cell cell = row.getCell(column); + if (Validator.isNotNull(cell)) + { + if (cell.getCellType() == CellType.NUMERIC || cell.getCellType() == CellType.FORMULA) + { + val = cell.getNumericCellValue(); + if (DateUtil.isCellDateFormatted(cell)) + { + val = DateUtil.getJavaDate((Double) val); // POI Excel 日期格式转换 + } + else + { + if ((Double) val % 1 != 0) + { + val = new BigDecimal(val.toString()); + } + else + { + val = new DecimalFormat("0").format(val); + } + } + } + else if (cell.getCellType() == CellType.STRING) + { + val = cell.getStringCellValue(); + } + else if (cell.getCellType() == CellType.BOOLEAN) + { + val = cell.getBooleanCellValue(); + } + else if (cell.getCellType() == CellType.ERROR) + { + val = cell.getErrorCellValue(); + } + + } + } + catch (Exception e) + { + return val; + } + return val; + } +} diff --git a/ruoyi-demo/pom.xml b/ruoyi-demo/pom.xml index 49049244..d3909a28 100644 --- a/ruoyi-demo/pom.xml +++ b/ruoyi-demo/pom.xml @@ -5,7 +5,7 @@ ruoyi-vue-plus com.ruoyi - ${ruoyi-vue-plus.version} + 2.5.0 4.0.0 @@ -25,4 +25,4 @@ - \ No newline at end of file + diff --git a/ruoyi-demo/src/main/java/com/ruoyi/demo/controller/RedisCacheController.java b/ruoyi-demo/src/main/java/com/ruoyi/demo/controller/RedisCacheController.java new file mode 100644 index 00000000..4588f138 --- /dev/null +++ b/ruoyi-demo/src/main/java/com/ruoyi/demo/controller/RedisCacheController.java @@ -0,0 +1,70 @@ +package com.ruoyi.demo.controller; + +import com.ruoyi.common.core.domain.AjaxResult; +import lombok.RequiredArgsConstructor; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cache.annotation.CacheEvict; +import org.springframework.cache.annotation.CachePut; +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; + +/** + * spring-cache 演示案例 + * + * @author Lion Li + */ +// 类级别 缓存统一配置 +//@CacheConfig(cacheNames = "redissonCacheMap") +@RequiredArgsConstructor(onConstructor_ = @Autowired) +@RestController +@RequestMapping("/demo/cache") +public class RedisCacheController { + + /** + * 测试 @Cacheable + * + * 表示这个方法有了缓存的功能,方法的返回值会被缓存下来 + * 下一次调用该方法前,会去检查是否缓存中已经有值 + * 如果有就直接返回,不调用方法 + * 如果没有,就调用方法,然后把结果缓存起来 + * 这个注解「一般用在查询方法上」 + * + * cacheNames 为配置文件内 groupId + */ + @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 + */ + @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 + */ + @CacheEvict(cacheNames = "redissonCacheMap", key = "#key", condition = "#key != null") + @GetMapping("/test3") + public AjaxResult test3(String key, String value){ + return AjaxResult.success("操作成功", value); + } + +} diff --git a/ruoyi-demo/src/main/java/com/ruoyi/demo/feign/fallback/FeignTestFallback.java b/ruoyi-demo/src/main/java/com/ruoyi/demo/feign/fallback/FeignTestFallback.java index 3b4dfd0c..0f9e4002 100644 --- a/ruoyi-demo/src/main/java/com/ruoyi/demo/feign/fallback/FeignTestFallback.java +++ b/ruoyi-demo/src/main/java/com/ruoyi/demo/feign/fallback/FeignTestFallback.java @@ -7,7 +7,10 @@ import org.springframework.stereotype.Component; /** * feign测试fallback + * 自定义封装结构体熔断 + * 需重写解码器 根据自定义实体 自行解析熔断 * + * @see {com.ruoyi.framework.config.FeignConfig#errorDecoder()} * @author Lion Li */ @Slf4j diff --git a/ruoyi-extend/pom.xml b/ruoyi-extend/pom.xml new file mode 100644 index 00000000..e71a426c --- /dev/null +++ b/ruoyi-extend/pom.xml @@ -0,0 +1,18 @@ + + + + ruoyi-vue-plus + com.ruoyi + 2.5.0 + + 4.0.0 + ruoyi-extend + pom + + + ruoyi-monitor-admin + + + diff --git a/ruoyi-extend/ruoyi-monitor-admin/Dockerfile b/ruoyi-extend/ruoyi-monitor-admin/Dockerfile new file mode 100644 index 00000000..ef551fec --- /dev/null +++ b/ruoyi-extend/ruoyi-monitor-admin/Dockerfile @@ -0,0 +1,13 @@ +FROM anapsix/alpine-java:8_server-jre_unlimited + +MAINTAINER Lion Li + +RUN mkdir -p /ruoyi/monitor + +WORKDIR /ruoyi/monitor + +EXPOSE 9090 + +ADD ./target/ruoyi-monitor-admin.jar ./app.jar + +ENTRYPOINT ["java", "-Djava.security.egd=file:/dev/./urandom", "-jar", "app.jar"] diff --git a/ruoyi-extend/ruoyi-monitor-admin/pom.xml b/ruoyi-extend/ruoyi-monitor-admin/pom.xml new file mode 100644 index 00000000..e9d48d66 --- /dev/null +++ b/ruoyi-extend/ruoyi-monitor-admin/pom.xml @@ -0,0 +1,73 @@ + + + + ruoyi-extend + com.ruoyi + 2.5.0 + + 4.0.0 + jar + ruoyi-monitor-admin + + + + + org.springframework.boot + spring-boot-starter-web + + + + + org.springframework.boot + spring-boot-starter-security + + + + de.codecentric + spring-boot-admin-starter-server + + + + + ${project.artifactId} + + + org.springframework.boot + spring-boot-maven-plugin + ${spring-boot.version} + + true + + + + + repackage + + + + + + com.spotify + docker-maven-plugin + ${docker.plugin.version} + + ${docker.namespace}/${project.artifactId}:${project.version} + ${project.basedir} + ${docker.registry.host} + ${docker.registry.url} + ${docker.registry.url} + + + / + ${project.build.directory} + ${project.build.finalName}.jar + + + + + + + + diff --git a/ruoyi-extend/ruoyi-monitor-admin/src/main/java/com/ruoyi/monitor/admin/MonitorAdminApplication.java b/ruoyi-extend/ruoyi-monitor-admin/src/main/java/com/ruoyi/monitor/admin/MonitorAdminApplication.java new file mode 100644 index 00000000..1d1cbca5 --- /dev/null +++ b/ruoyi-extend/ruoyi-monitor-admin/src/main/java/com/ruoyi/monitor/admin/MonitorAdminApplication.java @@ -0,0 +1,19 @@ +package com.ruoyi.monitor.admin; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +/** + * Admin 监控启动程序 + * + * @author Lion Li + */ +@SpringBootApplication +public class MonitorAdminApplication { + + public static void main(String[] args) { + SpringApplication.run(MonitorAdminApplication.class, args); + System.out.println("Admin 监控启动成功" ); + } + +} diff --git a/ruoyi-extend/ruoyi-monitor-admin/src/main/java/com/ruoyi/monitor/admin/config/AdminServerConfig.java b/ruoyi-extend/ruoyi-monitor-admin/src/main/java/com/ruoyi/monitor/admin/config/AdminServerConfig.java new file mode 100644 index 00000000..e2a9c51d --- /dev/null +++ b/ruoyi-extend/ruoyi-monitor-admin/src/main/java/com/ruoyi/monitor/admin/config/AdminServerConfig.java @@ -0,0 +1,31 @@ +package com.ruoyi.monitor.admin.config; + +import de.codecentric.boot.admin.server.config.EnableAdminServer; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration; +import org.springframework.boot.task.TaskExecutorBuilder; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Lazy; +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; + +import java.util.concurrent.Executor; + +/** + * springboot-admin server配置类 + * + * @author Lion Li + */ +@Configuration +@EnableAdminServer +public class AdminServerConfig { + + @Lazy + @Bean(name = TaskExecutionAutoConfiguration.APPLICATION_TASK_EXECUTOR_BEAN_NAME) + @ConditionalOnMissingBean(Executor.class) + public ThreadPoolTaskExecutor applicationTaskExecutor(TaskExecutorBuilder builder) { + return builder.build(); + } + + +} diff --git a/ruoyi-extend/ruoyi-monitor-admin/src/main/java/com/ruoyi/monitor/admin/config/SecurityConfig.java b/ruoyi-extend/ruoyi-monitor-admin/src/main/java/com/ruoyi/monitor/admin/config/SecurityConfig.java new file mode 100644 index 00000000..98834a9b --- /dev/null +++ b/ruoyi-extend/ruoyi-monitor-admin/src/main/java/com/ruoyi/monitor/admin/config/SecurityConfig.java @@ -0,0 +1,48 @@ +package com.ruoyi.monitor.admin.config; + +import de.codecentric.boot.admin.server.config.AdminServerProperties; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler; + +/** + * spring security配置 + * + * @author ruoyi + */ +@Configuration +@EnableWebSecurity +@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, proxyTargetClass = true) +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + private final String adminContextPath; + + public SecurityConfig(AdminServerProperties adminServerProperties) { + this.adminContextPath = adminServerProperties.getContextPath(); + } + + @Override + protected void configure(HttpSecurity httpSecurity) throws Exception { + SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler(); + successHandler.setTargetUrlParameter("redirectTo"); + successHandler.setDefaultTargetUrl(adminContextPath + "/"); + + httpSecurity.authorizeRequests() + //授予对所有静态资产和登录页面的公共访问权限。 + .antMatchers(adminContextPath + "/assets/**").permitAll() + .antMatchers(adminContextPath + "/login").permitAll() + //必须对每个其他请求进行身份验证 + .anyRequest().authenticated().and() + //配置登录和注销 + .formLogin().loginPage(adminContextPath + "/login") + .successHandler(successHandler).and() + .logout().logoutUrl(adminContextPath + "/logout").and() + //启用HTTP-Basic支持。这是Spring Boot Admin Client注册所必需的 + .httpBasic().and().csrf().disable() + .headers().frameOptions().disable(); + } + +} diff --git a/ruoyi-extend/ruoyi-monitor-admin/src/main/resources/application.yml b/ruoyi-extend/ruoyi-monitor-admin/src/main/resources/application.yml new file mode 100644 index 00000000..631f3e77 --- /dev/null +++ b/ruoyi-extend/ruoyi-monitor-admin/src/main/resources/application.yml @@ -0,0 +1,11 @@ +server: + port: 9090 + +spring: + security: + user: + name: ruoyi + password: 123456 + boot: + admin: + context-path: /admin diff --git a/ruoyi-framework/pom.xml b/ruoyi-framework/pom.xml index 4313ce55..e7ed9918 100644 --- a/ruoyi-framework/pom.xml +++ b/ruoyi-framework/pom.xml @@ -5,7 +5,7 @@ ruoyi-vue-plus com.ruoyi - ${ruoyi-vue-plus.version} + 2.5.0 4.0.0 diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/config/AdminServerConfig.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/config/AdminServerConfig.java deleted file mode 100644 index 59fed507..00000000 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/config/AdminServerConfig.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.ruoyi.framework.config; - -import de.codecentric.boot.admin.server.config.EnableAdminServer; -import org.springframework.beans.factory.ObjectProvider; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration; -import org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties; -import org.springframework.boot.task.TaskExecutorBuilder; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Lazy; -import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; -import org.thymeleaf.dialect.IDialect; -import org.thymeleaf.spring5.ISpringTemplateEngine; -import org.thymeleaf.spring5.SpringTemplateEngine; -import org.thymeleaf.templateresolver.ITemplateResolver; - -import java.util.Comparator; -import java.util.LinkedHashSet; -import java.util.Set; -import java.util.concurrent.Executor; -import java.util.stream.Collectors; - -/** - * springboot-admin server配置类 - * - * @author Lion Li - */ -@Configuration -@EnableAdminServer -public class AdminServerConfig { - - @Lazy - @Bean(name = TaskExecutionAutoConfiguration.APPLICATION_TASK_EXECUTOR_BEAN_NAME) - @ConditionalOnMissingBean(Executor.class) - public ThreadPoolTaskExecutor applicationTaskExecutor(TaskExecutorBuilder builder) { - return builder.build(); - } - - /** - * 解决 admin 与 项目 页面的交叉引用 将 admin 的路由放到最后 - * @param properties - * @param templateResolvers - * @param dialects - * @return - */ - @Bean - @ConditionalOnMissingBean(ISpringTemplateEngine.class) - SpringTemplateEngine templateEngine(ThymeleafProperties properties, - ObjectProvider templateResolvers, ObjectProvider dialects) { - SpringTemplateEngine engine = new SpringTemplateEngine(); - engine.setEnableSpringELCompiler(properties.isEnableSpringElCompiler()); - engine.setRenderHiddenMarkersBeforeCheckboxes(properties.isRenderHiddenMarkersBeforeCheckboxes()); - templateResolvers.orderedStream().forEach(engine::addTemplateResolver); - dialects.orderedStream().forEach(engine::addDialect); - Set templateResolvers1 = engine.getTemplateResolvers(); - templateResolvers1 = templateResolvers1.stream() - .sorted(Comparator.comparing(ITemplateResolver::getOrder)) - .collect(Collectors.toCollection(LinkedHashSet::new)); - engine.setTemplateResolvers(templateResolvers1); - return engine; - } -} diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/config/FeignConfig.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/config/FeignConfig.java index f10769bc..14db1c95 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/config/FeignConfig.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/config/FeignConfig.java @@ -54,4 +54,40 @@ public class FeignConfig { 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-framework/src/main/java/com/ruoyi/framework/config/RedisConfig.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/config/RedisConfig.java index 95c7572f..bc286574 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/config/RedisConfig.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/config/RedisConfig.java @@ -19,6 +19,7 @@ import org.springframework.context.annotation.Configuration; import java.io.IOException; import java.util.HashMap; +import java.util.List; import java.util.Map; /** @@ -78,8 +79,13 @@ public class RedisConfig extends CachingConfigurerSupport { */ @Bean public CacheManager cacheManager(RedissonClient redissonClient) { + List cacheGroup = redissonProperties.getCacheGroup(); Map config = new HashMap<>(); - config.put("redissonCacheMap", new CacheConfig(30*60*1000, 10*60*1000)); + for (RedissonProperties.CacheGroup group : cacheGroup) { + CacheConfig cacheConfig = new CacheConfig(group.getTtl(), group.getMaxIdleTime()); + cacheConfig.setMaxSize(group.getMaxSize()); + config.put(group.getGroupId(), cacheConfig); + } return new RedissonSpringCacheManager(redissonClient, config, JsonJacksonCodec.INSTANCE); } diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/config/SecurityConfig.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/config/SecurityConfig.java index 79ade787..0a8337e9 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/config/SecurityConfig.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/config/SecurityConfig.java @@ -3,7 +3,6 @@ package com.ruoyi.framework.config; import com.ruoyi.framework.security.filter.JwtAuthenticationTokenFilter; import com.ruoyi.framework.security.handle.AuthenticationEntryPointImpl; import com.ruoyi.framework.security.handle.LogoutSuccessHandlerImpl; -import de.codecentric.boot.admin.server.config.AdminServerProperties; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.http.HttpMethod; @@ -57,9 +56,6 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter @Autowired private CorsFilter corsFilter; - @Autowired - private AdminServerProperties adminServerProperties; - /** * 解决 无法直接注入 AuthenticationManager * @@ -104,12 +100,13 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter .antMatchers("/login", "/captchaImage").anonymous() .antMatchers( HttpMethod.GET, + "/", "/*.html", "/**/*.html", "/**/*.css", - "/**/*.js" + "/**/*.js", + "/profile/**" ).permitAll() - .antMatchers("/profile/**").anonymous() .antMatchers("/common/download**").anonymous() .antMatchers("/common/download/resource**").anonymous() .antMatchers("/doc.html").anonymous() @@ -117,9 +114,6 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter .antMatchers("/webjars/**").anonymous() .antMatchers("/*/api-docs").anonymous() .antMatchers("/druid/**").anonymous() - // Spring Boot Admin Server 的安全配置 - .antMatchers(adminServerProperties.getContextPath()).anonymous() - .antMatchers(adminServerProperties.getContextPath() + "/**").anonymous() // Spring Boot Actuator 的安全配置 .antMatchers("/actuator").anonymous() .antMatchers("/actuator/**").anonymous() diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/config/properties/RedissonProperties.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/config/properties/RedissonProperties.java index 99db89ef..b6e289d8 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/config/properties/RedissonProperties.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/config/properties/RedissonProperties.java @@ -2,11 +2,12 @@ package com.ruoyi.framework.config.properties; import lombok.Data; import lombok.NoArgsConstructor; -import org.redisson.client.codec.Codec; import org.redisson.config.TransportMode; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; +import java.util.List; + /** * Redisson 配置属性 * @@ -37,6 +38,11 @@ public class RedissonProperties { */ private SingleServerConfig singleServerConfig; + /** + * 缓存组 + */ + private List cacheGroup; + @Data @NoArgsConstructor public static class SingleServerConfig { @@ -98,4 +104,30 @@ public class RedissonProperties { } + @Data + @NoArgsConstructor + public static class CacheGroup { + + /** + * 组id + */ + private String groupId; + + /** + * 组过期时间 + */ + private long ttl; + + /** + * 组最大空闲时间 + */ + private long maxIdleTime; + + /** + * 组最大长度 + */ + private int maxSize; + + } + } diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/mybatisplus/CreateAndUpdateMetaObjectHandler.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/mybatisplus/CreateAndUpdateMetaObjectHandler.java index 4797a64b..2479293e 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/mybatisplus/CreateAndUpdateMetaObjectHandler.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/mybatisplus/CreateAndUpdateMetaObjectHandler.java @@ -1,6 +1,8 @@ package com.ruoyi.framework.mybatisplus; +import cn.hutool.http.HttpStatus; import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; +import com.ruoyi.common.exception.CustomException; import com.ruoyi.common.utils.SecurityUtils; import org.apache.ibatis.reflection.MetaObject; @@ -8,6 +10,7 @@ import java.util.Date; /** * MP注入处理器 + * * @author Lion Li * @date 2021/4/25 */ @@ -15,30 +18,38 @@ public class CreateAndUpdateMetaObjectHandler implements MetaObjectHandler { @Override public void insertFill(MetaObject metaObject) { - //根据属性名字设置要填充的值 - if (metaObject.hasGetter("createTime")) { - if (metaObject.getValue("createTime") == null) { - this.setFieldValByName("createTime", new Date(), metaObject); + try { + //根据属性名字设置要填充的值 + if (metaObject.hasGetter("createTime")) { + if (metaObject.getValue("createTime") == null) { + this.setFieldValByName("createTime", new Date(), metaObject); + } } - } - if (metaObject.hasGetter("createBy")) { - if (metaObject.getValue("createBy") == null) { - this.setFieldValByName("createBy", SecurityUtils.getUsername(), metaObject); + if (metaObject.hasGetter("createBy")) { + if (metaObject.getValue("createBy") == null) { + this.setFieldValByName("createBy", SecurityUtils.getUsername(), metaObject); + } } + } catch (Exception e) { + throw new CustomException("自动注入异常 => " + e.getMessage(), HttpStatus.HTTP_UNAUTHORIZED); } } @Override public void updateFill(MetaObject metaObject) { - if (metaObject.hasGetter("updateBy")) { - if (metaObject.getValue("updateBy") == null) { - this.setFieldValByName("updateBy", SecurityUtils.getUsername(), metaObject); + try { + if (metaObject.hasGetter("updateBy")) { + if (metaObject.getValue("updateBy") == null) { + this.setFieldValByName("updateBy", SecurityUtils.getUsername(), metaObject); + } } - } - if (metaObject.hasGetter("updateTime")) { - if (metaObject.getValue("updateTime") == null) { - this.setFieldValByName("updateTime", new Date(), metaObject); + if (metaObject.hasGetter("updateTime")) { + if (metaObject.getValue("updateTime") == null) { + this.setFieldValByName("updateTime", new Date(), metaObject); + } } + } catch (Exception e) { + throw new CustomException("自动注入异常 => " + e.getMessage(), HttpStatus.HTTP_UNAUTHORIZED); } } diff --git a/ruoyi-generator/pom.xml b/ruoyi-generator/pom.xml index 80737062..642dfec1 100644 --- a/ruoyi-generator/pom.xml +++ b/ruoyi-generator/pom.xml @@ -5,7 +5,7 @@ ruoyi-vue-plus com.ruoyi - ${ruoyi-vue-plus.version} + 2.5.0 4.0.0 diff --git a/ruoyi-generator/src/main/java/com/ruoyi/generator/service/GenTableServiceImpl.java b/ruoyi-generator/src/main/java/com/ruoyi/generator/service/GenTableServiceImpl.java index 4da27e87..5fcdd3b3 100644 --- a/ruoyi-generator/src/main/java/com/ruoyi/generator/service/GenTableServiceImpl.java +++ b/ruoyi-generator/src/main/java/com/ruoyi/generator/service/GenTableServiceImpl.java @@ -182,9 +182,9 @@ public class GenTableServiceImpl extends ServicePlusImpl genTableColumns = genTableColumnMapper.selectDbTableColumnsByName(tableName); for (GenTableColumn column : genTableColumns) { GenUtils.initColumnField(column, table); - genTableColumnMapper.insert(column); } - } + genTableColumnMapper.insertAll(genTableColumns); + } } } catch (Exception e) { throw new CustomException("导入失败:" + e.getMessage()); @@ -258,7 +258,7 @@ public class GenTableServiceImpl extends ServicePlusImpl templates = VelocityUtils.getTemplateList(table.getTplCategory()); for (String template : templates) { - if (!StrUtil.containsAny(template, "sql.vm", "api.js.vm", "index.vue.vm", "index-tree.vue.vm")) { + if (!StrUtil.containsAny("sql.vm", "api.js.vm", "index.vue.vm", "index-tree.vue.vm", template)) { // 渲染模板 StringWriter sw = new StringWriter(); Template tpl = Velocity.getTemplate(template, Constants.UTF8); @@ -290,9 +290,9 @@ public class GenTableServiceImpl extends ServicePlusImpl { if (!tableColumnNames.contains(column.getColumnName())) { GenUtils.initColumnField(column, table); - genTableColumnMapper.insert(column); - } - }); + } + }); + genTableColumnMapper.insertAll(tableColumns); List delColumns = tableColumns.stream().filter(column -> !dbTableColumnNames.contains(column.getColumnName())).collect(Collectors.toList()); if (CollUtil.isNotEmpty(delColumns)) { diff --git a/ruoyi-generator/src/main/resources/vm/java/mapper.java.vm b/ruoyi-generator/src/main/resources/vm/java/mapper.java.vm index 6d4f40fb..6f8ff7b9 100644 --- a/ruoyi-generator/src/main/resources/vm/java/mapper.java.vm +++ b/ruoyi-generator/src/main/resources/vm/java/mapper.java.vm @@ -11,8 +11,6 @@ import org.apache.ibatis.annotations.CacheNamespace; * @author ${author} * @date ${datetime} */ -// 如使需切换数据源 请勿使用缓存 会造成数据不一致现象 -@CacheNamespace(implementation = MybatisPlusRedisCache.class, eviction = MybatisPlusRedisCache.class) public interface ${ClassName}Mapper extends BaseMapperPlus<${ClassName}> { } diff --git a/ruoyi-generator/src/main/resources/vm/vue/index-tree.vue.vm b/ruoyi-generator/src/main/resources/vm/vue/index-tree.vue.vm index d43c2ce2..cedab30d 100644 --- a/ruoyi-generator/src/main/resources/vm/vue/index-tree.vue.vm +++ b/ruoyi-generator/src/main/resources/vm/vue/index-tree.vue.vm @@ -256,52 +256,16 @@ import { list${BusinessName}, get${BusinessName}, del${BusinessName}, add${BusinessName}, update${BusinessName}, export${BusinessName} } from "@/api/${moduleName}/${businessName}"; import Treeselect from "@riophae/vue-treeselect"; import "@riophae/vue-treeselect/dist/vue-treeselect.css"; -#foreach($column in $columns) -#if($column.insert && !$column.pk && $column.htmlType == "imageUpload") -import ImageUpload from '@/components/ImageUpload'; -#break -#end -#end -#foreach($column in $columns) -#if($column.insert && !$column.pk && $column.htmlType == "fileUpload") -import FileUpload from '@/components/FileUpload'; -#break -#end -#end -#foreach($column in $columns) -#if($column.insert && !$column.pk && $column.htmlType == "editor") -import Editor from '@/components/Editor'; -#break -#end -#end export default { name: "${BusinessName}", components: { -#foreach($column in $columns) -#if($column.insert && !$column.pk && $column.htmlType == "imageUpload") - ImageUpload, -#break -#end -#end -#foreach($column in $columns) -#if($column.insert && !$column.pk && $column.htmlType == "fileUpload") - FileUpload, -#break -#end -#end -#foreach($column in $columns) -#if($column.insert && !$column.pk && $column.htmlType == "editor") - Editor, -#break -#end -#end Treeselect }, data() { return { - //按钮loading - buttonLoading: false, + // 按钮loading + buttonLoading: false, // 遮罩层 loading: true, // 显示搜索条件 @@ -510,17 +474,19 @@ export default { #end if (this.form.${pkColumn.javaField} != null) { update${BusinessName}(this.form).then(response => { - this.buttonLoading = false; this.msgSuccess("修改成功"); this.open = false; this.getList(); + }).finally(() => { + this.buttonLoading = false; }); } else { add${BusinessName}(this.form).then(response => { - this.buttonLoading = false; this.msgSuccess("新增成功"); this.open = false; this.getList(); + }).finally(() => { + this.buttonLoading = false; }); } } diff --git a/ruoyi-generator/src/main/resources/vm/vue/index.vue.vm b/ruoyi-generator/src/main/resources/vm/vue/index.vue.vm index abc799e2..12a9a63c 100644 --- a/ruoyi-generator/src/main/resources/vm/vue/index.vue.vm +++ b/ruoyi-generator/src/main/resources/vm/vue/index.vue.vm @@ -308,51 +308,13 @@ diff --git a/ruoyi-ui/src/components/HeaderSearch/index.vue b/ruoyi-ui/src/components/HeaderSearch/index.vue index ce9f305f..c44eff56 100644 --- a/ruoyi-ui/src/components/HeaderSearch/index.vue +++ b/ruoyi-ui/src/components/HeaderSearch/index.vue @@ -70,9 +70,11 @@ export default { this.show = false }, change(val) { + const path = val.path; if(this.ishttp(val.path)) { // http(s):// 路径新窗口打开 - window.open(val.path, "_blank"); + const pindex = path.indexOf("http"); + window.open(path.substr(pindex, path.length), "_blank"); } else { this.$router.push(val.path) } diff --git a/ruoyi-ui/src/components/ImageUpload/index.vue b/ruoyi-ui/src/components/ImageUpload/index.vue index 17d30d84..f2a7402b 100644 --- a/ruoyi-ui/src/components/ImageUpload/index.vue +++ b/ruoyi-ui/src/components/ImageUpload/index.vue @@ -5,33 +5,38 @@ list-type="picture-card" :on-success="handleUploadSuccess" :before-upload="handleBeforeUpload" + :limit="limit" :on-error="handleUploadError" + :on-exceed="handleExceed" name="file" - :show-file-list="false" + :on-remove="handleRemove" + :show-file-list="true" :headers="headers" - style="display: inline-block; vertical-align: top" + :file-list="fileList" + :on-preview="handlePictureCardPreview" + :class="{hide: this.fileList.length >= this.limit}" > - -
- -
-
-
- -
-
- - - - - - -
-
-
+ - - + + +
+ 请上传 + + + 的文件 +
+ + + @@ -40,36 +45,128 @@ import { getToken } from "@/utils/auth"; export default { + props: { + value: [String, Object, Array], + // 图片数量限制 + limit: { + type: Number, + default: 5, + }, + // 大小限制(MB) + fileSize: { + type: Number, + default: 5, + }, + // 文件类型, 例如['png', 'jpg', 'jpeg'] + fileType: { + type: Array, + default: () => ["png", "jpg", "jpeg"], + }, + // 是否显示提示 + isShowTip: { + type: Boolean, + default: true + } + }, data() { return { + dialogImageUrl: "", dialogVisible: false, + hideUpload: false, + baseUrl: process.env.VUE_APP_BASE_API, uploadImgUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址 headers: { Authorization: "Bearer " + getToken(), }, + fileList: [] }; }, - props: { + watch: { value: { - type: String, - default: "", + handler(val) { + if (val) { + // 首先将值转为数组 + const list = Array.isArray(val) ? val : this.value.split(','); + // 然后将数组转为对象数组 + this.fileList = list.map(item => { + if (typeof item === "string") { + if (item.indexOf(this.baseUrl) === -1) { + item = { name: this.baseUrl + item, url: this.baseUrl + item }; + } else { + item = { name: item, url: item }; + } + } + return item; + }); + } else { + this.fileList = []; + return []; + } + }, + deep: true, + immediate: true + } + }, + computed: { + // 是否显示提示 + showTip() { + return this.isShowTip && (this.fileType || this.fileSize); }, }, methods: { - removeImage() { - this.$emit("input", ""); + // 删除图片 + handleRemove(file, fileList) { + const findex = this.fileList.indexOf(file.name); + this.fileList.splice(findex, 1); + this.$emit("input", this.listToString(this.fileList)); }, + // 上传成功回调 handleUploadSuccess(res) { - this.$emit("input", res.data.url); + this.fileList.push({ name: res.data.fileName, url: res.data.fileName }); + this.$emit("input", this.listToString(this.fileList)); this.loading.close(); }, - handleBeforeUpload() { + // 上传前loading加载 + handleBeforeUpload(file) { + let isImg = false; + if (this.fileType.length) { + let fileExtension = ""; + if (file.name.lastIndexOf(".") > -1) { + fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1); + } + isImg = this.fileType.some(type => { + if (file.type.indexOf(type) > -1) return true; + if (fileExtension && fileExtension.indexOf(type) > -1) return true; + return false; + }); + } else { + isImg = file.type.indexOf("image") > -1; + } + + if (!isImg) { + this.$message.error( + `文件格式不正确, 请上传${this.fileType.join("/")}图片格式文件!` + ); + return false; + } + if (this.fileSize) { + const isLt = file.size / 1024 / 1024 < this.fileSize; + if (!isLt) { + this.$message.error(`上传头像图片大小不能超过 ${this.fileSize} MB!`); + return false; + } + } this.loading = this.$loading({ lock: true, text: "上传中", background: "rgba(0, 0, 0, 0.7)", }); }, + // 文件个数超出 + handleExceed() { + this.$message.error(`上传文件数量不能超过 ${this.limit} 个!`); + }, + // 上传失败 handleUploadError() { this.$message({ type: "error", @@ -77,24 +174,37 @@ export default { }); this.loading.close(); }, - }, - watch: {}, + // 预览 + handlePictureCardPreview(file) { + this.dialogImageUrl = file.url; + this.dialogVisible = true; + }, + // 对象转成指定字符串分隔 + listToString(list, separator) { + let strs = ""; + separator = separator || ","; + for (let i in list) { + strs += list[i].url + separator; + } + return strs != '' ? strs.substr(0, strs.length - 1) : ''; + } + } }; - + diff --git a/ruoyi-ui/src/components/TopNav/index.vue b/ruoyi-ui/src/components/TopNav/index.vue index d89930a8..c8837f2a 100644 --- a/ruoyi-ui/src/components/TopNav/index.vue +++ b/ruoyi-ui/src/components/TopNav/index.vue @@ -73,9 +73,9 @@ export default { if(router.path === "/") { router.children[item].path = "/redirect/" + router.children[item].path; } else { - if(!this.ishttp(router.children[item].path)) { + if(!this.ishttp(router.children[item].path)) { router.children[item].path = router.path + "/" + router.children[item].path; - } + } } router.children[item].parentPath = router.path; } diff --git a/ruoyi-ui/src/directive/dialog/drag.js b/ruoyi-ui/src/directive/dialog/drag.js new file mode 100644 index 00000000..728f49dc --- /dev/null +++ b/ruoyi-ui/src/directive/dialog/drag.js @@ -0,0 +1,64 @@ +/** +* v-dialogDrag 弹窗拖拽 +* Copyright (c) 2019 ruoyi +*/ + +export default { + bind(el, binding, vnode, oldVnode) { + const value = binding.value + if (value == false) return + // 获取拖拽内容头部 + const dialogHeaderEl = el.querySelector('.el-dialog__header'); + const dragDom = el.querySelector('.el-dialog'); + dialogHeaderEl.style.cursor = 'move'; + // 获取原有属性 ie dom元素.currentStyle 火狐谷歌 window.getComputedStyle(dom元素, null); + const sty = dragDom.currentStyle || window.getComputedStyle(dragDom, null); + dragDom.style.position = 'absolute'; + dragDom.style.marginTop = 0; + let width = dragDom.style.width; + if (width.includes('%')) { + width = +document.body.clientWidth * (+width.replace(/\%/g, '') / 100); + } else { + width = +width.replace(/\px/g, ''); + } + dragDom.style.left = `${(document.body.clientWidth - width) / 2}px`; + // 鼠标按下事件 + dialogHeaderEl.onmousedown = (e) => { + // 鼠标按下,计算当前元素距离可视区的距离 (鼠标点击位置距离可视窗口的距离) + const disX = e.clientX - dialogHeaderEl.offsetLeft; + const disY = e.clientY - dialogHeaderEl.offsetTop; + + // 获取到的值带px 正则匹配替换 + let styL, styT; + + // 注意在ie中 第一次获取到的值为组件自带50% 移动之后赋值为px + if (sty.left.includes('%')) { + styL = +document.body.clientWidth * (+sty.left.replace(/\%/g, '') / 100); + styT = +document.body.clientHeight * (+sty.top.replace(/\%/g, '') / 100); + } else { + styL = +sty.left.replace(/\px/g, ''); + styT = +sty.top.replace(/\px/g, ''); + }; + + // 鼠标拖拽事件 + document.onmousemove = function (e) { + // 通过事件委托,计算移动的距离 (开始拖拽至结束拖拽的距离) + const l = e.clientX - disX; + const t = e.clientY - disY; + + let finallyL = l + styL + let finallyT = t + styT + + // 移动当前元素 + dragDom.style.left = `${finallyL}px`; + dragDom.style.top = `${finallyT}px`; + + }; + + document.onmouseup = function (e) { + document.onmousemove = null; + document.onmouseup = null; + }; + } + } +}; \ No newline at end of file diff --git a/ruoyi-ui/src/directive/permission/index.js b/ruoyi-ui/src/directive/index.js similarity index 55% rename from ruoyi-ui/src/directive/permission/index.js rename to ruoyi-ui/src/directive/index.js index e3d76d38..550109b4 100644 --- a/ruoyi-ui/src/directive/permission/index.js +++ b/ruoyi-ui/src/directive/index.js @@ -1,14 +1,17 @@ -import hasRole from './hasRole' -import hasPermi from './hasPermi' +import hasRole from './permission/hasRole' +import hasPermi from './permission/hasPermi' +import dialogDrag from './dialog/drag' const install = function(Vue) { Vue.directive('hasRole', hasRole) Vue.directive('hasPermi', hasPermi) + Vue.directive('dialogDrag', dialogDrag) } if (window.Vue) { window['hasRole'] = hasRole window['hasPermi'] = hasPermi + window['dialogDrag'] = dialogDrag Vue.use(install); // eslint-disable-line } diff --git a/ruoyi-ui/src/directive/permission/hasPermi.js b/ruoyi-ui/src/directive/permission/hasPermi.js index d7107cec..7101e3e8 100644 --- a/ruoyi-ui/src/directive/permission/hasPermi.js +++ b/ruoyi-ui/src/directive/permission/hasPermi.js @@ -1,8 +1,8 @@ /** - * 操作权限处理 + * v-hasPermi 操作权限处理 * Copyright (c) 2019 ruoyi */ - + import store from '@/store' export default { diff --git a/ruoyi-ui/src/directive/permission/hasRole.js b/ruoyi-ui/src/directive/permission/hasRole.js index 13038099..ad9d4d79 100644 --- a/ruoyi-ui/src/directive/permission/hasRole.js +++ b/ruoyi-ui/src/directive/permission/hasRole.js @@ -1,8 +1,8 @@ /** - * 角色权限处理 + * v-hasRole 角色权限处理 * Copyright (c) 2019 ruoyi */ - + import store from '@/store' export default { diff --git a/ruoyi-ui/src/layout/components/AppMain.vue b/ruoyi-ui/src/layout/components/AppMain.vue index a8976380..0c6f4b78 100644 --- a/ruoyi-ui/src/layout/components/AppMain.vue +++ b/ruoyi-ui/src/layout/components/AppMain.vue @@ -51,7 +51,7 @@ export default { // fix css style bug in open el-dialog .el-popup-parent--hidden { .fixed-header { - padding-right: 15px; + padding-right: 17px; } } diff --git a/ruoyi-ui/src/layout/components/InnerLink/index.vue b/ruoyi-ui/src/layout/components/InnerLink/index.vue new file mode 100644 index 00000000..227ff2a7 --- /dev/null +++ b/ruoyi-ui/src/layout/components/InnerLink/index.vue @@ -0,0 +1,27 @@ + diff --git a/ruoyi-ui/src/main.js b/ruoyi-ui/src/main.js index d1f8973b..d07dead4 100644 --- a/ruoyi-ui/src/main.js +++ b/ruoyi-ui/src/main.js @@ -10,7 +10,7 @@ import '@/assets/styles/ruoyi.scss' // ruoyi css import App from './App' import store from './store' import router from './router' -import permission from './directive/permission' +import directive from './directive' //directive import './assets/icons' // icon import './permission' // permission control @@ -20,6 +20,12 @@ import { parseTime, resetForm, addDateRange, selectDictLabel, selectDictLabels, import Pagination from "@/components/Pagination"; // 自定义表格工具组件 import RightToolbar from "@/components/RightToolbar" +// 富文本组件 +import Editor from "@/components/Editor" +// 文件上传组件 +import FileUpload from "@/components/FileUpload" +// 图片上传组件 +import ImageUpload from "@/components/ImageUpload" // 字典标签组件 import DictTag from '@/components/DictTag' // 头部标签组件 @@ -52,8 +58,11 @@ Vue.prototype.msgInfo = function (msg) { Vue.component('DictTag', DictTag) Vue.component('Pagination', Pagination) Vue.component('RightToolbar', RightToolbar) +Vue.component('Editor', Editor) +Vue.component('FileUpload', FileUpload) +Vue.component('ImageUpload', ImageUpload) -Vue.use(permission) +Vue.use(directive) Vue.use(VueMeta) /** diff --git a/ruoyi-ui/src/router/index.js b/ruoyi-ui/src/router/index.js index ffb12e7d..c7b9371b 100644 --- a/ruoyi-ui/src/router/index.js +++ b/ruoyi-ui/src/router/index.js @@ -6,6 +6,7 @@ Vue.use(Router) /* Layout */ import Layout from '@/layout' import ParentView from '@/components/ParentView'; +import InnerLink from '@/layout/components/InnerLink' /** * Note: 路由配置项 @@ -80,6 +81,32 @@ export const constantRoutes = [ } ] }, + { + path: '/auth', + component: Layout, + hidden: true, + children: [ + { + path: 'role/:userId(\\d+)', + component: (resolve) => require(['@/views/system/user/authRole'], resolve), + name: 'AuthRole', + meta: { title: '分配角色'} + } + ] + }, + { + path: '/auth', + component: Layout, + hidden: true, + children: [ + { + path: 'user/:roleId(\\d+)', + component: (resolve) => require(['@/views/system/role/authUser'], resolve), + name: 'AuthUser', + meta: { title: '分配用户'} + } + ] + }, { path: '/dict', component: Layout, diff --git a/ruoyi-ui/src/store/modules/permission.js b/ruoyi-ui/src/store/modules/permission.js index aacfc8c9..81026f36 100644 --- a/ruoyi-ui/src/store/modules/permission.js +++ b/ruoyi-ui/src/store/modules/permission.js @@ -2,6 +2,7 @@ import { constantRoutes } from '@/router' import { getRouters } from '@/api/menu' import Layout from '@/layout/index' import ParentView from '@/components/ParentView'; +import InnerLink from '@/layout/components/InnerLink' const permission = { state: { @@ -65,6 +66,8 @@ function filterAsyncRouter(asyncRouterMap, lastRouter = false, type = false) { route.component = Layout } else if (route.component === 'ParentView') { route.component = ParentView + } else if (route.component === 'InnerLink') { + route.component = InnerLink } else { route.component = loadView(route.component) } diff --git a/ruoyi-ui/src/views/demo/demo/index.vue b/ruoyi-ui/src/views/demo/demo/index.vue index 279c4693..a6679f39 100644 --- a/ruoyi-ui/src/views/demo/demo/index.vue +++ b/ruoyi-ui/src/views/demo/demo/index.vue @@ -304,17 +304,19 @@ export default { this.buttonLoading = true; if (this.form.id != null) { updateDemo(this.form).then(response => { - this.buttonLoading = false; this.msgSuccess("修改成功"); this.open = false; this.getList(); + }).finally(() => { + this.buttonLoading = false; }); } else { addDemo(this.form).then(response => { - this.buttonLoading = false; this.msgSuccess("新增成功"); this.open = false; this.getList(); + }).finally(() => { + this.buttonLoading = false; }); } } diff --git a/ruoyi-ui/src/views/demo/tree/index.vue b/ruoyi-ui/src/views/demo/tree/index.vue index afe96c4a..57b152fc 100644 --- a/ruoyi-ui/src/views/demo/tree/index.vue +++ b/ruoyi-ui/src/views/demo/tree/index.vue @@ -255,17 +255,19 @@ export default { this.buttonLoading = true; if (this.form.id != null) { updateTree(this.form).then(response => { - this.buttonLoading = false; this.msgSuccess("修改成功"); this.open = false; this.getList(); + }).finally(() => { + this.buttonLoading = false; }); } else { addTree(this.form).then(response => { - this.buttonLoading = false; this.msgSuccess("新增成功"); this.open = false; this.getList(); + }).finally(() => { + this.buttonLoading = false; }); } } diff --git a/ruoyi-ui/src/views/index.vue b/ruoyi-ui/src/views/index.vue index dba6dfe8..671dcde2 100644 --- a/ruoyi-ui/src/views/index.vue +++ b/ruoyi-ui/src/views/index.vue @@ -91,6 +91,32 @@ 更新日志 + +
    +
  1. update springboot 2.4.7 => 2.4.8
  2. +
  3. update knife4j 3.0.2 => 3.0.3
  4. +
  5. update hutool 5.7.2 => 5.7.4
  6. +
  7. update spring-boot-admin 2.4.1 => 2.4.3
  8. +
  9. update redisson 3.15.2 => 3.16.0
  10. +
  11. add 增加 docker 编排 与 shell 脚本
  12. +
  13. add 增加 feign 熔断 自定义结构体解析方法 与 demo 注释
  14. +
  15. add 用户管理新增分配角色功能
  16. +
  17. add 角色管理新增分配用户功能
  18. +
  19. add 增加spring-cache演示案例
  20. +
  21. update 独立 springboot-admin 监控到扩展模块项目
  22. +
  23. update springboot-admin 监控 增加用户登录权限管理
  24. +
  25. update 优化代码生成器 批量导入
  26. +
  27. update 优化 增加MP注入异常拦截
  28. +
  29. update 关闭默认二级缓存 推荐使用 spring-cache 注解手动缓存
  30. +
  31. update FileUpload ImageUpload组件 支持多图片上传
  32. +
  33. update 优化中英文语言配置
  34. +
  35. update 规范maven写法
  36. +
  37. fix redis获取map属性bug修复。
  38. +
  39. fix 修复 按钮loading 后端500卡死问题
  40. +
  41. fix 相对路径下载问题
  42. +
  43. fix 修复 hutool 工具返回结果不一致问题
  44. +
+
  1. update springboot 2.3.11 => 2.4.7
  2. diff --git a/ruoyi-ui/src/views/monitor/admin/index.vue b/ruoyi-ui/src/views/monitor/admin/index.vue index f1d48b0a..ad35dc46 100644 --- a/ruoyi-ui/src/views/monitor/admin/index.vue +++ b/ruoyi-ui/src/views/monitor/admin/index.vue @@ -1,26 +1,16 @@