From 960907872747054992a447f52242b5df50dbcf21 Mon Sep 17 00:00:00 2001 From: toesbieya <1647775459@qq.com> Date: Sun, 12 Jul 2020 14:05:58 +0800 Subject: [PATCH] =?UTF-8?q?=E7=A7=BB=E9=99=A4spring-session=EF=BC=8C?= =?UTF-8?q?=E6=94=B9=E7=94=A8=E7=AE=80=E6=98=93=E6=96=B9=E5=BC=8F=E5=AD=98?= =?UTF-8?q?=E5=82=A8=E7=99=BB=E5=BD=95=E6=80=81=20=E7=A7=BB=E9=99=A4?= =?UTF-8?q?=E7=B3=BB=E7=BB=9F=E7=9B=91=E6=8E=A7=E6=A8=A1=E5=9D=97=20SysUse?= =?UTF-8?q?rController=E9=83=A8=E5=88=86=E5=8A=9F=E8=83=BD=E6=8B=86?= =?UTF-8?q?=E5=88=86=E8=87=B3AccountController=20socket=E5=8F=82=E6=95=B0?= =?UTF-8?q?=E4=BF=AE=E6=94=B9=EF=BC=9Asession=5Fid->token=20=E5=85=B6?= =?UTF-8?q?=E4=BB=96=E4=BB=A3=E7=A0=81=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- java/my.sql | 68 ++++++-- java/pom.xml | 5 - .../java/com/toesbieya/my/MyApplication.java | 2 - .../com/toesbieya/my/aspect/LockAspect.java | 28 ++-- .../my/config/FastJsonConfigFactory.java | 19 +++ .../my/config/HttpSessionConfig.java | 70 --------- .../com/toesbieya/my/config/QiniuConfig.java | 22 +++ .../com/toesbieya/my/config/RedisConfig.java | 25 +-- .../com/toesbieya/my/config/SocketConfig.java | 32 ++-- .../my/config/SocketServerConfig.java | 37 +++++ .../com/toesbieya/my/config/WebConfig.java | 24 +-- .../my/constant/DocumentConstant.java | 7 + .../my/constant/SessionConstant.java | 4 +- .../toesbieya/my/constant/SocketConstant.java | 18 ++- .../my/controller/AccountController.java | 100 +++++------- .../BizPurchaseInboundController.java | 14 +- .../BizPurchaseOrderController.java | 22 +-- .../my/controller/BizSellOrderController.java | 15 +- .../controller/BizSellOutboundController.java | 20 +-- .../my/controller/MonitorController.java | 17 -- .../my/controller/MsgController.java | 24 +-- .../my/controller/RecController.java | 10 +- .../controller/SysDepartmentController.java | 6 +- .../my/controller/SysRoleController.java | 10 +- .../my/controller/SysUserController.java | 1 - .../interceptor/RateControlInterceptor.java | 20 +-- .../my/interceptor/SecurityInterceptor.java | 41 ++--- .../toesbieya/my/mapper/SysUserMapper.java | 9 +- .../toesbieya/my/model/entity/SysUser.java | 23 +-- .../com/toesbieya/my/model/vo/LoginParam.java | 17 ++ .../my/model/vo/LoginSuccessInfo.java | 26 ++++ .../my/model/vo/PasswordUpdateParam.java | 10 ++ .../toesbieya/my/model/vo/RegisterParam.java | 11 ++ .../com/toesbieya/my/model/vo/UserVo.java | 33 ++++ .../toesbieya/my/model/vo/info/CpuInfo.java | 54 ------- .../toesbieya/my/model/vo/info/DiskInfo.java | 25 --- .../toesbieya/my/model/vo/info/JvmInfo.java | 29 ---- .../my/model/vo/info/MemoryInfo.java | 26 ---- .../my/model/vo/info/MonitorInfo.java | 20 --- .../my/model/vo/info/OperatingInfo.java | 19 --- .../toesbieya/my/module/PermissionModule.java | 19 ++- .../my/module/{redis => }/RedisModule.java | 36 +++-- .../com/toesbieya/my/module/SocketModule.java | 61 ++++---- .../toesbieya/my/module/redis/LockHelper.java | 15 -- .../my/module/redis/RedisLockHelper.java | 45 ------ .../my/module/redis/RedisLockType.java | 5 - .../toesbieya/my/service/AccountService.java | 145 ++++++++++++++++++ .../my/service/BizPurchaseInboundService.java | 14 +- .../my/service/BizPurchaseOrderService.java | 11 +- .../my/service/BizSellOrderService.java | 11 +- .../my/service/BizSellOutboundService.java | 14 +- .../com/toesbieya/my/service/MsgService.java | 7 +- .../com/toesbieya/my/service/RecService.java | 4 +- .../toesbieya/my/service/SysUserService.java | 128 +--------------- .../com/toesbieya/my/utils/DocumentUtil.java | 47 ++++++ .../com/toesbieya/my/utils/ExcelUtil.java | 4 +- .../com/toesbieya/my/utils/MonitorUtil.java | 69 --------- .../com/toesbieya/my/utils/QiniuUtil.java | 41 +++-- .../com/toesbieya/my/utils/RedisUtil.java | 84 +++++----- .../com/toesbieya/my/utils/SessionUtil.java | 46 ++++++ .../com/toesbieya/my/utils/ThreadUtil.java | 13 +- .../java/com/toesbieya/my/utils/Util.java | 66 ++++---- .../java/com/toesbieya/my/utils/WebUtil.java | 23 +++ java/src/main/resources/mapper/SysUser.xml | 14 +- 64 files changed, 876 insertions(+), 1009 deletions(-) create mode 100644 java/src/main/java/com/toesbieya/my/config/FastJsonConfigFactory.java delete mode 100644 java/src/main/java/com/toesbieya/my/config/HttpSessionConfig.java create mode 100644 java/src/main/java/com/toesbieya/my/config/QiniuConfig.java create mode 100644 java/src/main/java/com/toesbieya/my/config/SocketServerConfig.java create mode 100644 java/src/main/java/com/toesbieya/my/constant/DocumentConstant.java delete mode 100644 java/src/main/java/com/toesbieya/my/controller/MonitorController.java create mode 100644 java/src/main/java/com/toesbieya/my/model/vo/LoginParam.java create mode 100644 java/src/main/java/com/toesbieya/my/model/vo/LoginSuccessInfo.java create mode 100644 java/src/main/java/com/toesbieya/my/model/vo/PasswordUpdateParam.java create mode 100644 java/src/main/java/com/toesbieya/my/model/vo/RegisterParam.java create mode 100644 java/src/main/java/com/toesbieya/my/model/vo/UserVo.java delete mode 100644 java/src/main/java/com/toesbieya/my/model/vo/info/CpuInfo.java delete mode 100644 java/src/main/java/com/toesbieya/my/model/vo/info/DiskInfo.java delete mode 100644 java/src/main/java/com/toesbieya/my/model/vo/info/JvmInfo.java delete mode 100644 java/src/main/java/com/toesbieya/my/model/vo/info/MemoryInfo.java delete mode 100644 java/src/main/java/com/toesbieya/my/model/vo/info/MonitorInfo.java delete mode 100644 java/src/main/java/com/toesbieya/my/model/vo/info/OperatingInfo.java rename java/src/main/java/com/toesbieya/my/module/{redis => }/RedisModule.java (69%) delete mode 100644 java/src/main/java/com/toesbieya/my/module/redis/LockHelper.java delete mode 100644 java/src/main/java/com/toesbieya/my/module/redis/RedisLockHelper.java delete mode 100644 java/src/main/java/com/toesbieya/my/module/redis/RedisLockType.java create mode 100644 java/src/main/java/com/toesbieya/my/service/AccountService.java create mode 100644 java/src/main/java/com/toesbieya/my/utils/DocumentUtil.java delete mode 100644 java/src/main/java/com/toesbieya/my/utils/MonitorUtil.java create mode 100644 java/src/main/java/com/toesbieya/my/utils/SessionUtil.java create mode 100644 java/src/main/java/com/toesbieya/my/utils/WebUtil.java diff --git a/java/my.sql b/java/my.sql index ff948b8..15e837e 100644 --- a/java/my.sql +++ b/java/my.sql @@ -11,7 +11,7 @@ Target Server Version : 80018 File Encoding : 65001 - Date: 11/07/2020 10:11:24 + Date: 12/07/2020 13:49:09 */ SET NAMES utf8mb4; @@ -34,7 +34,7 @@ CREATE TABLE `biz_document_history` ( PRIMARY KEY (`id`) USING BTREE, INDEX `pid_time_idx`(`pid`, `time`) USING BTREE, INDEX `uid_idx`(`uid`) USING BTREE -) ENGINE = InnoDB AUTO_INCREMENT = 30 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic; +) ENGINE = InnoDB AUTO_INCREMENT = 31 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Records of biz_document_history @@ -76,7 +76,7 @@ CREATE TABLE `biz_purchase_inbound_sub` ( `num` decimal(10, 2) NOT NULL COMMENT '入库数量', PRIMARY KEY (`id`) USING BTREE, UNIQUE INDEX `pid_cid_unique_idx`(`pid`, `cid`) USING BTREE COMMENT '同一采购入库单不能有重复分类的商品' -) ENGINE = InnoDB AUTO_INCREMENT = 12 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic; +) ENGINE = InnoDB AUTO_INCREMENT = 13 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Table structure for biz_purchase_order @@ -208,7 +208,7 @@ CREATE TABLE `biz_sell_outbound_sub` ( `cname` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '商品分类名称', `num` decimal(10, 2) NOT NULL COMMENT '出库数量', PRIMARY KEY (`id`) USING BTREE -) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic; +) ENGINE = InnoDB AUTO_INCREMENT = 5 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Table structure for biz_stock @@ -226,7 +226,7 @@ CREATE TABLE `biz_stock` ( PRIMARY KEY (`id`) USING BTREE, UNIQUE INDEX `cid_cgrkid_unique_idx`(`cid`, `cgrkid`) USING BTREE, INDEX `cdate_idx`(`ctime`) USING BTREE -) ENGINE = InnoDB AUTO_INCREMENT = 9 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic; +) ENGINE = InnoDB AUTO_INCREMENT = 10 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Table structure for msg @@ -297,7 +297,7 @@ CREATE TABLE `rec_attachment` ( PRIMARY KEY (`id`) USING BTREE, INDEX `pid_idx`(`pid`) USING BTREE, INDEX `url_idx`(`url`) USING BTREE -) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic; +) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Table structure for rec_login_history @@ -315,7 +315,7 @@ CREATE TABLE `rec_login_history` ( INDEX `uid_idx`(`uid`) USING BTREE, INDEX `type_idx`(`type`) USING BTREE, INDEX `time_idx`(`time`) USING BTREE -) ENGINE = InnoDB AUTO_INCREMENT = 400 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic; +) ENGINE = InnoDB AUTO_INCREMENT = 406 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Records of rec_login_history @@ -477,6 +477,21 @@ INSERT INTO `rec_login_history` VALUES (398, 1, 'admin', '127.0.0.1', NULL, 1, 1 INSERT INTO `rec_login_history` VALUES (399, 1, 'admin', '127.0.0.1', NULL, 1, 1594344197698); INSERT INTO `rec_login_history` VALUES (400, 1, 'admin', '127.0.0.1', NULL, 1, 1594396572079); INSERT INTO `rec_login_history` VALUES (401, 1, 'admin', '127.0.0.1', NULL, 1, 1594433292572); +INSERT INTO `rec_login_history` VALUES (402, 1, 'admin', '127.0.0.1', NULL, 1, 1594453804314); +INSERT INTO `rec_login_history` VALUES (403, 1, 'admin', '127.0.0.1', NULL, 1, 1594463748662); +INSERT INTO `rec_login_history` VALUES (404, 1, 'admin', '127.0.0.1', NULL, 1, 1594464193655); +INSERT INTO `rec_login_history` VALUES (405, 1, 'admin', '127.0.0.1', NULL, 1, 1594467338836); +INSERT INTO `rec_login_history` VALUES (406, 1, 'admin', '127.0.0.1', NULL, 1, 1594478241573); +INSERT INTO `rec_login_history` VALUES (407, 1, 'admin', '127.0.0.1', NULL, 1, 1594517412152); +INSERT INTO `rec_login_history` VALUES (408, 1, 'admin', '127.0.0.1', NULL, 1, 1594517476000); +INSERT INTO `rec_login_history` VALUES (409, 1, 'admin', '127.0.0.1', NULL, 1, 1594517663344); +INSERT INTO `rec_login_history` VALUES (410, 1, 'admin', '127.0.0.1', NULL, 1, 1594518624685); +INSERT INTO `rec_login_history` VALUES (411, 1, 'admin', '127.0.0.1', NULL, 0, 1594518745456); +INSERT INTO `rec_login_history` VALUES (412, 1, 'admin', '127.0.0.1', NULL, 1, 1594518838620); +INSERT INTO `rec_login_history` VALUES (413, 1, 'admin', '127.0.0.1', NULL, 1, 1594530875654); +INSERT INTO `rec_login_history` VALUES (414, 1, 'admin', '127.0.0.1', NULL, 1, 1594531358311); +INSERT INTO `rec_login_history` VALUES (415, 1, 'admin', '127.0.0.1', NULL, 0, 1594531491193); +INSERT INTO `rec_login_history` VALUES (416, 1, 'admin', '127.0.0.1', NULL, 1, 1594531562264); -- ---------------------------- -- Table structure for rec_user_action @@ -493,7 +508,7 @@ CREATE TABLE `rec_user_action` ( `error` text CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL COMMENT '错误信息', `type` int(11) NOT NULL COMMENT '0失败、1成功', PRIMARY KEY (`id`) USING BTREE -) ENGINE = InnoDB AUTO_INCREMENT = 64 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic; +) ENGINE = InnoDB AUTO_INCREMENT = 65 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Records of rec_user_action @@ -503,6 +518,9 @@ INSERT INTO `rec_user_action` VALUES (61, 1, 'admin', '127.0.0.1', '/purchase/or INSERT INTO `rec_user_action` VALUES (62, 1, 'admin', '127.0.0.1', '/purchase/order/commit', 1592537930960, '提交采购订单CGDD202006190001', NULL, 1); INSERT INTO `rec_user_action` VALUES (63, 1, 'admin', '127.0.0.1', '/purchase/order/pass', 1592537934425, '通过采购订单CGDD202006190001', NULL, 1); INSERT INTO `rec_user_action` VALUES (64, 1, 'admin', '127.0.0.1', '/system/user/add', 1592803978425, '添加用户:toesbieya', NULL, 1); +INSERT INTO `rec_user_action` VALUES (65, 1, 'admin', '127.0.0.1', '/system/role/update', 1594530891861, '修改角色:默认管理员', NULL, 1); +INSERT INTO `rec_user_action` VALUES (66, 1, 'admin', '127.0.0.1', '/system/role/update', 1594530931531, '修改角色:默认管理员', NULL, 1); +INSERT INTO `rec_user_action` VALUES (67, 1, 'admin', '127.0.0.1', '/system/role/update', 1594530948651, '修改角色:默认管理员', NULL, 1); -- ---------------------------- -- Table structure for stat_finish_order @@ -514,7 +532,7 @@ CREATE TABLE `stat_finish_order` ( `sell` int(11) NOT NULL COMMENT '销售订单完成数', `time` bigint(20) NOT NULL COMMENT '完成时间', PRIMARY KEY (`id`) USING BTREE -) ENGINE = InnoDB AUTO_INCREMENT = 131 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic; +) ENGINE = InnoDB AUTO_INCREMENT = 132 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Records of stat_finish_order @@ -553,6 +571,7 @@ INSERT INTO `stat_finish_order` VALUES (128, 0, 0, 1594051200000); INSERT INTO `stat_finish_order` VALUES (129, 0, 0, 1594137600000); INSERT INTO `stat_finish_order` VALUES (130, 0, 0, 1594224000000); INSERT INTO `stat_finish_order` VALUES (131, 0, 0, 1594310400000); +INSERT INTO `stat_finish_order` VALUES (132, 0, 0, 1594396800000); -- ---------------------------- -- Table structure for stat_profit_goods @@ -584,7 +603,7 @@ CREATE TABLE `stat_profit_total` ( `profit` decimal(10, 2) NOT NULL COMMENT '毛利润', `time` bigint(20) NOT NULL, PRIMARY KEY (`id`) USING BTREE -) ENGINE = InnoDB AUTO_INCREMENT = 131 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic; +) ENGINE = InnoDB AUTO_INCREMENT = 132 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Records of stat_profit_total @@ -623,6 +642,7 @@ INSERT INTO `stat_profit_total` VALUES (128, 0.00, 0.00, 0.00, 1594051200000); INSERT INTO `stat_profit_total` VALUES (129, 0.00, 0.00, 0.00, 1594137600000); INSERT INTO `stat_profit_total` VALUES (130, 0.00, 0.00, 0.00, 1594224000000); INSERT INTO `stat_profit_total` VALUES (131, 0.00, 0.00, 0.00, 1594310400000); +INSERT INTO `stat_profit_total` VALUES (132, 0.00, 0.00, 0.00, 1594396800000); -- ---------------------------- -- Table structure for sys_category @@ -669,7 +689,7 @@ CREATE TABLE `sys_customer` ( UNIQUE INDEX `name_unique_idx`(`name`) USING BTREE, INDEX `status_idx`(`status`) USING BTREE, INDEX `ctime_idx`(`ctime`) USING BTREE -) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic; +) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Records of sys_customer @@ -687,7 +707,7 @@ CREATE TABLE `sys_department` ( `status` int(11) NOT NULL DEFAULT 1 COMMENT '0禁用,1正常', PRIMARY KEY (`id`) USING BTREE, UNIQUE INDEX `pid_name_unique_idx`(`pid`, `name`) USING BTREE -) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic; +) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Records of sys_department @@ -47256,7 +47276,6 @@ INSERT INTO `sys_resource` VALUES (302, 300, '修改', '/update', 0, 100, 1); INSERT INTO `sys_resource` VALUES (303, 300, '删除', '/del', 0, 100, 1); INSERT INTO `sys_resource` VALUES (350, 200, '接口管理', '/resource', 1, 100, 1); INSERT INTO `sys_resource` VALUES (351, 350, '修改', '/update', 1, 100, 1); -INSERT INTO `sys_resource` VALUES (360, 200, '系统监控', '/monitor', 1, 100, 1); -- ---------------------------- -- Table structure for sys_role @@ -47298,7 +47317,7 @@ CREATE TABLE `sys_supplier` ( UNIQUE INDEX `name_unique_idx`(`name`) USING BTREE, INDEX `ctime_idx`(`ctime`) USING BTREE, INDEX `status_idx`(`status`) USING BTREE -) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic; +) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Records of sys_supplier @@ -47328,4 +47347,25 @@ CREATE TABLE `sys_user` ( INSERT INTO `sys_user` VALUES (1, 'admin', 'e10adc3949ba59abbe56e057f20f883e', NULL, NULL, 1582184632922, 1, 1); INSERT INTO `sys_user` VALUES (47, 'toesbieya', 'e10adc3949ba59abbe56e057f20f883e', 1, NULL, 1592803978422, 0, 1); +-- ---------------------------- +-- Function structure for check_category_use +-- ---------------------------- +DROP FUNCTION IF EXISTS `check_category_use`; +delimiter ;; +CREATE FUNCTION `check_category_use`(cid INT) + RETURNS tinyint(4) + READS SQL DATA +BEGIN + declare r int; + select count(0) from biz_purchase_order_sub where cid=cid into r; + if r=0 then + select count(0) from biz_sell_order_sub where cid=cid into r; + return r; + else + return 1; + end if; +END +;; +delimiter ; + SET FOREIGN_KEY_CHECKS = 1; diff --git a/java/pom.xml b/java/pom.xml index 17f9dab..bc33479 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -54,11 +54,6 @@ commons-pool2 - - org.springframework.session - spring-session-data-redis - - org.mybatis.spring.boot diff --git a/java/src/main/java/com/toesbieya/my/MyApplication.java b/java/src/main/java/com/toesbieya/my/MyApplication.java index abe1fdb..0c9a742 100644 --- a/java/src/main/java/com/toesbieya/my/MyApplication.java +++ b/java/src/main/java/com/toesbieya/my/MyApplication.java @@ -3,13 +3,11 @@ package com.toesbieya.my; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.cache.annotation.EnableCaching; import org.springframework.scheduling.annotation.EnableScheduling; @SpringBootApplication @MapperScan("com.toesbieya.my.mapper") @EnableScheduling -@EnableCaching public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); diff --git a/java/src/main/java/com/toesbieya/my/aspect/LockAspect.java b/java/src/main/java/com/toesbieya/my/aspect/LockAspect.java index b6591f2..164b4ba 100644 --- a/java/src/main/java/com/toesbieya/my/aspect/LockAspect.java +++ b/java/src/main/java/com/toesbieya/my/aspect/LockAspect.java @@ -1,8 +1,7 @@ package com.toesbieya.my.aspect; import com.toesbieya.my.annoation.Lock; -import com.toesbieya.my.module.redis.LockHelper; -import com.toesbieya.my.module.redis.RedisLockHelper; +import com.toesbieya.my.utils.RedisUtil; import com.toesbieya.my.utils.Result; import com.toesbieya.my.utils.SpringUtil; import lombok.extern.slf4j.Slf4j; @@ -11,7 +10,6 @@ import org.aspectj.lang.annotation.*; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; -import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import java.lang.reflect.Method; @@ -22,7 +20,7 @@ import java.util.ArrayList; @Slf4j @Order(Integer.MAX_VALUE - 1) public class LockAspect { - private final ThreadLocal> lockHelperThreadLocal = new ThreadLocal<>(); + private final ThreadLocal> lockerThreadLocal = new ThreadLocal<>(); @Pointcut("@annotation(com.toesbieya.my.annoation.Lock)&&execution(com.toesbieya.my.utils.Result com.toesbieya.my..*.*(..))") public void pointCut() { @@ -37,21 +35,23 @@ public class LockAspect { if (values.length <= 0) { return point.proceed(); } - ArrayList locks = new ArrayList<>(); + ArrayList locks = new ArrayList<>(); String[] parameterNames = signature.getParameterNames(); Object[] args = point.getArgs(); for (String v : values) { String lockKey = (String) SpringUtil.spell(v, parameterNames, args); + //跳过空值 if (StringUtils.isEmpty(lockKey)) continue; - LockHelper lockHelper = new RedisLockHelper(lockKey); - if (!lockHelper.lock()) { - locks.forEach(LockHelper::close); + + RedisUtil.Locker locker = new RedisUtil.Locker(lockKey); + if (!locker.lock()) { + locks.forEach(RedisUtil.Locker::close); return Result.fail("操作失败,请刷新后重试"); } - locks.add(lockHelper); + locks.add(locker); } - lockHelperThreadLocal.set(locks); + lockerThreadLocal.set(locks); return point.proceed(); } @@ -66,10 +66,10 @@ public class LockAspect { } private void unlock() { - ArrayList locks = lockHelperThreadLocal.get(); - if (!CollectionUtils.isEmpty(locks)) { - locks.forEach(LockHelper::close); - lockHelperThreadLocal.remove(); + ArrayList locks = lockerThreadLocal.get(); + if (locks != null) { + locks.forEach(RedisUtil.Locker::close); + lockerThreadLocal.remove(); } } } diff --git a/java/src/main/java/com/toesbieya/my/config/FastJsonConfigFactory.java b/java/src/main/java/com/toesbieya/my/config/FastJsonConfigFactory.java new file mode 100644 index 0000000..e32ed4e --- /dev/null +++ b/java/src/main/java/com/toesbieya/my/config/FastJsonConfigFactory.java @@ -0,0 +1,19 @@ +package com.toesbieya.my.config; + +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.alibaba.fastjson.support.config.FastJsonConfig; + +public class FastJsonConfigFactory { + public static FastJsonConfig defaultConfig() { + FastJsonConfig config = new FastJsonConfig(); + + config.setSerializerFeatures( + SerializerFeature.WriteMapNullValue, // 是否输出值为null的字段 + SerializerFeature.WriteDateUseDateFormat, + SerializerFeature.WriteNullListAsEmpty, + SerializerFeature.DisableCircularReferenceDetect // 禁用循环引用 + ); + + return config; + } +} diff --git a/java/src/main/java/com/toesbieya/my/config/HttpSessionConfig.java b/java/src/main/java/com/toesbieya/my/config/HttpSessionConfig.java deleted file mode 100644 index 906f0e5..0000000 --- a/java/src/main/java/com/toesbieya/my/config/HttpSessionConfig.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.toesbieya.my.config; - -import com.alibaba.fastjson.JSON; -import com.toesbieya.my.model.entity.SysUser; -import com.toesbieya.my.module.SocketModule; -import com.toesbieya.my.utils.Util; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.data.redis.serializer.RedisSerializer; -import org.springframework.data.redis.serializer.SerializationException; -import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; - -import javax.servlet.http.HttpSessionEvent; -import javax.servlet.http.HttpSessionListener; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; - -@Configuration -@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 28800) -public class HttpSessionConfig { - @Bean - public HttpSessionListener httpSessionEventPublisher() { - return new HttpSessionListener() { - @Override - public void sessionCreated(HttpSessionEvent se) { - } - - @Override - public void sessionDestroyed(HttpSessionEvent se) { - SysUser user = Util.getUser(se.getSession()); - if (user != null) { - SocketModule.logout(user.getId(), "登陆状态过期,请重新登陆"); - } - } - }; - } - - @Bean("springSessionDefaultRedisSerializer") - public RedisSerializer defaultRedisSerializer() { - return new JsonRedisSerializer<>(Object.class); - } - - private class JsonRedisSerializer implements RedisSerializer { - - private final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8; - - private final Class clazz; - - public JsonRedisSerializer(Class clazz) { - this.clazz = clazz; - } - - @Override - public byte[] serialize(T t) throws SerializationException { - if (t == null) { - return new byte[0]; - } - return JSON.toJSONString(t).getBytes(DEFAULT_CHARSET); - } - - @Override - public T deserialize(byte[] bytes) throws SerializationException { - if (bytes == null || bytes.length <= 0) { - return null; - } - String str = new String(bytes, DEFAULT_CHARSET); - return JSON.parseObject(str, clazz); - } - } -} diff --git a/java/src/main/java/com/toesbieya/my/config/QiniuConfig.java b/java/src/main/java/com/toesbieya/my/config/QiniuConfig.java new file mode 100644 index 0000000..609ba51 --- /dev/null +++ b/java/src/main/java/com/toesbieya/my/config/QiniuConfig.java @@ -0,0 +1,22 @@ +package com.toesbieya.my.config; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +@Component +@ConfigurationProperties("qiniu") +@Data +public class QiniuConfig { + private String accessKey; + + private String secretKey; + + private String bucket; + + //临时上传凭证的有效期,单位秒 + private Integer tokenExpire = 3600; + + //临时上传凭证的redis键名 + private String redisCacheKey = "qiniu-token"; +} diff --git a/java/src/main/java/com/toesbieya/my/config/RedisConfig.java b/java/src/main/java/com/toesbieya/my/config/RedisConfig.java index 03f7e1c..cc87835 100644 --- a/java/src/main/java/com/toesbieya/my/config/RedisConfig.java +++ b/java/src/main/java/com/toesbieya/my/config/RedisConfig.java @@ -3,16 +3,10 @@ package com.toesbieya.my.config; import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.data.redis.cache.RedisCacheConfiguration; -import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; -import org.springframework.data.redis.serializer.RedisSerializationContext; import org.springframework.data.redis.serializer.StringRedisSerializer; -import java.time.Duration; - @Configuration public class RedisConfig { @Bean @@ -21,6 +15,8 @@ public class RedisConfig { redisTemplate.setConnectionFactory(factory); FastJsonRedisSerializer fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class); + fastJsonRedisSerializer.setFastJsonConfig(FastJsonConfigFactory.defaultConfig()); + StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); // 设置值(value)的序列化采用FastJsonRedisSerializer。 @@ -35,21 +31,4 @@ public class RedisConfig { redisTemplate.afterPropertiesSet(); return redisTemplate; } - - @Bean - public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) { - RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig() - .entryTtl(Duration.ofSeconds(60)) - // 设置key的序列化方式 - .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer())) - // 设置value的序列化方式 - .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer())) - // 不缓存null值 - .disableCachingNullValues(); - - return RedisCacheManager.builder(connectionFactory) - .cacheDefaults(config) - .transactionAware() - .build(); - } } diff --git a/java/src/main/java/com/toesbieya/my/config/SocketConfig.java b/java/src/main/java/com/toesbieya/my/config/SocketConfig.java index 90c5515..2a04661 100644 --- a/java/src/main/java/com/toesbieya/my/config/SocketConfig.java +++ b/java/src/main/java/com/toesbieya/my/config/SocketConfig.java @@ -1,27 +1,15 @@ package com.toesbieya.my.config; -import com.corundumstudio.socketio.SocketIOServer; -import com.corundumstudio.socketio.annotation.SpringAnnotationScanner; -import com.toesbieya.my.constant.SocketConstant; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; -@Configuration +@Component +@ConfigurationProperties("socket") +@Data public class SocketConfig { - - @Bean - public SocketIOServer socketIOServer() { - com.corundumstudio.socketio.Configuration config = new com.corundumstudio.socketio.Configuration(); - config.setHostname(SocketConstant.HOSTNAME); - config.setPort(SocketConstant.PORT); - config.setMaxFramePayloadLength(SocketConstant.MAX_FRAME_PAYLOAD); - config.setMaxHttpContentLength(SocketConstant.MAX_HTTP_CONTENT); - config.setAddVersionHeader(false); - return new SocketIOServer(config); - } - - @Bean - public SpringAnnotationScanner springAnnotationScanner(SocketIOServer socketServer) { - return new SpringAnnotationScanner(socketServer); - } + private String hostname = "localhost"; + private Integer port = 12580; + private Integer maxFramePayloadLength = 1024 * 1024; + private Integer maxHttpContentLength = 1024 * 1024; } diff --git a/java/src/main/java/com/toesbieya/my/config/SocketServerConfig.java b/java/src/main/java/com/toesbieya/my/config/SocketServerConfig.java new file mode 100644 index 0000000..7956320 --- /dev/null +++ b/java/src/main/java/com/toesbieya/my/config/SocketServerConfig.java @@ -0,0 +1,37 @@ +package com.toesbieya.my.config; + +import com.corundumstudio.socketio.SocketIOServer; +import com.corundumstudio.socketio.annotation.SpringAnnotationScanner; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.DependsOn; + +@Configuration +@DependsOn("redisUtil") +public class SocketServerConfig { + private SocketConfig socketConfig; + + @Bean + public SocketIOServer socketIOServer() { + com.corundumstudio.socketio.Configuration config = new com.corundumstudio.socketio.Configuration(); + + config.setHostname(socketConfig.getHostname()); + config.setPort(socketConfig.getPort()); + config.setMaxFramePayloadLength(socketConfig.getMaxFramePayloadLength()); + config.setMaxHttpContentLength(socketConfig.getMaxHttpContentLength()); + + config.setAddVersionHeader(false); + return new SocketIOServer(config); + } + + @Bean + public SpringAnnotationScanner springAnnotationScanner(SocketIOServer socketServer) { + return new SpringAnnotationScanner(socketServer); + } + + @Autowired + public void setSocketConfig(SocketConfig socketConfig) { + this.socketConfig = socketConfig; + } +} diff --git a/java/src/main/java/com/toesbieya/my/config/WebConfig.java b/java/src/main/java/com/toesbieya/my/config/WebConfig.java index 15483d5..f6e84e1 100644 --- a/java/src/main/java/com/toesbieya/my/config/WebConfig.java +++ b/java/src/main/java/com/toesbieya/my/config/WebConfig.java @@ -1,7 +1,5 @@ package com.toesbieya.my.config; -import com.alibaba.fastjson.serializer.SerializerFeature; -import com.alibaba.fastjson.support.config.FastJsonConfig; import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; import com.toesbieya.my.interceptor.RateControlInterceptor; import com.toesbieya.my.interceptor.SecurityInterceptor; @@ -22,33 +20,19 @@ import java.util.List; public class WebConfig implements WebMvcConfigurer { @Override public void configureMessageConverters(List> converters) { - /* - 先把JackSon的消息转换器删除. - 备注:(1)源码分析可知,返回json的过程为: - Controller调用结束后返回一个数据对象,for循环遍历conventers,找到支持application/json的HttpMessageConverter,然后将返回的数据序列化成json。 - 具体参考org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor的writeWithMessageConverters方法 - (2)由于是list结构,我们添加的fastjson在最后。因此必须要将jackson的转换器删除,不然会先匹配上jackson,导致没使用fastjson - */ for (int i = converters.size() - 1; i >= 0; i--) { if (converters.get(i) instanceof MappingJackson2HttpMessageConverter) { converters.remove(i); } } + FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter(); - FastJsonConfig config = new FastJsonConfig(); - config.setSerializerFeatures( - SerializerFeature.WriteMapNullValue, // 是否输出值为null的字段,默认为false,我们将它打开 - SerializerFeature.WriteDateUseDateFormat, - SerializerFeature.WriteNullListAsEmpty, - SerializerFeature.DisableCircularReferenceDetect // 禁用循环引用 - ); - fastJsonHttpMessageConverter.setFastJsonConfig(config); - // 添加支持的MediaTypes;不添加时默认为*/*,也就是默认支持全部 - // 但是MappingJackson2HttpMessageConverter里面支持的MediaTypes为application/json - // 参考它的做法, fastjson也只添加application/json的MediaType + fastJsonHttpMessageConverter.setFastJsonConfig(FastJsonConfigFactory.defaultConfig()); + List fastMediaTypes = new ArrayList<>(); fastMediaTypes.add(MediaType.APPLICATION_JSON); fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes); + converters.add(fastJsonHttpMessageConverter); } diff --git a/java/src/main/java/com/toesbieya/my/constant/DocumentConstant.java b/java/src/main/java/com/toesbieya/my/constant/DocumentConstant.java new file mode 100644 index 0000000..55bab59 --- /dev/null +++ b/java/src/main/java/com/toesbieya/my/constant/DocumentConstant.java @@ -0,0 +1,7 @@ +package com.toesbieya.my.constant; + +public class DocumentConstant { + public static final String UPDATE_DOCUMENTS_LOCK_KEY = "UPDATE_DOCUMENTS"; + public static final String[] DOCUMENT_TYPE = {"CGDD", "CGRK", "CGTH", "XSDD", "XSCK", "XSTH"}; + public static final String DOCUMENT_TYPE_REDIS_KEY = "documentsID"; +} diff --git a/java/src/main/java/com/toesbieya/my/constant/SessionConstant.java b/java/src/main/java/com/toesbieya/my/constant/SessionConstant.java index 65cc02e..a112834 100644 --- a/java/src/main/java/com/toesbieya/my/constant/SessionConstant.java +++ b/java/src/main/java/com/toesbieya/my/constant/SessionConstant.java @@ -1,8 +1,6 @@ package com.toesbieya.my.constant; public class SessionConstant { - public static String REDIS_NAMESPACE = "spring:session:sessions:"; - public static String USER_KEY = "user"; + public static String REDIS_NAMESPACE = "sessions:"; public static String TOKEN_KEY = "X-Token"; - public static Integer PREDICT_MAX_USER = 128; } diff --git a/java/src/main/java/com/toesbieya/my/constant/SocketConstant.java b/java/src/main/java/com/toesbieya/my/constant/SocketConstant.java index 3487e53..93d59d8 100644 --- a/java/src/main/java/com/toesbieya/my/constant/SocketConstant.java +++ b/java/src/main/java/com/toesbieya/my/constant/SocketConstant.java @@ -1,12 +1,14 @@ package com.toesbieya.my.constant; -import com.toesbieya.my.utils.YmlUtil; - public class SocketConstant { - public static final String HOSTNAME = (String) YmlUtil.get("socket.hostname"); - public static final int PORT = (int) YmlUtil.get("socket.port"); - public static final int MAX_FRAME_PAYLOAD = (int) YmlUtil.get("socket.max-frame-payload"); - public static final int MAX_HTTP_CONTENT = (int) YmlUtil.get("socket.max-http-content"); - public static final String EVENT_LOGOUT = (String) YmlUtil.get("socket.event.logout"); - public static final String EVENT_NEW_MESSAGE = (String) YmlUtil.get("socket.event.new-message"); + public static String REDIS_EVENT_TOPIC_SEND = "socket:event:send"; + public static int REDIS_EVENT_SPECIFIC = 0; + public static int REDIS_EVENT_BROADCAST = 1; + public static int REDIS_EVENT_LOGOUT = 2; + + public static String REDIS_ONLINE_NUM = "socket:online-num"; + public static String REDIS_ONLINE_USER = "socket:online-user"; + + public static final String EVENT_LOGOUT = "logout"; + public static final String EVENT_NEW_MESSAGE = "new-message"; } diff --git a/java/src/main/java/com/toesbieya/my/controller/AccountController.java b/java/src/main/java/com/toesbieya/my/controller/AccountController.java index ece1492..8a9bced 100644 --- a/java/src/main/java/com/toesbieya/my/controller/AccountController.java +++ b/java/src/main/java/com/toesbieya/my/controller/AccountController.java @@ -1,115 +1,89 @@ package com.toesbieya.my.controller; -import com.toesbieya.my.enumeration.RecLoginHistoryEnum; -import com.toesbieya.my.model.entity.SysUser; -import com.toesbieya.my.model.vo.update.UserUpdatePwd; -import com.toesbieya.my.service.RecService; -import com.toesbieya.my.service.SysUserService; +import com.toesbieya.my.model.vo.LoginParam; +import com.toesbieya.my.model.vo.PasswordUpdateParam; +import com.toesbieya.my.model.vo.RegisterParam; +import com.toesbieya.my.model.vo.UserVo; +import com.toesbieya.my.service.AccountService; import com.toesbieya.my.utils.IpUtil; import com.toesbieya.my.utils.Result; -import com.toesbieya.my.utils.Util; -import org.springframework.util.DigestUtils; +import com.toesbieya.my.utils.SessionUtil; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; +import javax.validation.Valid; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; -import java.util.Map; @RestController @RequestMapping("account") public class AccountController { @Resource - private SysUserService userService; - - @Resource - private RecService recService; - - @Resource - private HttpSession session; + private AccountService accountService; @PostMapping("login") - public Result login(HttpServletRequest request, @RequestBody Map map) { - String username = map.get("username"); - String password = map.get("password"); - String err = validate(username, password); - if (err != null) return Result.fail(err); - - return userService.login(username, password, IpUtil.getIp(request)); - } - - @PostMapping("register") - public Result register(@RequestBody Map map) { - String username = map.get("username"); - String password = map.get("password"); - String err = validate(username, password); - if (err != null) return Result.fail(err); - - return userService.register(username, password); + public Result login(HttpServletRequest request, @Valid @RequestBody LoginParam param) { + return accountService.login(param, IpUtil.getIp(request)); } @GetMapping("logout") public Result logout(HttpServletRequest request) { - SysUser user = Util.getUser(); - if (user != null) { - recService.insertLoginHistory(user, IpUtil.getIp(request), RecLoginHistoryEnum.LOGOUT); - } - session.invalidate(); - return Result.success("登出成功"); + UserVo user = SessionUtil.get(); + return accountService.logout(user, IpUtil.getIp(request)); + } + + @PostMapping("register") + public Result register(@Valid @RequestBody RegisterParam param) { + return accountService.register(param); } @PostMapping("updatePwd") - public Result updatePwd(@RequestBody UserUpdatePwd vo) { - SysUser user = Util.getUser(); - vo.setId(user.getId()); + public Result updatePwd(@RequestBody PasswordUpdateParam param) { + UserVo user = SessionUtil.get(); + param.setId(user.getId()); - String errMsg = validateUpdatePwdParam(vo); + String errMsg = validateUpdatePwdParam(param); if (errMsg != null) return Result.fail(errMsg); - vo.setOld_pwd(DigestUtils.md5DigestAsHex(vo.getOld_pwd().getBytes())); - vo.setNew_pwd(DigestUtils.md5DigestAsHex(vo.getNew_pwd().getBytes())); - - return userService.updatePwd(vo); + return accountService.updatePwd(param); } @GetMapping("updateAvatar") public Result updateAvatar(@RequestParam String key) throws UnsupportedEncodingException { if (StringUtils.isEmpty(key)) return Result.fail("参数错误"); - return userService.updateAvatar(Util.getUser(), URLDecoder.decode(key, "utf-8"), Util.getSession()); + UserVo user = SessionUtil.get(); + return accountService.updateAvatar(user, URLDecoder.decode(key, "utf-8")); } @GetMapping("validate") public Result validate(@RequestParam String pwd) { - SysUser current = Util.getUser(); - if (!pwd.equals(current.getPwd())) return Result.fail("校验失败"); + UserVo current = SessionUtil.get(); + + if (!pwd.equals(current.getPwd())) { + return Result.fail("校验失败"); + } + return Result.success("校验通过"); } @GetMapping("checkName") - public Result checkName(@RequestParam String name) { - return Result.success(userService.checkName(name) ? null : "该用户名已存在"); - } - - private String validate(String username, String password) { - if ((StringUtils.isEmpty(username) - || StringUtils.isEmpty(password) - || username.length() > 20 - || password.length() != 32)) { - return "用户名或密码输入有误"; + public Result checkName(@RequestParam(required = false) Integer id, @RequestParam String name) { + if (StringUtils.isEmpty(name)) { + return Result.success(); } - return null; + + return Result.success(accountService.checkName(name, id) ? null : "该用户名已存在"); } - private String validateUpdatePwdParam(UserUpdatePwd vo) { + private String validateUpdatePwdParam(PasswordUpdateParam vo) { if (vo.getId() == null) return "修改失败,参数错误"; if (StringUtils.isEmpty(vo.getOld_pwd())) return "修改失败,原密码不能为空"; if (StringUtils.isEmpty(vo.getNew_pwd())) return "修改失败,新密码不能为空"; if (vo.getOld_pwd().equals(vo.getNew_pwd())) return "修改失败,新密码不得与旧密码相同"; - if (vo.getNew_pwd().length() < 6 || vo.getNew_pwd().length() > 32) return "修改失败,密码长度为6-32位"; + if (vo.getNew_pwd().length() != 32) return "修改失败,密码参数有误"; return null; } } diff --git a/java/src/main/java/com/toesbieya/my/controller/BizPurchaseInboundController.java b/java/src/main/java/com/toesbieya/my/controller/BizPurchaseInboundController.java index 3089570..b13b594 100644 --- a/java/src/main/java/com/toesbieya/my/controller/BizPurchaseInboundController.java +++ b/java/src/main/java/com/toesbieya/my/controller/BizPurchaseInboundController.java @@ -3,12 +3,12 @@ package com.toesbieya.my.controller; import com.toesbieya.my.enumeration.BizDocumentStatusEnum; import com.toesbieya.my.model.entity.BizPurchaseInbound; import com.toesbieya.my.model.entity.BizPurchaseInboundSub; -import com.toesbieya.my.model.entity.SysUser; +import com.toesbieya.my.model.vo.UserVo; import com.toesbieya.my.model.vo.search.PurchaseInboundSearch; import com.toesbieya.my.model.vo.update.DocumentStatusUpdate; import com.toesbieya.my.service.BizPurchaseInboundService; import com.toesbieya.my.utils.Result; -import com.toesbieya.my.utils.Util; +import com.toesbieya.my.utils.SessionUtil; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.*; @@ -51,7 +51,7 @@ public class BizPurchaseInboundController { String errMsg = validateSub(inbound.getData()); if (errMsg != null) return Result.fail(errMsg); - SysUser user = Util.getUser(); + UserVo user = SessionUtil.get(); inbound.setCid(user.getId()); inbound.setCname(user.getName()); inbound.setCtime(System.currentTimeMillis()); @@ -79,7 +79,7 @@ public class BizPurchaseInboundController { inbound.setStatus(BizDocumentStatusEnum.WAIT_VERIFY.getCode()); if (isFirst) { - SysUser user = Util.getUser(); + UserVo user = SessionUtil.get(); inbound.setCid(user.getId()); inbound.setCname(user.getName()); inbound.setCtime(System.currentTimeMillis()); @@ -89,18 +89,18 @@ public class BizPurchaseInboundController { @PostMapping("withdraw") public Result withdraw(@RequestBody DocumentStatusUpdate vo) { - return purchaseInboundService.withdraw(vo, Util.getUser()); + return purchaseInboundService.withdraw(vo, SessionUtil.get()); } @PostMapping("pass") public Result pass(@RequestBody DocumentStatusUpdate vo) { if (StringUtils.isEmpty(vo.getPid())) return Result.fail("参数错误"); - return purchaseInboundService.pass(vo, Util.getUser()); + return purchaseInboundService.pass(vo, SessionUtil.get()); } @PostMapping("reject") public Result reject(@RequestBody DocumentStatusUpdate vo) { - return purchaseInboundService.reject(vo, Util.getUser()); + return purchaseInboundService.reject(vo, SessionUtil.get()); } @GetMapping("del") diff --git a/java/src/main/java/com/toesbieya/my/controller/BizPurchaseOrderController.java b/java/src/main/java/com/toesbieya/my/controller/BizPurchaseOrderController.java index 2a8912c..22c7774 100644 --- a/java/src/main/java/com/toesbieya/my/controller/BizPurchaseOrderController.java +++ b/java/src/main/java/com/toesbieya/my/controller/BizPurchaseOrderController.java @@ -3,12 +3,12 @@ package com.toesbieya.my.controller; import com.toesbieya.my.enumeration.BizDocumentStatusEnum; import com.toesbieya.my.model.entity.BizPurchaseOrder; import com.toesbieya.my.model.entity.BizPurchaseOrderSub; -import com.toesbieya.my.model.entity.SysUser; +import com.toesbieya.my.model.vo.UserVo; import com.toesbieya.my.model.vo.search.PurchaseOrderSearch; import com.toesbieya.my.model.vo.update.DocumentStatusUpdate; import com.toesbieya.my.service.BizPurchaseOrderService; import com.toesbieya.my.utils.Result; -import com.toesbieya.my.utils.Util; +import com.toesbieya.my.utils.SessionUtil; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.*; @@ -56,9 +56,9 @@ public class BizPurchaseOrderController { String errMsg = validateSub(order.getData()); if (errMsg != null) return Result.fail(errMsg); - SysUser sysUser = Util.getUser(); - order.setCid(sysUser.getId()); - order.setCname(sysUser.getName()); + UserVo user = SessionUtil.get(); + order.setCid(user.getId()); + order.setCname(user.getName()); order.setCtime(System.currentTimeMillis()); order.setStatus(BizDocumentStatusEnum.DRAFT.getCode()); @@ -85,9 +85,9 @@ public class BizPurchaseOrderController { order.setStatus(BizDocumentStatusEnum.WAIT_VERIFY.getCode()); if (isFirst) { - SysUser sysUser = Util.getUser(); - order.setCid(sysUser.getId()); - order.setCname(sysUser.getName()); + UserVo user = SessionUtil.get(); + order.setCid(user.getId()); + order.setCname(user.getName()); order.setCtime(System.currentTimeMillis()); } @@ -96,17 +96,17 @@ public class BizPurchaseOrderController { @PostMapping("withdraw") public Result withdraw(@RequestBody DocumentStatusUpdate vo) { - return purchaseOrderService.withdraw(vo, Util.getUser()); + return purchaseOrderService.withdraw(vo, SessionUtil.get()); } @PostMapping("pass") public Result pass(@RequestBody DocumentStatusUpdate vo) { - return purchaseOrderService.pass(vo, Util.getUser()); + return purchaseOrderService.pass(vo, SessionUtil.get()); } @PostMapping("reject") public Result reject(@RequestBody DocumentStatusUpdate vo) { - return purchaseOrderService.reject(vo, Util.getUser()); + return purchaseOrderService.reject(vo, SessionUtil.get()); } @GetMapping("del") diff --git a/java/src/main/java/com/toesbieya/my/controller/BizSellOrderController.java b/java/src/main/java/com/toesbieya/my/controller/BizSellOrderController.java index a1d1a7d..8953c12 100644 --- a/java/src/main/java/com/toesbieya/my/controller/BizSellOrderController.java +++ b/java/src/main/java/com/toesbieya/my/controller/BizSellOrderController.java @@ -3,12 +3,12 @@ package com.toesbieya.my.controller; import com.toesbieya.my.enumeration.BizDocumentStatusEnum; import com.toesbieya.my.model.entity.BizSellOrder; import com.toesbieya.my.model.entity.BizSellOrderSub; -import com.toesbieya.my.model.entity.SysUser; +import com.toesbieya.my.model.vo.UserVo; import com.toesbieya.my.model.vo.search.SellOrderSearch; import com.toesbieya.my.model.vo.update.DocumentStatusUpdate; import com.toesbieya.my.service.BizSellOrderService; import com.toesbieya.my.utils.Result; -import com.toesbieya.my.utils.Util; +import com.toesbieya.my.utils.SessionUtil; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.*; @@ -56,7 +56,7 @@ public class BizSellOrderController { String errMsg = validateSub(order.getData()); if (errMsg != null) return Result.fail(errMsg); - SysUser user = Util.getUser(); + UserVo user = SessionUtil.get(); order.setCid(user.getId()); order.setCname(user.getName()); @@ -86,7 +86,8 @@ public class BizSellOrderController { order.setStatus(BizDocumentStatusEnum.WAIT_VERIFY.getCode()); if (isFirst) { - SysUser user = Util.getUser(); + UserVo user = SessionUtil.get(); + order.setCid(user.getId()); order.setCname(user.getName()); order.setCtime(System.currentTimeMillis()); @@ -97,17 +98,17 @@ public class BizSellOrderController { @PostMapping("withdraw") public Result withdraw(@RequestBody DocumentStatusUpdate vo) { - return sellOrderService.withdraw(vo, Util.getUser()); + return sellOrderService.withdraw(vo, SessionUtil.get()); } @PostMapping("pass") public Result pass(@RequestBody DocumentStatusUpdate vo) { - return sellOrderService.pass(vo, Util.getUser()); + return sellOrderService.pass(vo, SessionUtil.get()); } @PostMapping("reject") public Result reject(@RequestBody DocumentStatusUpdate vo) { - return sellOrderService.reject(vo, Util.getUser()); + return sellOrderService.reject(vo, SessionUtil.get()); } @GetMapping("del") diff --git a/java/src/main/java/com/toesbieya/my/controller/BizSellOutboundController.java b/java/src/main/java/com/toesbieya/my/controller/BizSellOutboundController.java index 0b39bf3..a746c74 100644 --- a/java/src/main/java/com/toesbieya/my/controller/BizSellOutboundController.java +++ b/java/src/main/java/com/toesbieya/my/controller/BizSellOutboundController.java @@ -3,12 +3,12 @@ package com.toesbieya.my.controller; import com.toesbieya.my.enumeration.BizDocumentStatusEnum; import com.toesbieya.my.model.entity.BizSellOutbound; import com.toesbieya.my.model.entity.BizSellOutboundSub; -import com.toesbieya.my.model.entity.SysUser; +import com.toesbieya.my.model.vo.UserVo; import com.toesbieya.my.model.vo.search.SellOutboundSearch; import com.toesbieya.my.model.vo.update.DocumentStatusUpdate; import com.toesbieya.my.service.BizSellOutboundService; import com.toesbieya.my.utils.Result; -import com.toesbieya.my.utils.Util; +import com.toesbieya.my.utils.SessionUtil; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.*; @@ -51,7 +51,8 @@ public class BizSellOutboundController { String errMsg = validateSub(outbound.getData()); if (errMsg != null) return Result.fail(errMsg); - SysUser user = Util.getUser(); + UserVo user = SessionUtil.get(); + outbound.setCid(user.getId()); outbound.setCname(user.getName()); outbound.setCtime(System.currentTimeMillis()); @@ -79,9 +80,10 @@ public class BizSellOutboundController { outbound.setStatus(BizDocumentStatusEnum.WAIT_VERIFY.getCode()); if (isFirst) { - SysUser sysUser = Util.getUser(); - outbound.setCid(sysUser.getId()); - outbound.setCname(sysUser.getName()); + UserVo user = SessionUtil.get(); + + outbound.setCid(user.getId()); + outbound.setCname(user.getName()); outbound.setCtime(System.currentTimeMillis()); } return sellOutboundService.commit(outbound); @@ -89,18 +91,18 @@ public class BizSellOutboundController { @PostMapping("withdraw") public Result withdraw(@RequestBody DocumentStatusUpdate vo) { - return sellOutboundService.withdraw(vo, Util.getUser()); + return sellOutboundService.withdraw(vo, SessionUtil.get()); } @PostMapping("pass") public Result pass(@RequestBody DocumentStatusUpdate vo) { if (StringUtils.isEmpty(vo.getPid())) return Result.fail("参数错误"); - return sellOutboundService.pass(vo, Util.getUser()); + return sellOutboundService.pass(vo, SessionUtil.get()); } @PostMapping("reject") public Result reject(@RequestBody DocumentStatusUpdate vo) { - return sellOutboundService.reject(vo, Util.getUser()); + return sellOutboundService.reject(vo, SessionUtil.get()); } @GetMapping("del") diff --git a/java/src/main/java/com/toesbieya/my/controller/MonitorController.java b/java/src/main/java/com/toesbieya/my/controller/MonitorController.java deleted file mode 100644 index bd49907..0000000 --- a/java/src/main/java/com/toesbieya/my/controller/MonitorController.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.toesbieya.my.controller; - -import com.toesbieya.my.utils.MonitorUtil; -import com.toesbieya.my.utils.Result; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -@RestController -@RequestMapping("system/monitor") -public class MonitorController { - - @GetMapping("get") - public Result get() { - return Result.success(MonitorUtil.getMonitorInfo()); - } -} diff --git a/java/src/main/java/com/toesbieya/my/controller/MsgController.java b/java/src/main/java/com/toesbieya/my/controller/MsgController.java index 06bf6de..29e1360 100644 --- a/java/src/main/java/com/toesbieya/my/controller/MsgController.java +++ b/java/src/main/java/com/toesbieya/my/controller/MsgController.java @@ -2,12 +2,12 @@ package com.toesbieya.my.controller; import com.toesbieya.my.constant.MsgConstant; import com.toesbieya.my.model.entity.Msg; -import com.toesbieya.my.model.entity.SysUser; +import com.toesbieya.my.model.vo.UserVo; import com.toesbieya.my.model.vo.search.MsgPersonalSearch; import com.toesbieya.my.model.vo.search.MsgSearch; import com.toesbieya.my.service.MsgService; import com.toesbieya.my.utils.Result; -import com.toesbieya.my.utils.Util; +import com.toesbieya.my.utils.SessionUtil; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.*; @@ -29,7 +29,8 @@ public class MsgController { String errMsg = validateAdd(msg); if (errMsg != null) return Result.fail(errMsg); - SysUser user = Util.getUser(); + UserVo user = SessionUtil.get(); + setAddInfo(user, msg); return msgService.add(msg); @@ -52,8 +53,10 @@ public class MsgController { if (errMsg == null && !isFirstCreate) errMsg = validateUpdate(msg); if (errMsg != null) return Result.fail(errMsg); - SysUser user = Util.getUser(); + UserVo user = SessionUtil.get(); + if (isFirstCreate) setAddInfo(user, msg); + msg.setPid(user.getId()); msg.setPname(user.getName()); msg.setPtime(System.currentTimeMillis()); @@ -66,7 +69,8 @@ public class MsgController { public Result withdraw(@RequestBody Msg msg) { if (msg.getId() == null) return Result.fail("参数错误"); - SysUser user = Util.getUser(); + UserVo user = SessionUtil.get(); + msg.setWid(user.getId()); msg.setWname(user.getName()); msg.setWtime(System.currentTimeMillis()); @@ -82,23 +86,25 @@ public class MsgController { @PostMapping("user/search") public Result searchPersonal(@RequestBody MsgPersonalSearch vo) { - SysUser user = Util.getUser(); + UserVo user = SessionUtil.get(); + vo.setUid(user.getId()); vo.setCtime(user.getCtime()); + return Result.success(msgService.searchPersonal(vo)); } @GetMapping("user/read") public Result read(@RequestParam Integer id) { - return msgService.read(Util.getUser(), id); + return msgService.read(SessionUtil.get(), id); } @GetMapping("user/readAll") public Result readAll() { - return msgService.readAll(Util.getUser()); + return msgService.readAll(SessionUtil.get()); } - private void setAddInfo(SysUser user, Msg msg) { + private void setAddInfo(UserVo user, Msg msg) { msg.setCid(user.getId()); msg.setCname(user.getName()); msg.setCtime(System.currentTimeMillis()); diff --git a/java/src/main/java/com/toesbieya/my/controller/RecController.java b/java/src/main/java/com/toesbieya/my/controller/RecController.java index af72423..744c2a4 100644 --- a/java/src/main/java/com/toesbieya/my/controller/RecController.java +++ b/java/src/main/java/com/toesbieya/my/controller/RecController.java @@ -1,12 +1,12 @@ package com.toesbieya.my.controller; -import com.toesbieya.my.model.entity.SysUser; +import com.toesbieya.my.model.vo.UserVo; import com.toesbieya.my.model.vo.search.LoginHistorySearch; import com.toesbieya.my.model.vo.search.UserActionSearch; import com.toesbieya.my.service.RecService; import com.toesbieya.my.utils.DateUtil; import com.toesbieya.my.utils.Result; -import com.toesbieya.my.utils.Util; +import com.toesbieya.my.utils.SessionUtil; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; @@ -22,7 +22,8 @@ public class RecController { @PostMapping("searchLoginHistory") public Result searchLoginHistory(@RequestBody LoginHistorySearch vo) { - SysUser user = Util.getUser(); + UserVo user = SessionUtil.get(); + vo.setUid(user.getId()); vo.setStartTime(DateUtil.getTimestampBeforeNow(7)); @@ -31,7 +32,8 @@ public class RecController { @PostMapping("searchUserAction") public Result searchUserAction(@RequestBody UserActionSearch vo) { - SysUser user = Util.getUser(); + UserVo user = SessionUtil.get(); + vo.setUid(user.getId()); vo.setStartTime(DateUtil.getTimestampBeforeNow(7)); diff --git a/java/src/main/java/com/toesbieya/my/controller/SysDepartmentController.java b/java/src/main/java/com/toesbieya/my/controller/SysDepartmentController.java index e37c662..02271de 100644 --- a/java/src/main/java/com/toesbieya/my/controller/SysDepartmentController.java +++ b/java/src/main/java/com/toesbieya/my/controller/SysDepartmentController.java @@ -28,8 +28,7 @@ public class SysDepartmentController { public Result add(@RequestBody SysDepartment department) { if (null == department.getPid() || StringUtils.isEmpty(department.getName()) - || null == department.getStatus() - ) { + || null == department.getStatus()) { return Result.fail("添加失败,参数错误"); } return departmentService.add(department); @@ -40,8 +39,7 @@ public class SysDepartmentController { if (null == department.getId() || null == department.getPid() || StringUtils.isEmpty(department.getName()) - || null == department.getStatus() - ) { + || null == department.getStatus()) { return Result.fail("修改失败,参数错误"); } return departmentService.update(department); diff --git a/java/src/main/java/com/toesbieya/my/controller/SysRoleController.java b/java/src/main/java/com/toesbieya/my/controller/SysRoleController.java index 57c1e92..deed936 100644 --- a/java/src/main/java/com/toesbieya/my/controller/SysRoleController.java +++ b/java/src/main/java/com/toesbieya/my/controller/SysRoleController.java @@ -1,24 +1,21 @@ package com.toesbieya.my.controller; import com.toesbieya.my.model.entity.SysRole; -import com.toesbieya.my.model.entity.SysUser; +import com.toesbieya.my.model.vo.UserVo; import com.toesbieya.my.model.vo.search.RoleSearch; import com.toesbieya.my.service.SysRoleService; import com.toesbieya.my.utils.Result; -import com.toesbieya.my.utils.Util; +import com.toesbieya.my.utils.SessionUtil; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; -import javax.servlet.http.HttpSession; @RequestMapping("system/role") @RestController public class SysRoleController { @Resource private SysRoleService roleService; - @Resource - private HttpSession session; @GetMapping("get") public Result get() { @@ -37,7 +34,8 @@ public class SysRoleController { return Result.fail("添加失败,参数错误"); } - SysUser user = Util.getUser(); + UserVo user = SessionUtil.get(); + role.setCid(user.getId()); role.setCname(user.getName()); role.setCtime(System.currentTimeMillis()); diff --git a/java/src/main/java/com/toesbieya/my/controller/SysUserController.java b/java/src/main/java/com/toesbieya/my/controller/SysUserController.java index e9dca0c..85cbcb9 100644 --- a/java/src/main/java/com/toesbieya/my/controller/SysUserController.java +++ b/java/src/main/java/com/toesbieya/my/controller/SysUserController.java @@ -42,7 +42,6 @@ public class SysUserController { if (errMsg != null) { return Result.fail(errMsg); } - userService.setUpdateAction(user); return userService.update(user); } diff --git a/java/src/main/java/com/toesbieya/my/interceptor/RateControlInterceptor.java b/java/src/main/java/com/toesbieya/my/interceptor/RateControlInterceptor.java index 3d4f4d8..4e52dd5 100644 --- a/java/src/main/java/com/toesbieya/my/interceptor/RateControlInterceptor.java +++ b/java/src/main/java/com/toesbieya/my/interceptor/RateControlInterceptor.java @@ -1,11 +1,8 @@ package com.toesbieya.my.interceptor; -import com.toesbieya.my.model.entity.SysUser; +import com.toesbieya.my.model.vo.UserVo; import com.toesbieya.my.module.request.RequestModule; -import com.toesbieya.my.utils.IpUtil; -import com.toesbieya.my.utils.Result; -import com.toesbieya.my.utils.ThreadUtil; -import com.toesbieya.my.utils.Util; +import com.toesbieya.my.utils.*; import lombok.extern.slf4j.Slf4j; import org.springframework.web.servlet.HandlerInterceptor; @@ -16,29 +13,34 @@ import javax.servlet.http.HttpServletResponse; public class RateControlInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { - SysUser user = ThreadUtil.getUser(); + UserVo user = SessionUtil.get(request); + if (user.getAdmin() == 1) return true; String url = request.getServletPath(); String ip = IpUtil.getIp(request); + int result = RequestModule.pass(url, ip); + switch (result) { case -1: log.warn("限流拦截,服务的总请求频率超出,url:{},用户:{},ip:{}", url, user.getName(), ip); - Util.responseJson(response, Result.overload()); + WebUtil.responseJson(response, Result.overload()); break; case 0: log.warn("限流拦截,ip已被暂时拉黑,url:{},用户:{},ip:{}", url, user.getName(), ip); - Util.responseJson(response, Result.tooManyRequest()); + WebUtil.responseJson(response, Result.tooManyRequest()); break; case -2: log.warn("限流拦截,ip的请求频率超出,url:{},用户:{},ip:{}", url, user.getName(), ip); - Util.responseJson(response, Result.tooManyRequest()); + WebUtil.responseJson(response, Result.tooManyRequest()); break; case 1: return true; } + ThreadUtil.clearUser(); + return false; } } diff --git a/java/src/main/java/com/toesbieya/my/interceptor/SecurityInterceptor.java b/java/src/main/java/com/toesbieya/my/interceptor/SecurityInterceptor.java index ed591b2..e0cf623 100644 --- a/java/src/main/java/com/toesbieya/my/interceptor/SecurityInterceptor.java +++ b/java/src/main/java/com/toesbieya/my/interceptor/SecurityInterceptor.java @@ -1,66 +1,45 @@ package com.toesbieya.my.interceptor; -import com.toesbieya.my.constant.SessionConstant; -import com.toesbieya.my.model.entity.SysUser; +import com.toesbieya.my.model.vo.UserVo; import com.toesbieya.my.module.PermissionModule; import com.toesbieya.my.module.request.RequestModule; -import com.toesbieya.my.utils.IpUtil; -import com.toesbieya.my.utils.Result; -import com.toesbieya.my.utils.ThreadUtil; -import com.toesbieya.my.utils.Util; +import com.toesbieya.my.utils.*; import lombok.extern.slf4j.Slf4j; import org.springframework.web.servlet.HandlerInterceptor; -import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; @Slf4j public class SecurityInterceptor implements HandlerInterceptor { - @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { - HttpSession httpSession = request.getSession(); String url = request.getServletPath(); String method = request.getMethod(); String ip = IpUtil.getIp(request); if (!RequestModule.urlExistMapping(url, method)) { - Util.responseJson(response, Result.notfound()); + WebUtil.responseJson(response, Result.notfound()); log.error("请求地址不存在:{},{},IP:{}", url, method, ip); ThreadUtil.clearUser(); return false; } - SysUser sysUser = Util.getUser(httpSession); - if (sysUser == null - || request.getHeader(SessionConstant.TOKEN_KEY) == null - || !request.getHeader(SessionConstant.TOKEN_KEY).equals(httpSession.getAttribute(SessionConstant.TOKEN_KEY))) { - Util.responseJson(response, Result.requireLogin()); + UserVo user = SessionUtil.get(request); + + if (user == null) { + WebUtil.responseJson(response, Result.requireLogin()); ThreadUtil.clearUser(); return false; } - if (!PermissionModule.authority(sysUser, url)) { - Util.responseJson(response, Result.noPermission()); - log.warn("权限拦截,访问路径:{},用户:{},IP:{}", url, sysUser.getName(), ip); + if (!PermissionModule.authority(user, url)) { + WebUtil.responseJson(response, Result.noPermission()); + log.warn("权限拦截,访问路径:{},用户:{},IP:{}", url, user.getName(), ip); ThreadUtil.clearUser(); return false; } - ThreadUtil.setUser(sysUser); - return true; } - - @Override - public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { - - } - - @Override - public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { - - } } diff --git a/java/src/main/java/com/toesbieya/my/mapper/SysUserMapper.java b/java/src/main/java/com/toesbieya/my/mapper/SysUserMapper.java index cb4ecdb..f064c44 100644 --- a/java/src/main/java/com/toesbieya/my/mapper/SysUserMapper.java +++ b/java/src/main/java/com/toesbieya/my/mapper/SysUserMapper.java @@ -1,18 +1,17 @@ package com.toesbieya.my.mapper; import com.toesbieya.my.model.entity.SysUser; +import com.toesbieya.my.model.vo.PasswordUpdateParam; +import com.toesbieya.my.model.vo.UserVo; import com.toesbieya.my.model.vo.search.UserSearch; -import com.toesbieya.my.model.vo.update.UserUpdatePwd; import org.apache.ibatis.annotations.Param; import java.util.List; public interface SysUserMapper { - SysUser getById(@Param("id") Integer id); - SysUser getByNameAndPwd(@Param("name") String name, @Param("pwd") String pwd); - List search(UserSearch vo); + List search(UserSearch vo); boolean isNameExist(@Param("name") String name, @Param("id") Integer id); @@ -24,7 +23,7 @@ public interface SysUserMapper { int resetPwd(@Param("id") Integer id, @Param("pwd") String pwd); - int updatePwd(UserUpdatePwd vo); + int updatePwd(PasswordUpdateParam vo); int updateAvatar(@Param("id") Integer id, @Param("avatar") String avatar); } diff --git a/java/src/main/java/com/toesbieya/my/model/entity/SysUser.java b/java/src/main/java/com/toesbieya/my/model/entity/SysUser.java index 555faf0..87072c9 100644 --- a/java/src/main/java/com/toesbieya/my/model/entity/SysUser.java +++ b/java/src/main/java/com/toesbieya/my/model/entity/SysUser.java @@ -4,37 +4,16 @@ import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; -import java.io.Serializable; -import java.util.HashSet; - @Data @AllArgsConstructor @NoArgsConstructor -public class SysUser implements Serializable { - private static final long serialVersionUID = 9527L; +public class SysUser { private Integer id; private String name; private String pwd; private Integer role; - private String role_name; private String avatar; private Long ctime; private Integer admin; private Integer status; - private Boolean online; - private HashSet resource_ids; - - public static String getUpdateInfo(SysUser origin, SysUser update) { - StringBuilder stringBuilder = new StringBuilder(); - if (!origin.getName().equals(update.getName())) { - stringBuilder.append(String.format(",名称改为【%s】", update.getName())); - } - if (!origin.getRole().equals(update.getRole())) { - stringBuilder.append(String.format(",角色改为【%s】", update.getRole_name())); - } - if (!origin.getStatus().equals(update.getStatus())) { - stringBuilder.append(String.format(",状态改为【%s】", update.getStatus() == 1 ? "正常" : "禁用")); - } - return stringBuilder.toString(); - } } diff --git a/java/src/main/java/com/toesbieya/my/model/vo/LoginParam.java b/java/src/main/java/com/toesbieya/my/model/vo/LoginParam.java new file mode 100644 index 0000000..f6104dd --- /dev/null +++ b/java/src/main/java/com/toesbieya/my/model/vo/LoginParam.java @@ -0,0 +1,17 @@ +package com.toesbieya.my.model.vo; + +import lombok.Data; +import org.hibernate.validator.constraints.Length; + +import javax.validation.constraints.NotNull; + +@Data +public class LoginParam { + @NotNull(message = "用户名不能为空") + @Length(max = 20, message = "用户名太长了") + private String username; + + @NotNull(message = "密码不能为空") + @Length(min = 32, max = 32, message = "密码异常") + private String password; +} diff --git a/java/src/main/java/com/toesbieya/my/model/vo/LoginSuccessInfo.java b/java/src/main/java/com/toesbieya/my/model/vo/LoginSuccessInfo.java new file mode 100644 index 0000000..96166a3 --- /dev/null +++ b/java/src/main/java/com/toesbieya/my/model/vo/LoginSuccessInfo.java @@ -0,0 +1,26 @@ +package com.toesbieya.my.model.vo; + +import com.toesbieya.my.model.entity.SysUser; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.Map; + +@Data +@NoArgsConstructor +public class LoginSuccessInfo { + private Integer id; + private String name; + private String role_name; + private String avatar; + private Integer admin; + private String token; + private Map resources; + + public LoginSuccessInfo(SysUser user) { + this.id = user.getId(); + this.name = user.getName(); + this.avatar = user.getAvatar(); + this.admin = user.getAdmin(); + } +} diff --git a/java/src/main/java/com/toesbieya/my/model/vo/PasswordUpdateParam.java b/java/src/main/java/com/toesbieya/my/model/vo/PasswordUpdateParam.java new file mode 100644 index 0000000..305a070 --- /dev/null +++ b/java/src/main/java/com/toesbieya/my/model/vo/PasswordUpdateParam.java @@ -0,0 +1,10 @@ +package com.toesbieya.my.model.vo; + +import lombok.Data; + +@Data +public class PasswordUpdateParam { + private Integer id; + private String new_pwd; + private String old_pwd; +} diff --git a/java/src/main/java/com/toesbieya/my/model/vo/RegisterParam.java b/java/src/main/java/com/toesbieya/my/model/vo/RegisterParam.java new file mode 100644 index 0000000..3e83f73 --- /dev/null +++ b/java/src/main/java/com/toesbieya/my/model/vo/RegisterParam.java @@ -0,0 +1,11 @@ +package com.toesbieya.my.model.vo; + +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.ToString; + +@Data +@ToString(callSuper = true) +@EqualsAndHashCode(callSuper = true) +public class RegisterParam extends LoginParam { +} diff --git a/java/src/main/java/com/toesbieya/my/model/vo/UserVo.java b/java/src/main/java/com/toesbieya/my/model/vo/UserVo.java new file mode 100644 index 0000000..8698db7 --- /dev/null +++ b/java/src/main/java/com/toesbieya/my/model/vo/UserVo.java @@ -0,0 +1,33 @@ +package com.toesbieya.my.model.vo; + +import com.toesbieya.my.model.entity.SysUser; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.NoArgsConstructor; +import lombok.ToString; + +import java.util.Map; +import java.util.Set; + +@Data +@NoArgsConstructor +@ToString(callSuper = true) +@EqualsAndHashCode(callSuper = true) +public class UserVo extends SysUser { + private String token; + private String role_name; + private boolean online = false; + private Set resource_ids; + private Map resource_map; + + public UserVo(SysUser parent) { + this.setId(parent.getId()); + this.setName(parent.getName()); + this.setPwd(parent.getPwd()); + this.setRole(parent.getRole()); + this.setAvatar(parent.getAvatar()); + this.setCtime(parent.getCtime()); + this.setAdmin(parent.getAdmin()); + this.setStatus(parent.getStatus()); + } +} diff --git a/java/src/main/java/com/toesbieya/my/model/vo/info/CpuInfo.java b/java/src/main/java/com/toesbieya/my/model/vo/info/CpuInfo.java deleted file mode 100644 index 9bd4cfa..0000000 --- a/java/src/main/java/com/toesbieya/my/model/vo/info/CpuInfo.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.toesbieya.my.model.vo.info; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import oshi.hardware.CentralProcessor; - -@Data -@AllArgsConstructor -@NoArgsConstructor -public class CpuInfo { - //cpu名称 - private String name; - //核心数 - private int core; - //内核态CPU时间 - private double system; - //用户态CPU时间 - private double user; - //低优先级用户态CPU时间 - private double nice; - //空闲时间,不包括io等待时间 - private double idle; - //等待I/O的CPU时间 - private double ioWait; - //处理硬中断的CPU时间 - private double irq; - //处理软中断的CPU时间 - private double softIrq; - //运行在虚拟机中的时候,被其他虚拟机占用的CPU时间 - private double steal; - - public CpuInfo(CentralProcessor processor, long[] prevTicks, long[] ticks) { - this.name = processor.getProcessorIdentifier().getName().trim(); - this.core = processor.getLogicalProcessorCount(); - long nice = ticks[CentralProcessor.TickType.NICE.getIndex()] - prevTicks[CentralProcessor.TickType.NICE.getIndex()]; - long irq = ticks[CentralProcessor.TickType.IRQ.getIndex()] - prevTicks[CentralProcessor.TickType.IRQ.getIndex()]; - long softIrq = ticks[CentralProcessor.TickType.SOFTIRQ.getIndex()] - prevTicks[CentralProcessor.TickType.SOFTIRQ.getIndex()]; - long steal = ticks[CentralProcessor.TickType.STEAL.getIndex()] - prevTicks[CentralProcessor.TickType.STEAL.getIndex()]; - long system = ticks[CentralProcessor.TickType.SYSTEM.getIndex()] - prevTicks[CentralProcessor.TickType.SYSTEM.getIndex()]; - long user = ticks[CentralProcessor.TickType.USER.getIndex()] - prevTicks[CentralProcessor.TickType.USER.getIndex()]; - long ioWait = ticks[CentralProcessor.TickType.IOWAIT.getIndex()] - prevTicks[CentralProcessor.TickType.IOWAIT.getIndex()]; - long idle = ticks[CentralProcessor.TickType.IDLE.getIndex()] - prevTicks[CentralProcessor.TickType.IDLE.getIndex()]; - long total = user + nice + system + idle + ioWait + irq + softIrq + steal; - this.system = system * 1.0 / total * 100; - this.nice = nice * 1.0 / total * 100; - this.user = user * 1.0 / total * 100; - this.idle = idle * 1.0 / total * 100; - this.ioWait = ioWait * 1.0 / total * 100; - this.irq = irq * 1.0 / total * 100; - this.softIrq = softIrq * 1.0 / total * 100; - this.steal = steal * 1.0 / total * 100; - } -} diff --git a/java/src/main/java/com/toesbieya/my/model/vo/info/DiskInfo.java b/java/src/main/java/com/toesbieya/my/model/vo/info/DiskInfo.java deleted file mode 100644 index 0f0396e..0000000 --- a/java/src/main/java/com/toesbieya/my/model/vo/info/DiskInfo.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.toesbieya.my.model.vo.info; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import oshi.software.os.OSFileStore; - -@Data -@AllArgsConstructor -@NoArgsConstructor -public class DiskInfo { - private String name; - private long total; - private long used; - private long remain; - private double utilizationRate; - - public DiskInfo(OSFileStore fs) { - this.name = fs.getMount(); - this.total = fs.getTotalSpace(); - this.remain = fs.getUsableSpace(); - this.used = this.total - this.remain; - this.utilizationRate = this.used * 1.0 / this.total * 100; - } -} diff --git a/java/src/main/java/com/toesbieya/my/model/vo/info/JvmInfo.java b/java/src/main/java/com/toesbieya/my/model/vo/info/JvmInfo.java deleted file mode 100644 index d8d65fd..0000000 --- a/java/src/main/java/com/toesbieya/my/model/vo/info/JvmInfo.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.toesbieya.my.model.vo.info; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -@Data -@AllArgsConstructor -@NoArgsConstructor -public class JvmInfo { - //jvm最大可申请内存 - private long max; - //jvm当前总内存 - private long total; - //已使用内存 - private long used; - //空闲内存 - private long remain; - //使用率 - private double utilizationRate; - - public JvmInfo(long max, long total, long remain) { - this.max = max; - this.total = total; - this.remain = remain; - this.used = total - remain; - this.utilizationRate = this.used * 1.0 / total * 100; - } -} diff --git a/java/src/main/java/com/toesbieya/my/model/vo/info/MemoryInfo.java b/java/src/main/java/com/toesbieya/my/model/vo/info/MemoryInfo.java deleted file mode 100644 index cbf14c9..0000000 --- a/java/src/main/java/com/toesbieya/my/model/vo/info/MemoryInfo.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.toesbieya.my.model.vo.info; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -@Data -@AllArgsConstructor -@NoArgsConstructor -public class MemoryInfo { - //总内存 - private long total; - //已使用内存 - private long used; - //剩余内存 - private long remain; - //内存使用率 - private double utilizationRate; - - public MemoryInfo(long total, long remain) { - this.total = total; - this.remain = remain; - this.used = total - remain; - this.utilizationRate = this.used * 1.0 / total * 100; - } -} diff --git a/java/src/main/java/com/toesbieya/my/model/vo/info/MonitorInfo.java b/java/src/main/java/com/toesbieya/my/model/vo/info/MonitorInfo.java deleted file mode 100644 index c08a58f..0000000 --- a/java/src/main/java/com/toesbieya/my/model/vo/info/MonitorInfo.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.toesbieya.my.model.vo.info; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -import java.util.List; - -@Data -@AllArgsConstructor -@NoArgsConstructor -public class MonitorInfo { - private OperatingInfo operatingInfo; - private CpuInfo cpuInfo; - private MemoryInfo memoryInfo; - private JvmInfo jvmInfo; - private List diskInfos; - private Long timestamp; - private Integer expire; -} diff --git a/java/src/main/java/com/toesbieya/my/model/vo/info/OperatingInfo.java b/java/src/main/java/com/toesbieya/my/model/vo/info/OperatingInfo.java deleted file mode 100644 index 43e0f8c..0000000 --- a/java/src/main/java/com/toesbieya/my/model/vo/info/OperatingInfo.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.toesbieya.my.model.vo.info; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import oshi.software.os.OperatingSystem; - -@Data -@AllArgsConstructor -@NoArgsConstructor -public class OperatingInfo { - private long bootedTime; - private long upTime; - - public OperatingInfo(OperatingSystem os) { - this.bootedTime = os.getSystemBootTime(); - this.upTime = os.getSystemUptime(); - } -} diff --git a/java/src/main/java/com/toesbieya/my/module/PermissionModule.java b/java/src/main/java/com/toesbieya/my/module/PermissionModule.java index 9dcce8a..bef452b 100644 --- a/java/src/main/java/com/toesbieya/my/module/PermissionModule.java +++ b/java/src/main/java/com/toesbieya/my/module/PermissionModule.java @@ -1,20 +1,18 @@ package com.toesbieya.my.module; import com.toesbieya.my.model.entity.SysResource; -import com.toesbieya.my.model.entity.SysUser; +import com.toesbieya.my.model.vo.UserVo; import com.toesbieya.my.service.SysResourceService; import lombok.extern.slf4j.Slf4j; -import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import javax.annotation.Resource; import java.time.Instant; import java.time.temporal.ChronoUnit; -import java.util.HashSet; import java.util.List; +import java.util.Set; import java.util.concurrent.ConcurrentHashMap; -@Component @Slf4j public class PermissionModule { private final static ConcurrentHashMap urlMap = new ConcurrentHashMap<>(128); @@ -22,13 +20,17 @@ public class PermissionModule { @Resource private SysResourceService resourceService; - public static boolean authority(SysUser sysUser, String url) { - if (sysUser.getAdmin() == 1 || !needAuthority(url)) { + public static boolean authority(UserVo user, String url) { + if (user.getAdmin() == 1 || !needAuthority(url)) { return true; } + if (adminUrlMap.containsKey(url)) return false; - HashSet ids = sysUser.getResource_ids(); + + Set ids = user.getResource_ids(); + if (ids == null) return false; + return ids.contains(urlMap.get(url)); } @@ -41,6 +43,7 @@ public class PermissionModule { Instant start = Instant.now(); List resources = resourceService.getAll(); + if (resources != null) { for (SysResource p : resources) { if (p.getAdmin() == 1) { @@ -49,7 +52,9 @@ public class PermissionModule { else urlMap.put(p.getUrl(), p.getId()); } } + Instant end = Instant.now(); + log.info("权限模块启动成功,耗时:{}毫秒", ChronoUnit.MILLIS.between(start, end)); } } diff --git a/java/src/main/java/com/toesbieya/my/module/redis/RedisModule.java b/java/src/main/java/com/toesbieya/my/module/RedisModule.java similarity index 69% rename from java/src/main/java/com/toesbieya/my/module/redis/RedisModule.java rename to java/src/main/java/com/toesbieya/my/module/RedisModule.java index 836af5a..c44bf75 100644 --- a/java/src/main/java/com/toesbieya/my/module/redis/RedisModule.java +++ b/java/src/main/java/com/toesbieya/my/module/RedisModule.java @@ -1,5 +1,6 @@ -package com.toesbieya.my.module.redis; +package com.toesbieya.my.module; +import com.toesbieya.my.constant.DocumentConstant; import com.toesbieya.my.utils.DateUtil; import com.toesbieya.my.utils.RedisUtil; import lombok.extern.slf4j.Slf4j; @@ -19,9 +20,6 @@ import java.util.Map; @Slf4j @DependsOn("redisUtil") public class RedisModule { - public static final String DOCUMENTS_KEY = "documentsID"; - public static final String[] DOCUMENTS_TYPE = {"CGDD", "CGRK", "CGTH", "XSDD", "XSCK", "XSTH"}; - @PostConstruct public void init() { Instant start = Instant.now(); @@ -34,17 +32,17 @@ public class RedisModule { //初始化单据ID private void initDocumentsID() { - String[] fields = new String[DOCUMENTS_TYPE.length + 1]; + String[] fields = new String[DocumentConstant.DOCUMENT_TYPE.length + 1]; fields[0] = "date"; - System.arraycopy(DOCUMENTS_TYPE, 0, fields, 1, fields.length - 1); - List result = RedisUtil.hmget(DOCUMENTS_KEY, fields); + System.arraycopy(DocumentConstant.DOCUMENT_TYPE, 0, fields, 1, fields.length - 1); + List result = RedisUtil.hmget(DocumentConstant.DOCUMENT_TYPE_REDIS_KEY, fields); long now = DateUtil.getTimestampNow(); //日期不是今天时,更新全部,初始值为1 if (null == result.get(0) || now != (long) result.get(0)) { updateAllDocument(now); - log.info("更新【{}】种单据ID成功", DOCUMENTS_TYPE.length); + log.info("更新【{}】种单据ID成功", DocumentConstant.DOCUMENT_TYPE.length); return; } @@ -55,11 +53,11 @@ public class RedisModule { for (int i = 1; i < resultSize; i++) { if (result.get(i) == null) { updateNum++; - update.put(DOCUMENTS_TYPE[i - 1], 1); + update.put(DocumentConstant.DOCUMENT_TYPE[i - 1], 1); } } if (updateNum > 0) { - RedisUtil.hmset(DOCUMENTS_KEY, update); + RedisUtil.hmset(DocumentConstant.DOCUMENT_TYPE_REDIS_KEY, update); log.info("更新增加的单据【{}】种", updateNum); } } @@ -67,24 +65,30 @@ public class RedisModule { private void updateAllDocument(long now) { Map map = new HashMap<>(); map.put("date", now); - for (String v : DOCUMENTS_TYPE) { + for (String v : DocumentConstant.DOCUMENT_TYPE) { map.put(v, 1); } - RedisUtil.hmset(DOCUMENTS_KEY, map); + RedisUtil.hmset(DocumentConstant.DOCUMENT_TYPE_REDIS_KEY, map); } //每天零点初始化单据ID @Async("scheduledExecutor") @Scheduled(cron = "1 0 0 */1 * ?") public void autoRefreshDocumentID() { - log.info("开始定时更新单据ID......当前共有【{}】种待更新......", DOCUMENTS_TYPE.length); - try (LockHelper locker = new RedisLockHelper(RedisLockType.UPDATE_DOCUMENT_ID)) { + log.info("开始定时更新单据ID......当前共有【{}】种待更新......", DocumentConstant.DOCUMENT_TYPE.length); + + String lockKey = DocumentConstant.UPDATE_DOCUMENTS_LOCK_KEY; + + try (RedisUtil.Locker locker = new RedisUtil.Locker(lockKey)) { + if (!locker.lock()) { - log.error("定时更新单据ID失败,获取锁【{}】失败", RedisLockType.UPDATE_DOCUMENT_ID); + log.error("定时更新单据ID失败,获取锁【{}】失败", lockKey); return; } + updateAllDocument(DateUtil.getTimestampNow()); - log.info("定时更新单据ID结束,成功更新【{}】种", DOCUMENTS_TYPE.length); + + log.info("定时更新单据ID结束,成功更新【{}】种", DocumentConstant.DOCUMENT_TYPE.length); } catch (Exception e) { log.error("定时更新单据ID失败", e); } diff --git a/java/src/main/java/com/toesbieya/my/module/SocketModule.java b/java/src/main/java/com/toesbieya/my/module/SocketModule.java index 56c3910..2bad309 100644 --- a/java/src/main/java/com/toesbieya/my/module/SocketModule.java +++ b/java/src/main/java/com/toesbieya/my/module/SocketModule.java @@ -6,9 +6,8 @@ import com.corundumstudio.socketio.SocketIOServer; import com.corundumstudio.socketio.annotation.OnConnect; import com.corundumstudio.socketio.annotation.OnDisconnect; import com.corundumstudio.socketio.annotation.OnEvent; -import com.toesbieya.my.constant.SessionConstant; import com.toesbieya.my.constant.SocketConstant; -import com.toesbieya.my.utils.RedisUtil; +import com.toesbieya.my.utils.SessionUtil; import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; @@ -23,7 +22,7 @@ import java.util.function.BiConsumer; @Component @Slf4j public class SocketModule { - private static final ConcurrentHashMap socketMap = new ConcurrentHashMap<>(SessionConstant.PREDICT_MAX_USER); + private static final ConcurrentHashMap socketMap = new ConcurrentHashMap<>(128); private static SocketIOServer server; @Autowired @@ -38,10 +37,15 @@ public class SocketModule { public static void sendEvent(String event, Integer uid, Object data, BiConsumer consumer) { UserObject obj = socketMap.get(uid); + if (obj == null) return; + SocketIOClient client = server.getClient(obj.getUuid()); + if (client == null) return; + client.sendEvent(event, data); + if (consumer != null) consumer.accept(obj, client); } @@ -53,11 +57,26 @@ public class SocketModule { return uid != null && socketMap.containsKey(uid); } + public static void logout(Integer uid, String msg) { + sendEvent(SocketConstant.EVENT_LOGOUT, uid, msg, (obj, client) -> { + SessionUtil.remove(obj.getToken()); + client.disconnect(); + socketMap.remove(uid); + }); + } + + public static int getOnlineNum() { + return socketMap.size(); + } + @OnConnect public void onConnect(SocketIOClient client) { UserObject obj = new UserObject(client); Integer uid = obj.getUid(); - if (socketMap.containsKey(uid)) logout(uid, "该账号在其他位置登录"); + + if (socketMap.containsKey(uid)) { + logout(uid, "该账号在其他位置登录"); + } else socketMap.put(uid, obj); } @@ -66,48 +85,32 @@ public class SocketModule { UserObject obj = new UserObject(client); Integer uid = obj.getUid(); UserObject already = socketMap.get(uid); + if (already == null) return; - //只有sessionID相同时才移除 - if (obj.getSessionID().equals(already.getSessionID())) { + + //只有token相同时才移除 + if (obj.getToken().equals(already.getToken())) { socketMap.remove(uid); } } @OnEvent("text") public void onEvent(SocketIOClient client, AckRequest ackRequest, String data) { - System.out.println(getIp(client) + ":客户端:************" + data); client.sendEvent("response", "后台得到了数据"); } - public static void logout(Integer uid, String msg) { - sendEvent(SocketConstant.EVENT_LOGOUT, uid, msg, (obj, client) -> { - RedisUtil.expire(SessionConstant.REDIS_NAMESPACE + obj.getSessionID()); - client.disconnect(); - socketMap.remove(uid); - }); - } - - public static int getOnlineNum() { - return socketMap.size(); - } - - private String getIp(SocketIOClient client) { - String sa = client.getRemoteAddress().toString(); - return sa.substring(1, sa.indexOf(":")); - } - @Data private static class UserObject { - private Integer uid;//用户id - private String sessionID;//redis中的sessionID - private UUID uuid;//socketClient自己的sessionID + private Integer uid; //用户id + private String token; //redis中的token + private UUID uuid; //socketClient自己的sessionID public UserObject(SocketIOClient client) { Map> params = client.getHandshakeData().getUrlParams(); List list = params.get("id"); this.uid = Integer.valueOf(list.get(0)); - list = params.get("session_id"); - this.sessionID = list.get(0); + list = params.get("token"); + this.token = list.get(0); this.uuid = client.getSessionId(); } } diff --git a/java/src/main/java/com/toesbieya/my/module/redis/LockHelper.java b/java/src/main/java/com/toesbieya/my/module/redis/LockHelper.java deleted file mode 100644 index 9d0f324..0000000 --- a/java/src/main/java/com/toesbieya/my/module/redis/LockHelper.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.toesbieya.my.module.redis; - -import java.io.Closeable; - -public interface LockHelper extends Closeable { - String LOCK_LUA_SCRIPT = "return redis.call('set',KEYS[1],ARGV[1],'EX',ARGV[2],'NX')"; - String UNLOCK_LUA_SCRIPT = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return false end"; - - @Override - void close(); - - boolean lock(); - - void unlock(); -} diff --git a/java/src/main/java/com/toesbieya/my/module/redis/RedisLockHelper.java b/java/src/main/java/com/toesbieya/my/module/redis/RedisLockHelper.java deleted file mode 100644 index de577e0..0000000 --- a/java/src/main/java/com/toesbieya/my/module/redis/RedisLockHelper.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.toesbieya.my.module.redis; - -import com.toesbieya.my.utils.RedisUtil; -import lombok.extern.slf4j.Slf4j; -import org.springframework.data.redis.core.StringRedisTemplate; -import org.springframework.data.redis.core.script.DefaultRedisScript; -import org.springframework.data.redis.core.script.RedisScript; - -import java.util.Collections; -import java.util.Objects; - -@Slf4j -public class RedisLockHelper implements LockHelper { - private final StringRedisTemplate template = RedisUtil.getStringRedisTemplate(); - private final String key; - private final String value; - private final String expire; - - public RedisLockHelper(String key) { - this.key = "lock:" + key; - this.value = String.valueOf(System.currentTimeMillis()); - this.expire = "300"; - } - - @Override - public void close() { - unlock(); - } - - @Override - public boolean lock() { - RedisScript redisScript = new DefaultRedisScript<>(LockHelper.LOCK_LUA_SCRIPT, Boolean.class); - Boolean result = template.execute(redisScript, Collections.singletonList(key), value, expire); - return Objects.equals(result, true); - } - - @Override - public void unlock() { - RedisScript redisScript = new DefaultRedisScript<>(LockHelper.UNLOCK_LUA_SCRIPT, Boolean.class); - Boolean result = template.execute(redisScript, Collections.singletonList(key), value); - if (result == null || !result) { - log.error("redis锁释放失败,key:{},value:{}", key, value); - } - } -} diff --git a/java/src/main/java/com/toesbieya/my/module/redis/RedisLockType.java b/java/src/main/java/com/toesbieya/my/module/redis/RedisLockType.java deleted file mode 100644 index 4ad6f96..0000000 --- a/java/src/main/java/com/toesbieya/my/module/redis/RedisLockType.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.toesbieya.my.module.redis; - -public class RedisLockType { - public static final String UPDATE_DOCUMENT_ID = "UPDATE_DOCUMENTS"; -} diff --git a/java/src/main/java/com/toesbieya/my/service/AccountService.java b/java/src/main/java/com/toesbieya/my/service/AccountService.java new file mode 100644 index 0000000..fb7fa33 --- /dev/null +++ b/java/src/main/java/com/toesbieya/my/service/AccountService.java @@ -0,0 +1,145 @@ +package com.toesbieya.my.service; + +import com.toesbieya.my.annoation.UserAction; +import com.toesbieya.my.enumeration.GeneralStatusEnum; +import com.toesbieya.my.enumeration.RecLoginHistoryEnum; +import com.toesbieya.my.mapper.SysUserMapper; +import com.toesbieya.my.model.entity.SysResource; +import com.toesbieya.my.model.entity.SysUser; +import com.toesbieya.my.model.vo.*; +import com.toesbieya.my.utils.QiniuUtil; +import com.toesbieya.my.utils.Result; +import com.toesbieya.my.utils.SessionUtil; +import com.toesbieya.my.utils.Util; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; + +import javax.annotation.Resource; +import java.util.*; + +@Service +public class AccountService { + @Resource + private SysUserMapper userMapper; + @Resource + private SysResourceService resourceService; + @Resource + private RecService recService; + + public Result login(LoginParam param, String ip) { + SysUser user = userMapper.getByNameAndPwd(param.getUsername(), param.getPassword()); + + if (user == null) { + return Result.fail("用户名或密码错误"); + } + if (user.getStatus() == GeneralStatusEnum.DISABLED.getCode()) { + return Result.fail("该用户已被禁用,请联系管理员"); + } + Integer roleId = user.getRole(); + if (user.getAdmin() != 1 && roleId == null) { + return Result.fail("该用户尚未被分配角色,请联系管理员"); + } + + //设置token + String token = Util.UUID(); + + //存入redis的数据 + UserVo userVo = new UserVo(user); + userVo.setToken(token); + + //传递给前端的数据 + LoginSuccessInfo info = new LoginSuccessInfo(user); + info.setToken(token); + + Map userResourcesUrlMap = null; + + Set userResourcesIdSet = null; + + //获取用户的所有权限url + if (roleId != null) { + List resources = resourceService.getByRole(user.getRole()); + + userResourcesUrlMap = new HashMap<>(128); + userResourcesIdSet = new HashSet<>(128); + + for (SysResource resource : resources) { + Integer resourceId = resource.getId(); + userResourcesUrlMap.put(resource.getUrl(), resourceId); + userResourcesIdSet.add(resourceId); + } + } + + userVo.setResource_ids(userResourcesIdSet); + + info.setResources(userResourcesUrlMap); + + //用户信息插入redis + SessionUtil.save(userVo); + + //记录登陆信息 + recService.insertLoginHistory(userVo, ip, RecLoginHistoryEnum.LOGIN); + + return Result.success(info); + } + + public Result logout(UserVo user, String ip) { + if (user != null) { + recService.insertLoginHistory(user, ip, RecLoginHistoryEnum.LOGOUT); + SessionUtil.remove(user.getToken()); + } + + return Result.success("登出成功"); + } + + public Result register(RegisterParam param) { + String name = param.getUsername(); + + if (userMapper.isNameExist(name, null)) { + return Result.fail("该用户名称已存在"); + } + + SysUser user = new SysUser(); + user.setName(name); + user.setPwd(param.getPassword()); + user.setRole(1); + user.setStatus(GeneralStatusEnum.ENABLED.getCode()); + user.setCtime(System.currentTimeMillis()); + + userMapper.add(user); + + return Result.success("注册成功"); + } + + @UserAction("'修改密码'") + public Result updatePwd(PasswordUpdateParam param) { + int rows = userMapper.updatePwd(param); + return rows > 0 ? Result.success("修改成功") : Result.fail("修改失败,请检查原密码是否正确"); + } + + @UserAction("'修改头像'") + public Result updateAvatar(UserVo user, String avatar) { + int rows = userMapper.updateAvatar(user.getId(), avatar); + + //更新成功后删除云上旧的头像,同时更新redis中的用户信息 + if (rows > 0) { + String oldAvatar = user.getAvatar(); + if (!StringUtils.isEmpty(oldAvatar)) { + QiniuUtil.delete(oldAvatar); + } + + user.setAvatar(avatar); + SessionUtil.save(user); + + return Result.success("上传头像成功"); + } + + //否则删除此次上传至云的头像 + QiniuUtil.delete(avatar); + + return Result.fail("上传头像失败"); + } + + public boolean checkName(String name, Integer id) { + return !userMapper.isNameExist(name, id); + } +} diff --git a/java/src/main/java/com/toesbieya/my/service/BizPurchaseInboundService.java b/java/src/main/java/com/toesbieya/my/service/BizPurchaseInboundService.java index 5fc29e9..e77e433 100644 --- a/java/src/main/java/com/toesbieya/my/service/BizPurchaseInboundService.java +++ b/java/src/main/java/com/toesbieya/my/service/BizPurchaseInboundService.java @@ -13,14 +13,12 @@ import com.toesbieya.my.mapper.BizPurchaseInboundMapper; import com.toesbieya.my.mapper.BizPurchaseOrderMapper; import com.toesbieya.my.mapper.BizStockMapper; import com.toesbieya.my.model.entity.*; +import com.toesbieya.my.model.vo.UserVo; import com.toesbieya.my.model.vo.export.PurchaseInboundExport; import com.toesbieya.my.model.vo.result.PageResult; import com.toesbieya.my.model.vo.search.PurchaseInboundSearch; import com.toesbieya.my.model.vo.update.DocumentStatusUpdate; -import com.toesbieya.my.utils.ExcelUtil; -import com.toesbieya.my.utils.RedisUtil; -import com.toesbieya.my.utils.Result; -import com.toesbieya.my.utils.Util; +import com.toesbieya.my.utils.*; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; @@ -108,7 +106,7 @@ public class BizPurchaseInboundService { @UserAction("'撤回采购入库单'+#vo.id") @Lock("#vo.id") @Tx - public Result withdraw(DocumentStatusUpdate vo, SysUser user) { + public Result withdraw(DocumentStatusUpdate vo, UserVo user) { String id = vo.getId(); String info = vo.getInfo(); @@ -135,7 +133,7 @@ public class BizPurchaseInboundService { @UserAction("'通过采购入库单'+#vo.id") @Lock({"#vo.pid", "#vo.id"}) @Tx - public Result pass(DocumentStatusUpdate vo, SysUser user) { + public Result pass(DocumentStatusUpdate vo, UserVo user) { String id = vo.getId(); String info = vo.getInfo(); String pid = vo.getPid(); @@ -202,7 +200,7 @@ public class BizPurchaseInboundService { @UserAction("'驳回采购入库单'+#vo.id") @Lock("#vo.id") @Tx - public Result reject(DocumentStatusUpdate vo, SysUser user) { + public Result reject(DocumentStatusUpdate vo, UserVo user) { String id = vo.getId(); String info = vo.getInfo(); @@ -240,7 +238,7 @@ public class BizPurchaseInboundService { String err = checkOrder(doc.getPid(), doc.getData()); if (err != null) return Result.fail(err); - String id = RedisUtil.getDocumentID("CGRK"); + String id = DocumentUtil.getDocumentID("CGRK"); if (StringUtils.isEmpty(id)) return Result.fail("获取单号失败"); doc.setId(id); diff --git a/java/src/main/java/com/toesbieya/my/service/BizPurchaseOrderService.java b/java/src/main/java/com/toesbieya/my/service/BizPurchaseOrderService.java index ad02bed..7edbeba 100644 --- a/java/src/main/java/com/toesbieya/my/service/BizPurchaseOrderService.java +++ b/java/src/main/java/com/toesbieya/my/service/BizPurchaseOrderService.java @@ -9,12 +9,13 @@ import com.toesbieya.my.enumeration.BizDocumentStatusEnum; import com.toesbieya.my.mapper.BizDocumentHistoryMapper; import com.toesbieya.my.mapper.BizPurchaseOrderMapper; import com.toesbieya.my.model.entity.*; +import com.toesbieya.my.model.vo.UserVo; import com.toesbieya.my.model.vo.export.PurchaseOrderExport; import com.toesbieya.my.model.vo.result.PageResult; import com.toesbieya.my.model.vo.search.PurchaseOrderSearch; import com.toesbieya.my.model.vo.update.DocumentStatusUpdate; +import com.toesbieya.my.utils.DocumentUtil; import com.toesbieya.my.utils.ExcelUtil; -import com.toesbieya.my.utils.RedisUtil; import com.toesbieya.my.utils.Result; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; @@ -99,7 +100,7 @@ public class BizPurchaseOrderService { @UserAction("'撤回采购订单'+#vo.id") @Lock("#vo.id") @Tx - public Result withdraw(DocumentStatusUpdate vo, SysUser user) { + public Result withdraw(DocumentStatusUpdate vo, UserVo user) { String id = vo.getId(); String info = vo.getInfo(); @@ -126,7 +127,7 @@ public class BizPurchaseOrderService { @UserAction("'通过采购订单'+#vo.id") @Lock("#vo.id") @Tx - public Result pass(DocumentStatusUpdate vo, SysUser user) { + public Result pass(DocumentStatusUpdate vo, UserVo user) { String id = vo.getId(); String info = vo.getInfo(); long now = System.currentTimeMillis(); @@ -154,7 +155,7 @@ public class BizPurchaseOrderService { @UserAction("'驳回采购订单'+#vo.id") @Lock("#vo.id") @Tx - public Result reject(DocumentStatusUpdate vo, SysUser user) { + public Result reject(DocumentStatusUpdate vo, UserVo user) { String id = vo.getId(); String info = vo.getInfo(); @@ -189,7 +190,7 @@ public class BizPurchaseOrderService { } private Result addOrder(BizPurchaseOrder doc) { - String id = RedisUtil.getDocumentID("CGDD"); + String id = DocumentUtil.getDocumentID("CGDD"); if (StringUtils.isEmpty(id)) return Result.fail("获取单号失败"); doc.setId(id); diff --git a/java/src/main/java/com/toesbieya/my/service/BizSellOrderService.java b/java/src/main/java/com/toesbieya/my/service/BizSellOrderService.java index 370308b..61c68de 100644 --- a/java/src/main/java/com/toesbieya/my/service/BizSellOrderService.java +++ b/java/src/main/java/com/toesbieya/my/service/BizSellOrderService.java @@ -10,14 +10,15 @@ import com.toesbieya.my.mapper.BizDocumentHistoryMapper; import com.toesbieya.my.mapper.BizSellOrderMapper; import com.toesbieya.my.mapper.BizStockMapper; import com.toesbieya.my.model.entity.*; +import com.toesbieya.my.model.vo.UserVo; import com.toesbieya.my.model.vo.export.SellOrderExport; import com.toesbieya.my.model.vo.result.PageResult; import com.toesbieya.my.model.vo.result.StockSearchResult; import com.toesbieya.my.model.vo.search.SellOrderSearch; import com.toesbieya.my.model.vo.search.StockSearch; import com.toesbieya.my.model.vo.update.DocumentStatusUpdate; +import com.toesbieya.my.utils.DocumentUtil; import com.toesbieya.my.utils.ExcelUtil; -import com.toesbieya.my.utils.RedisUtil; import com.toesbieya.my.utils.Result; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; @@ -107,7 +108,7 @@ public class BizSellOrderService { @UserAction("'撤回销售订单'+#vo.id") @Lock("#vo.id") @Tx - public Result withdraw(DocumentStatusUpdate vo, SysUser user) { + public Result withdraw(DocumentStatusUpdate vo, UserVo user) { String id = vo.getId(); String info = vo.getInfo(); @@ -134,7 +135,7 @@ public class BizSellOrderService { @UserAction("'通过销售订单'+#vo.id") @Lock("#vo.id") @Tx - public Result pass(DocumentStatusUpdate vo, SysUser user) { + public Result pass(DocumentStatusUpdate vo, UserVo user) { String id = vo.getId(); String info = vo.getInfo(); long now = System.currentTimeMillis(); @@ -162,7 +163,7 @@ public class BizSellOrderService { @UserAction("'驳回销售订单'+#vo.id") @Lock("#vo.id") @Tx - public Result reject(DocumentStatusUpdate vo, SysUser user) { + public Result reject(DocumentStatusUpdate vo, UserVo user) { String id = vo.getId(); String info = vo.getInfo(); @@ -200,7 +201,7 @@ public class BizSellOrderService { String err = checkStock(doc.getData()); if (err != null) return Result.fail(err); - String id = RedisUtil.getDocumentID("XSDD"); + String id = DocumentUtil.getDocumentID("XSDD"); if (StringUtils.isEmpty(id)) return Result.fail("获取单号失败"); doc.setId(id); diff --git a/java/src/main/java/com/toesbieya/my/service/BizSellOutboundService.java b/java/src/main/java/com/toesbieya/my/service/BizSellOutboundService.java index 772a8c3..cd97013 100644 --- a/java/src/main/java/com/toesbieya/my/service/BizSellOutboundService.java +++ b/java/src/main/java/com/toesbieya/my/service/BizSellOutboundService.java @@ -13,14 +13,12 @@ import com.toesbieya.my.mapper.BizSellOrderMapper; import com.toesbieya.my.mapper.BizSellOutboundMapper; import com.toesbieya.my.mapper.BizStockMapper; import com.toesbieya.my.model.entity.*; +import com.toesbieya.my.model.vo.UserVo; import com.toesbieya.my.model.vo.export.SellOutboundExport; import com.toesbieya.my.model.vo.result.PageResult; import com.toesbieya.my.model.vo.search.SellOutboundSearch; import com.toesbieya.my.model.vo.update.DocumentStatusUpdate; -import com.toesbieya.my.utils.ExcelUtil; -import com.toesbieya.my.utils.RedisUtil; -import com.toesbieya.my.utils.Result; -import com.toesbieya.my.utils.Util; +import com.toesbieya.my.utils.*; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; @@ -112,7 +110,7 @@ public class BizSellOutboundService { @UserAction("'撤回销售出库单'+#vo.id") @Lock("#vo.id") @Tx - public Result withdraw(DocumentStatusUpdate vo, SysUser user) { + public Result withdraw(DocumentStatusUpdate vo, UserVo user) { String id = vo.getId(); String info = vo.getInfo(); @@ -139,7 +137,7 @@ public class BizSellOutboundService { @UserAction("'通过销售出库单'+#vo.id") @Lock({"#vo.pid", "#vo.id"}) @Tx - public Result pass(DocumentStatusUpdate vo, SysUser user) { + public Result pass(DocumentStatusUpdate vo, UserVo user) { String id = vo.getId(); String info = vo.getInfo(); String pid = vo.getPid(); @@ -202,7 +200,7 @@ public class BizSellOutboundService { @UserAction("'驳回销售出库单'+#vo.id") @Lock("#vo.id") @Tx - public Result reject(DocumentStatusUpdate vo, SysUser user) { + public Result reject(DocumentStatusUpdate vo, UserVo user) { String id = vo.getId(); String info = vo.getInfo(); @@ -240,7 +238,7 @@ public class BizSellOutboundService { String err = check(doc.getPid(), doc.getData()); if (err != null) return Result.fail(err); - String id = RedisUtil.getDocumentID("XSCK"); + String id = DocumentUtil.getDocumentID("XSCK"); if (StringUtils.isEmpty(id)) return Result.fail("获取单号失败"); doc.setId(id); diff --git a/java/src/main/java/com/toesbieya/my/service/MsgService.java b/java/src/main/java/com/toesbieya/my/service/MsgService.java index a7cd053..121d3ce 100644 --- a/java/src/main/java/com/toesbieya/my/service/MsgService.java +++ b/java/src/main/java/com/toesbieya/my/service/MsgService.java @@ -6,7 +6,7 @@ import com.toesbieya.my.constant.SocketConstant; import com.toesbieya.my.mapper.MsgMapper; import com.toesbieya.my.model.entity.Msg; import com.toesbieya.my.model.entity.MsgState; -import com.toesbieya.my.model.entity.SysUser; +import com.toesbieya.my.model.vo.UserVo; import com.toesbieya.my.model.vo.result.PageResult; import com.toesbieya.my.model.vo.search.MsgPersonalSearch; import com.toesbieya.my.model.vo.search.MsgSearch; @@ -83,12 +83,13 @@ public class MsgService { return result; } - public Result read(SysUser user, int id) { + public Result read(UserVo user, int id) { if (msgMapper.checkRead(id, user.getId())) { return Result.success(); } MsgState state = new MsgState(); + state.setMid(id); state.setUid(user.getId()); state.setTime(System.currentTimeMillis()); @@ -96,7 +97,7 @@ public class MsgService { return Result.success(msgMapper.insertState(state)); } - public Result readAll(SysUser user) { + public Result readAll(UserVo user) { MsgPersonalSearch vo = new MsgPersonalSearch(); vo.setUid(user.getId()); vo.setCtime(user.getCtime()); diff --git a/java/src/main/java/com/toesbieya/my/service/RecService.java b/java/src/main/java/com/toesbieya/my/service/RecService.java index 52d3291..5917ccd 100644 --- a/java/src/main/java/com/toesbieya/my/service/RecService.java +++ b/java/src/main/java/com/toesbieya/my/service/RecService.java @@ -9,7 +9,7 @@ import com.toesbieya.my.mapper.RecUserActionMapper; import com.toesbieya.my.model.entity.RecAttachment; import com.toesbieya.my.model.entity.RecLoginHistory; import com.toesbieya.my.model.entity.RecUserAction; -import com.toesbieya.my.model.entity.SysUser; +import com.toesbieya.my.model.vo.UserVo; import com.toesbieya.my.model.vo.result.PageResult; import com.toesbieya.my.model.vo.search.LoginHistorySearch; import com.toesbieya.my.model.vo.search.UserActionSearch; @@ -66,7 +66,7 @@ public class RecService { } @Async("dbInsertExecutor") - public void insertLoginHistory(SysUser user, String ip, RecLoginHistoryEnum historyEnum) { + public void insertLoginHistory(UserVo user, String ip, RecLoginHistoryEnum historyEnum) { RecLoginHistory history = RecLoginHistory.builder() .uid(user.getId()) .uname(user.getName()) diff --git a/java/src/main/java/com/toesbieya/my/service/SysUserService.java b/java/src/main/java/com/toesbieya/my/service/SysUserService.java index 5838c80..228104d 100644 --- a/java/src/main/java/com/toesbieya/my/service/SysUserService.java +++ b/java/src/main/java/com/toesbieya/my/service/SysUserService.java @@ -3,29 +3,17 @@ package com.toesbieya.my.service; import com.github.pagehelper.PageHelper; import com.toesbieya.my.annoation.Tx; import com.toesbieya.my.annoation.UserAction; -import com.toesbieya.my.constant.SessionConstant; -import com.toesbieya.my.enumeration.GeneralStatusEnum; -import com.toesbieya.my.enumeration.RecLoginHistoryEnum; import com.toesbieya.my.mapper.SysUserMapper; -import com.toesbieya.my.model.entity.RecUserAction; -import com.toesbieya.my.model.entity.SysResource; import com.toesbieya.my.model.entity.SysUser; +import com.toesbieya.my.model.vo.UserVo; import com.toesbieya.my.model.vo.result.PageResult; import com.toesbieya.my.model.vo.search.UserSearch; -import com.toesbieya.my.model.vo.update.UserUpdatePwd; import com.toesbieya.my.module.SocketModule; -import com.toesbieya.my.utils.QiniuUtil; import com.toesbieya.my.utils.Result; -import com.toesbieya.my.utils.ThreadUtil; -import com.toesbieya.my.utils.Util; import org.springframework.stereotype.Service; import org.springframework.util.DigestUtils; -import org.springframework.util.StringUtils; import javax.annotation.Resource; -import javax.servlet.http.HttpSession; -import java.util.HashMap; -import java.util.HashSet; import java.util.List; @Service @@ -33,88 +21,16 @@ public class SysUserService { private static final String DEFAULT_PWD = DigestUtils.md5DigestAsHex("123456".getBytes()); @Resource private SysUserMapper userMapper; - @Resource - private SysResourceService resourceService; - @Resource - private RecService recService; - - public Result login(String name, String pwd, String ip) { - HttpSession session = Util.getRequest().getSession(); - SysUser user = userMapper.getByNameAndPwd(name, pwd); - - if (user == null) { - return Result.fail("用户名或密码错误"); - } - else if (user.getStatus() == GeneralStatusEnum.DISABLED.getCode()) { - return Result.fail("该用户已被禁用,请联系管理员"); - } - else if (user.getAdmin() != 1 && (user.getRole() == null || StringUtils.isEmpty(user.getRole_name()))) { - return Result.fail("该用户尚未被分配角色,请联系管理员"); - } - - //设置token - String token = DigestUtils.md5DigestAsHex((user.getId() + "" + System.currentTimeMillis()).getBytes()); - - //传输回前端 - HashMap userVo = new HashMap<>(); - - List resources; - HashMap userResourcesUrlMap = new HashMap<>(); - - HashSet userResourcesIdSet = new HashSet<>(); - - //获取用户的所有权限url - if (user.getRole() != null) { - resources = resourceService.getByRole(user.getRole()); - userResourcesUrlMap = new HashMap<>(128); - userResourcesIdSet = new HashSet<>(128); - for (SysResource p : resources) { - userResourcesUrlMap.put(p.getUrl(), p.getId()); - userResourcesIdSet.add(p.getId()); - } - } - - user.setResource_ids(userResourcesIdSet); - - userVo.put("id", user.getId()); - userVo.put("resources", userResourcesUrlMap); - userVo.put("name", user.getName()); - userVo.put("avatar", user.getAvatar()); - userVo.put("admin", user.getAdmin()); - userVo.put("token", token); - userVo.put("role_name", user.getRole_name()); - userVo.put("session_id", session.getId()); - - recService.insertLoginHistory(user, ip, RecLoginHistoryEnum.LOGIN); - - session.setAttribute(SessionConstant.USER_KEY, user); - session.setAttribute(SessionConstant.TOKEN_KEY, token); - return Result.success(userVo); - } - - //演示用的临时注册功能 - public Result register(String name, String pwd) { - if (userMapper.isNameExist(name, null)) { - return Result.fail("该用户名称已存在"); - } - - SysUser user = new SysUser(); - user.setName(name); - user.setRole(1); - user.setCtime(System.currentTimeMillis()); - user.setPwd(pwd); + public PageResult search(UserSearch vo) { + PageHelper.startPage(vo.getPage(), vo.getPageSize()); - userMapper.add(user); - return Result.success("注册成功"); - } + List users = userMapper.search(vo); - public PageResult search(UserSearch vo) { - PageHelper.startPage(vo.getPage(), vo.getPageSize()); - List users = userMapper.search(vo); - for (SysUser user : users) { + for (UserVo user : users) { user.setOnline(SocketModule.online(user.getId())); } + return new PageResult<>(users); } @@ -131,7 +47,7 @@ public class SysUserService { return Result.success("添加成功"); } - @UserAction + @UserAction("'修改用户:'+#user.name") public Result update(SysUser user) { if (userMapper.isNameExist(user.getName(), user.getId())) { return Result.fail("该用户名称已存在"); @@ -163,34 +79,4 @@ public class SysUserService { int rows = userMapper.resetPwd(user.getId(), DEFAULT_PWD); return rows > 0 ? Result.success() : Result.fail("重置失败,未匹配到用户"); } - - @UserAction("'修改密码'") - public Result updatePwd(UserUpdatePwd vo) { - int rows = userMapper.updatePwd(vo); - return rows > 0 ? Result.success("修改成功") : Result.fail("修改失败,请检查原密码是否正确"); - } - - public Result updateAvatar(SysUser user, String key, HttpSession session) { - int rows = userMapper.updateAvatar(user.getId(), key); - if (rows > 0) { - if (!StringUtils.isEmpty(user.getAvatar())) { - QiniuUtil.delete(user.getAvatar()); - } - user.setAvatar(key); - session.setAttribute(SessionConstant.USER_KEY, user); - return Result.success("上传头像成功"); - } - QiniuUtil.delete(key); - return Result.fail("上传头像失败"); - } - - public boolean checkName(String name) { - return !userMapper.isNameExist(name, null); - } - - public void setUpdateAction(SysUser user) { - RecUserAction action = ThreadUtil.getAction(); - SysUser origin = userMapper.getById(user.getId()); - action.setAction(String.format("修改用户【%s】%s", origin.getName(), SysUser.getUpdateInfo(origin, user))); - } } diff --git a/java/src/main/java/com/toesbieya/my/utils/DocumentUtil.java b/java/src/main/java/com/toesbieya/my/utils/DocumentUtil.java new file mode 100644 index 0000000..38773da --- /dev/null +++ b/java/src/main/java/com/toesbieya/my/utils/DocumentUtil.java @@ -0,0 +1,47 @@ +package com.toesbieya.my.utils; + +import com.google.common.io.ByteStreams; +import com.toesbieya.my.constant.DocumentConstant; +import lombok.extern.slf4j.Slf4j; +import org.springframework.core.io.ClassPathResource; +import org.springframework.data.redis.core.script.DefaultRedisScript; +import org.springframework.data.redis.core.script.RedisScript; + +import java.io.IOException; +import java.time.format.DateTimeFormatter; +import java.util.Arrays; + +@Slf4j +public class DocumentUtil { + private static String GET_DOCUMENT_ID_SCRIPT; + + static { + try { + GET_DOCUMENT_ID_SCRIPT = new String(ByteStreams.toByteArray(new ClassPathResource("/script/get_document_id.lua").getInputStream())); + } + catch (IOException e) { + e.printStackTrace(); + } + } + + //获取单号,形如 {type}0001 + public static String getDocumentID(String type) { + if (!Arrays.asList(DocumentConstant.DOCUMENT_TYPE).contains(type)) { + log.error("单据类型有误,【{}】不存在", type); + return null; + } + + RedisScript redisScript = new DefaultRedisScript<>(GET_DOCUMENT_ID_SCRIPT, Long.class); + + Long result = RedisUtil.execute( + redisScript, + Arrays.asList(DocumentConstant.DOCUMENT_TYPE_REDIS_KEY, DocumentConstant.DOCUMENT_TYPE_REDIS_KEY), + String.valueOf(DateUtil.getTimestampNow()), + type + ); + + if (result == null || result <= 1) return null; + + return String.format("%s%s%04d", type, DateUtil.dateFormat(DateTimeFormatter.BASIC_ISO_DATE), result - 1); + } +} diff --git a/java/src/main/java/com/toesbieya/my/utils/ExcelUtil.java b/java/src/main/java/com/toesbieya/my/utils/ExcelUtil.java index 80945dd..b12e9f0 100644 --- a/java/src/main/java/com/toesbieya/my/utils/ExcelUtil.java +++ b/java/src/main/java/com/toesbieya/my/utils/ExcelUtil.java @@ -48,11 +48,11 @@ public class ExcelUtil { int size = list.size(); if (size == 0) { - Util.responseJson(response, Result.fail("当前没有能导出的数据")); + WebUtil.responseJson(response, Result.fail("当前没有能导出的数据")); return; } else if (size < 10000) { - Util.responseJson(response, Result.success(list)); + WebUtil.responseJson(response, Result.success(list)); return; } diff --git a/java/src/main/java/com/toesbieya/my/utils/MonitorUtil.java b/java/src/main/java/com/toesbieya/my/utils/MonitorUtil.java deleted file mode 100644 index b418265..0000000 --- a/java/src/main/java/com/toesbieya/my/utils/MonitorUtil.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.toesbieya.my.utils; - -import com.alibaba.fastjson.JSONObject; -import com.toesbieya.my.model.vo.info.*; -import com.toesbieya.my.model.vo.info.*; -import lombok.extern.slf4j.Slf4j; -import oshi.SystemInfo; -import oshi.hardware.CentralProcessor; -import oshi.hardware.GlobalMemory; -import oshi.software.os.FileSystem; -import oshi.software.os.OSFileStore; -import oshi.software.os.OperatingSystem; -import oshi.util.Util; - -import java.util.ArrayList; -import java.util.List; - -@Slf4j -public class MonitorUtil { - private final static String REDIS_MONITOR_INFO_KEY = "SYSTEM_MONITOR_INFO_CACHE"; - private final static int EXPIRE = 30; - private final static SystemInfo SYSTEM_INFO = new SystemInfo(); - - public static MonitorInfo getMonitorInfo() { - long timestamp = System.currentTimeMillis(); - JSONObject cache = (JSONObject) RedisUtil.get(REDIS_MONITOR_INFO_KEY); - if (cache == null) { - MonitorInfo monitorInfo = new MonitorInfo(getOperatingInfo(), getCpuInfo(), getMemoryInfo(), getJvmInfo(), getDiskInfo(), timestamp, EXPIRE); - RedisUtil.set(REDIS_MONITOR_INFO_KEY, monitorInfo, EXPIRE); - return monitorInfo; - } - else { - return JSONObject.toJavaObject(cache, MonitorInfo.class); - } - } - - private static OperatingInfo getOperatingInfo() { - OperatingSystem os = SYSTEM_INFO.getOperatingSystem(); - return new OperatingInfo(os); - } - - private static CpuInfo getCpuInfo() { - CentralProcessor processor = SYSTEM_INFO.getHardware().getProcessor(); - long[] prevTicks = processor.getSystemCpuLoadTicks(); - Util.sleep(1000); - long[] ticks = processor.getSystemCpuLoadTicks(); - return new CpuInfo(processor, prevTicks, ticks); - } - - private static MemoryInfo getMemoryInfo() { - GlobalMemory memory = SYSTEM_INFO.getHardware().getMemory(); - return new MemoryInfo(memory.getTotal(), memory.getAvailable()); - } - - private static JvmInfo getJvmInfo() { - Runtime runtime = Runtime.getRuntime(); - return new JvmInfo(runtime.maxMemory(), runtime.totalMemory(), runtime.freeMemory()); - } - - private static List getDiskInfo() { - FileSystem fileSystem = SYSTEM_INFO.getOperatingSystem().getFileSystem(); - OSFileStore[] fsArray = fileSystem.getFileStores(); - List list = new ArrayList<>(); - for (OSFileStore fs : fsArray) { - list.add(new DiskInfo(fs)); - } - return list; - } -} diff --git a/java/src/main/java/com/toesbieya/my/utils/QiniuUtil.java b/java/src/main/java/com/toesbieya/my/utils/QiniuUtil.java index d7d9a72..f7678e4 100644 --- a/java/src/main/java/com/toesbieya/my/utils/QiniuUtil.java +++ b/java/src/main/java/com/toesbieya/my/utils/QiniuUtil.java @@ -5,24 +5,41 @@ import com.qiniu.storage.BucketManager; import com.qiniu.storage.Configuration; import com.qiniu.storage.Region; import com.qiniu.util.Auth; +import com.toesbieya.my.config.QiniuConfig; import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.DependsOn; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; @Slf4j +@Component +@DependsOn("redisUtil") public class QiniuUtil { - private static final String ACCESS_KEY = (String) YmlUtil.get("qiniu.access-key"); - private static final String SECRET_KEY = (String) YmlUtil.get("qiniu.secret-key"); - private static final String BUCKET = (String) YmlUtil.get("qiniu.bucket"); - private static final int TOKEN_EXPIRES = (int) YmlUtil.get("qiniu.token-expires"); - private static final String REDIS_CACHE_KEY = (String) YmlUtil.get("qiniu.redis-cache-key"); - private static final Auth AUTH = Auth.create(ACCESS_KEY, SECRET_KEY); - private static final BucketManager BUCKET_MANAGER = new BucketManager(AUTH, new Configuration(Region.huadong())); + private static QiniuConfig config; + private static Auth AUTH ; + private static BucketManager BUCKET_MANAGER; + + @Autowired + public QiniuUtil(QiniuConfig config) { + QiniuUtil.config = config; + + if (StringUtils.isEmpty(config.getAccessKey())) { + QiniuUtil.AUTH = null; + QiniuUtil.BUCKET_MANAGER = null; + return; + } + + QiniuUtil.AUTH = Auth.create(config.getAccessKey(), config.getSecretKey()); + QiniuUtil.BUCKET_MANAGER = new BucketManager(QiniuUtil.AUTH, new Configuration(Region.huadong())); + } public static String getToken() { - String token = (String) RedisUtil.get(REDIS_CACHE_KEY); + String token = (String) RedisUtil.get(config.getRedisCacheKey()); if (token == null) { - token = AUTH.uploadToken(BUCKET); - RedisUtil.set(REDIS_CACHE_KEY, token, TOKEN_EXPIRES); + token = AUTH.uploadToken(config.getBucket()); + RedisUtil.set(config.getRedisCacheKey(), token, config.getTokenExpire()); } return token; @@ -30,7 +47,7 @@ public class QiniuUtil { public static void delete(String key) { try { - BUCKET_MANAGER.delete(BUCKET, key); + BUCKET_MANAGER.delete(config.getBucket(), key); } catch (QiniuException e) { log.info("七牛云删除单个文件失败,{}", e.getMessage()); } @@ -38,7 +55,7 @@ public class QiniuUtil { public static void deleteBatch(String... key) { BucketManager.BatchOperations batchOperations = new BucketManager.BatchOperations(); - batchOperations.addDeleteOp(BUCKET, key); + batchOperations.addDeleteOp(config.getBucket(), key); try { BUCKET_MANAGER.batch(batchOperations); } catch (QiniuException e) { diff --git a/java/src/main/java/com/toesbieya/my/utils/RedisUtil.java b/java/src/main/java/com/toesbieya/my/utils/RedisUtil.java index 31adbc2..b3d033f 100644 --- a/java/src/main/java/com/toesbieya/my/utils/RedisUtil.java +++ b/java/src/main/java/com/toesbieya/my/utils/RedisUtil.java @@ -1,36 +1,27 @@ package com.toesbieya.my.utils; -import com.alibaba.fastjson.JSONObject; import com.google.common.io.ByteStreams; -import com.toesbieya.my.constant.SessionConstant; -import com.toesbieya.my.model.entity.SysUser; -import com.toesbieya.my.module.redis.RedisLockType; -import com.toesbieya.my.module.redis.RedisModule; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.ClassPathResource; import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.core.script.DefaultRedisScript; import org.springframework.data.redis.core.script.RedisScript; import org.springframework.stereotype.Component; +import java.io.Closeable; import java.io.IOException; -import java.time.format.DateTimeFormatter; import java.util.*; import java.util.concurrent.TimeUnit; @Component @Slf4j public class RedisUtil { - private static String GET_DOCUMENT_ID_SCRIPT = null; private static String INCREMENT_AND_EXPIRE_SCRIPT = null; - private static StringRedisTemplate stringRedisTemplate; private static RedisTemplate redisTemplate; static { try { - GET_DOCUMENT_ID_SCRIPT = new String(ByteStreams.toByteArray(new ClassPathResource("/script/get_document_id.lua").getInputStream())); INCREMENT_AND_EXPIRE_SCRIPT = new String(ByteStreams.toByteArray(new ClassPathResource("/script/increase_and_expire.lua").getInputStream())); } catch (IOException e) { e.printStackTrace(); @@ -38,13 +29,12 @@ public class RedisUtil { } @Autowired - public RedisUtil(StringRedisTemplate stringRedisTemplate, RedisTemplate redisTemplate) { - RedisUtil.stringRedisTemplate = stringRedisTemplate; + public RedisUtil(RedisTemplate redisTemplate) { RedisUtil.redisTemplate = redisTemplate; } public static boolean exist(String key) { - Boolean result = stringRedisTemplate.hasKey(key); + Boolean result = redisTemplate.hasKey(key); return result != null && result; } @@ -54,16 +44,8 @@ public class RedisUtil { return result == null ? 0 : result; } - public static void del(String key) { - stringRedisTemplate.delete(key); - } - - public static void expire(String key) { - stringRedisTemplate.expire(key, 0L, TimeUnit.MILLISECONDS); - } - - public static Set keys(String key) { - return stringRedisTemplate.keys(key + '*'); + public static void expireImmediately(String key) { + redisTemplate.expire(key, 0L, TimeUnit.MILLISECONDS); } public static Object get(String key) { @@ -90,32 +72,44 @@ public class RedisUtil { redisTemplate.opsForHash().putAll(key, map); } - public static String getDocumentID(String type) { - if (!Arrays.asList(RedisModule.DOCUMENTS_TYPE).contains(type)) { - log.error("单据类型有误,【{}】不存在", type); - return null; - } + public static T execute(RedisScript script, List keys, Object... args) { + return redisTemplate.execute(script, keys, args); + } - RedisScript redisScript = new DefaultRedisScript<>(GET_DOCUMENT_ID_SCRIPT, Long.class); - Long result = stringRedisTemplate.execute( - redisScript, - Arrays.asList(RedisLockType.UPDATE_DOCUMENT_ID, RedisModule.DOCUMENTS_KEY), - String.valueOf(DateUtil.getTimestampNow()), - type - ); - if (result == null || result <= 1) return null; - return type + DateUtil.dateFormat(DateTimeFormatter.BASIC_ISO_DATE) + String.format("%04d", result - 1); + public static RedisTemplate getRedisTemplate() { + return redisTemplate; } - public static SysUser getUserByRedisKey(String key) { - JSONObject o = (JSONObject) redisTemplate.opsForHash().get(key, "sessionAttr:" + SessionConstant.USER_KEY); - if (o == null) { - return null; + public static class Locker implements Closeable { + private final String key; + private final String value; + private final long expire; + + public Locker(String key) { + this.key = "lock:" + key; + this.value = String.valueOf(System.currentTimeMillis()); + this.expire = 300; + } + + @Override + public void close() { + this.unlock(); } - return JSONObject.toJavaObject(o, SysUser.class); - } - public static StringRedisTemplate getStringRedisTemplate() { - return stringRedisTemplate; + public boolean lock() { + String LOCK_LUA_SCRIPT = "return redis.call('set',KEYS[1],ARGV[1],'EX',ARGV[2],'NX')"; + RedisScript redisScript = new DefaultRedisScript<>(LOCK_LUA_SCRIPT, Boolean.class); + Boolean result = RedisUtil.execute(redisScript, Collections.singletonList(key), value, expire); + return Objects.equals(result, true); + } + + public void unlock() { + String UNLOCK_LUA_SCRIPT = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return false end"; + RedisScript redisScript = new DefaultRedisScript<>(UNLOCK_LUA_SCRIPT, Boolean.class); + Boolean result = RedisUtil.execute(redisScript, Collections.singletonList(key), value); + if (result == null || !result) { + log.error("redis锁释放失败,key:{},value:{}", key, value); + } + } } } diff --git a/java/src/main/java/com/toesbieya/my/utils/SessionUtil.java b/java/src/main/java/com/toesbieya/my/utils/SessionUtil.java new file mode 100644 index 0000000..424019e --- /dev/null +++ b/java/src/main/java/com/toesbieya/my/utils/SessionUtil.java @@ -0,0 +1,46 @@ +package com.toesbieya.my.utils; + +import com.alibaba.fastjson.JSONObject; +import com.toesbieya.my.constant.SessionConstant; +import com.toesbieya.my.model.vo.UserVo; +import org.springframework.util.StringUtils; + +import javax.servlet.http.HttpServletRequest; + +public class SessionUtil { + private static long expire = 3600 * 8; + + public static void remove(String token) { + if (StringUtils.isEmpty(token)) return; + + RedisUtil.expireImmediately(SessionConstant.REDIS_NAMESPACE + token); + } + + public static void save(UserVo user) { + String token = user.getToken(); + + if (StringUtils.isEmpty(token)) return; + + RedisUtil.set(SessionConstant.REDIS_NAMESPACE + token, user, expire); + } + + public static UserVo get() { + UserVo user = ThreadUtil.getUser(); + return user == null ? get(WebUtil.getRequest()) : user; + } + + public static UserVo get(String token) { + if (StringUtils.isEmpty(token)) return null; + + JSONObject o = (JSONObject) RedisUtil.get(SessionConstant.REDIS_NAMESPACE + token); + + if (o == null) return null; + + return JSONObject.toJavaObject(o, UserVo.class); + } + + public static UserVo get(HttpServletRequest request) { + String token = request.getHeader(SessionConstant.TOKEN_KEY); + return get(token); + } +} diff --git a/java/src/main/java/com/toesbieya/my/utils/ThreadUtil.java b/java/src/main/java/com/toesbieya/my/utils/ThreadUtil.java index 3d87c94..6044f3c 100644 --- a/java/src/main/java/com/toesbieya/my/utils/ThreadUtil.java +++ b/java/src/main/java/com/toesbieya/my/utils/ThreadUtil.java @@ -1,23 +1,26 @@ package com.toesbieya.my.utils; import com.toesbieya.my.model.entity.RecUserAction; -import com.toesbieya.my.model.entity.SysUser; +import com.toesbieya.my.model.vo.UserVo; import javax.servlet.http.HttpServletRequest; public class ThreadUtil { private static final ThreadLocal THREAD_LOCAL_USER_ACTION = new ThreadLocal<>(); - private static final ThreadLocal THREAD_LOCAL_USER = new ThreadLocal<>(); + private static final ThreadLocal THREAD_LOCAL_USER = new ThreadLocal<>(); public static void quicklySetAction(HttpServletRequest request) { - SysUser user = getUser(); + UserVo user = SessionUtil.get(request); + if (null == user) return; + RecUserAction userAction = RecUserAction.builder() .uid(user.getId()) .uname(user.getName()) .ip(IpUtil.getIp(request)) .url(request.getServletPath()) .build(); + setAction(userAction); } @@ -29,11 +32,11 @@ public class ThreadUtil { THREAD_LOCAL_USER_ACTION.set(action); } - public static SysUser getUser() { + public static UserVo getUser() { return THREAD_LOCAL_USER.get(); } - public static void setUser(SysUser user) { + public static void setUser(UserVo user) { THREAD_LOCAL_USER.set(user); } diff --git a/java/src/main/java/com/toesbieya/my/utils/Util.java b/java/src/main/java/com/toesbieya/my/utils/Util.java index f2b0b4f..830b909 100644 --- a/java/src/main/java/com/toesbieya/my/utils/Util.java +++ b/java/src/main/java/com/toesbieya/my/utils/Util.java @@ -1,23 +1,16 @@ package com.toesbieya.my.utils; -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; -import com.toesbieya.my.constant.SessionConstant; -import com.toesbieya.my.model.entity.SysUser; import org.springframework.util.StringUtils; -import org.springframework.web.context.request.RequestContextHolder; -import org.springframework.web.context.request.ServletRequestAttributes; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; import javax.validation.constraints.NotNull; -import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.nio.charset.StandardCharsets; import java.text.DecimalFormat; -import java.util.*; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.UUID; import java.util.function.Predicate; import java.util.regex.Pattern; import java.util.stream.Collectors; @@ -28,7 +21,9 @@ public class Util { } public static List str2List(@NotNull String string) { - if (StringUtils.isEmpty(string)) return new ArrayList<>(0); + if (StringUtils.isEmpty(string)) { + return Collections.emptyList(); + } return Arrays.stream(string.split(",")) .map(i -> Integer.parseInt(i.trim())) .collect(Collectors.toList()); @@ -46,13 +41,6 @@ public class Util { return o == null ? defaultValue : o; } - public static void responseJson(HttpServletResponse response, Result result) throws IOException { - response.setCharacterEncoding("UTF-8"); - response.setContentType("application/json; charset=utf-8"); - - response.getWriter().print(JSON.toJSONString(result)); - } - public static boolean isInteger(String str) { Pattern pattern = Pattern.compile("^[-+]?[\\d]*$"); return pattern.matcher(str).matches(); @@ -66,24 +54,6 @@ public class Util { return stringWriter.toString(); } - public static HttpServletRequest getRequest() { - return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest(); - } - - public static HttpSession getSession() { - return getRequest().getSession(); - } - - public static SysUser getUser() { - return getUser(getSession()); - } - - public static SysUser getUser(HttpSession session) { - JSONObject o = (JSONObject) session.getAttribute(SessionConstant.USER_KEY); - if (o == null) return null; - return JSONObject.toJavaObject(o, SysUser.class); - } - public static String formatByte(long byteNumber) { //换算单位 double FORMAT = 1024.0; @@ -104,9 +74,31 @@ public class Util { } public static T find(Iterable list, Predicate predicate) { + if (list == null) return null; + for (T t : list) { if (predicate.test(t)) return t; } + return null; } + + public static int findIndex(Iterable list, Predicate predicate) { + int i = -1; + + if (list == null) return i; + + for (T t : list) { + i++; + if (predicate.test(t)) return i; + } + + return -1; + } + + public static boolean some(Iterable list, Predicate predicate) { + int index = findIndex(list, predicate); + + return index > -1; + } } diff --git a/java/src/main/java/com/toesbieya/my/utils/WebUtil.java b/java/src/main/java/com/toesbieya/my/utils/WebUtil.java new file mode 100644 index 0000000..a512ac1 --- /dev/null +++ b/java/src/main/java/com/toesbieya/my/utils/WebUtil.java @@ -0,0 +1,23 @@ +package com.toesbieya.my.utils; + +import com.alibaba.fastjson.JSON; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.Objects; + +public class WebUtil { + public static void responseJson(HttpServletResponse response, Result result) throws IOException { + response.setCharacterEncoding("UTF-8"); + response.setContentType("application/json; charset=utf-8"); + + response.getWriter().print(JSON.toJSONString(result)); + } + + public static HttpServletRequest getRequest() { + return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest(); + } +} diff --git a/java/src/main/resources/mapper/SysUser.xml b/java/src/main/resources/mapper/SysUser.xml index 50c58f2..2035af2 100644 --- a/java/src/main/resources/mapper/SysUser.xml +++ b/java/src/main/resources/mapper/SysUser.xml @@ -37,24 +37,16 @@ where id = #{id} and admin = 0 - -