移除spring-session,改用简易方式存储登录态

移除系统监控模块
SysUserController部分功能拆分至AccountController
socket参数修改:session_id->token
其他代码修改
master
toesbieya 6 years ago
parent 14404fa6a4
commit 9609078727
  1. 68
      java/my.sql
  2. 5
      java/pom.xml
  3. 2
      java/src/main/java/com/toesbieya/my/MyApplication.java
  4. 28
      java/src/main/java/com/toesbieya/my/aspect/LockAspect.java
  5. 19
      java/src/main/java/com/toesbieya/my/config/FastJsonConfigFactory.java
  6. 70
      java/src/main/java/com/toesbieya/my/config/HttpSessionConfig.java
  7. 22
      java/src/main/java/com/toesbieya/my/config/QiniuConfig.java
  8. 25
      java/src/main/java/com/toesbieya/my/config/RedisConfig.java
  9. 32
      java/src/main/java/com/toesbieya/my/config/SocketConfig.java
  10. 37
      java/src/main/java/com/toesbieya/my/config/SocketServerConfig.java
  11. 24
      java/src/main/java/com/toesbieya/my/config/WebConfig.java
  12. 7
      java/src/main/java/com/toesbieya/my/constant/DocumentConstant.java
  13. 4
      java/src/main/java/com/toesbieya/my/constant/SessionConstant.java
  14. 18
      java/src/main/java/com/toesbieya/my/constant/SocketConstant.java
  15. 100
      java/src/main/java/com/toesbieya/my/controller/AccountController.java
  16. 14
      java/src/main/java/com/toesbieya/my/controller/BizPurchaseInboundController.java
  17. 22
      java/src/main/java/com/toesbieya/my/controller/BizPurchaseOrderController.java
  18. 15
      java/src/main/java/com/toesbieya/my/controller/BizSellOrderController.java
  19. 20
      java/src/main/java/com/toesbieya/my/controller/BizSellOutboundController.java
  20. 17
      java/src/main/java/com/toesbieya/my/controller/MonitorController.java
  21. 24
      java/src/main/java/com/toesbieya/my/controller/MsgController.java
  22. 10
      java/src/main/java/com/toesbieya/my/controller/RecController.java
  23. 6
      java/src/main/java/com/toesbieya/my/controller/SysDepartmentController.java
  24. 10
      java/src/main/java/com/toesbieya/my/controller/SysRoleController.java
  25. 1
      java/src/main/java/com/toesbieya/my/controller/SysUserController.java
  26. 20
      java/src/main/java/com/toesbieya/my/interceptor/RateControlInterceptor.java
  27. 41
      java/src/main/java/com/toesbieya/my/interceptor/SecurityInterceptor.java
  28. 9
      java/src/main/java/com/toesbieya/my/mapper/SysUserMapper.java
  29. 23
      java/src/main/java/com/toesbieya/my/model/entity/SysUser.java
  30. 17
      java/src/main/java/com/toesbieya/my/model/vo/LoginParam.java
  31. 26
      java/src/main/java/com/toesbieya/my/model/vo/LoginSuccessInfo.java
  32. 10
      java/src/main/java/com/toesbieya/my/model/vo/PasswordUpdateParam.java
  33. 11
      java/src/main/java/com/toesbieya/my/model/vo/RegisterParam.java
  34. 33
      java/src/main/java/com/toesbieya/my/model/vo/UserVo.java
  35. 54
      java/src/main/java/com/toesbieya/my/model/vo/info/CpuInfo.java
  36. 25
      java/src/main/java/com/toesbieya/my/model/vo/info/DiskInfo.java
  37. 29
      java/src/main/java/com/toesbieya/my/model/vo/info/JvmInfo.java
  38. 26
      java/src/main/java/com/toesbieya/my/model/vo/info/MemoryInfo.java
  39. 20
      java/src/main/java/com/toesbieya/my/model/vo/info/MonitorInfo.java
  40. 19
      java/src/main/java/com/toesbieya/my/model/vo/info/OperatingInfo.java
  41. 19
      java/src/main/java/com/toesbieya/my/module/PermissionModule.java
  42. 36
      java/src/main/java/com/toesbieya/my/module/RedisModule.java
  43. 61
      java/src/main/java/com/toesbieya/my/module/SocketModule.java
  44. 15
      java/src/main/java/com/toesbieya/my/module/redis/LockHelper.java
  45. 45
      java/src/main/java/com/toesbieya/my/module/redis/RedisLockHelper.java
  46. 5
      java/src/main/java/com/toesbieya/my/module/redis/RedisLockType.java
  47. 145
      java/src/main/java/com/toesbieya/my/service/AccountService.java
  48. 14
      java/src/main/java/com/toesbieya/my/service/BizPurchaseInboundService.java
  49. 11
      java/src/main/java/com/toesbieya/my/service/BizPurchaseOrderService.java
  50. 11
      java/src/main/java/com/toesbieya/my/service/BizSellOrderService.java
  51. 14
      java/src/main/java/com/toesbieya/my/service/BizSellOutboundService.java
  52. 7
      java/src/main/java/com/toesbieya/my/service/MsgService.java
  53. 4
      java/src/main/java/com/toesbieya/my/service/RecService.java
  54. 128
      java/src/main/java/com/toesbieya/my/service/SysUserService.java
  55. 47
      java/src/main/java/com/toesbieya/my/utils/DocumentUtil.java
  56. 4
      java/src/main/java/com/toesbieya/my/utils/ExcelUtil.java
  57. 69
      java/src/main/java/com/toesbieya/my/utils/MonitorUtil.java
  58. 41
      java/src/main/java/com/toesbieya/my/utils/QiniuUtil.java
  59. 84
      java/src/main/java/com/toesbieya/my/utils/RedisUtil.java
  60. 46
      java/src/main/java/com/toesbieya/my/utils/SessionUtil.java
  61. 13
      java/src/main/java/com/toesbieya/my/utils/ThreadUtil.java
  62. 66
      java/src/main/java/com/toesbieya/my/utils/Util.java
  63. 23
      java/src/main/java/com/toesbieya/my/utils/WebUtil.java
  64. 14
      java/src/main/resources/mapper/SysUser.xml

@ -11,7 +11,7 @@
Target Server Version : 80018 Target Server Version : 80018
File Encoding : 65001 File Encoding : 65001
Date: 11/07/2020 10:11:24 Date: 12/07/2020 13:49:09
*/ */
SET NAMES utf8mb4; SET NAMES utf8mb4;
@ -34,7 +34,7 @@ CREATE TABLE `biz_document_history` (
PRIMARY KEY (`id`) USING BTREE, PRIMARY KEY (`id`) USING BTREE,
INDEX `pid_time_idx`(`pid`, `time`) USING BTREE, INDEX `pid_time_idx`(`pid`, `time`) USING BTREE,
INDEX `uid_idx`(`uid`) 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 -- Records of biz_document_history
@ -76,7 +76,7 @@ CREATE TABLE `biz_purchase_inbound_sub` (
`num` decimal(10, 2) NOT NULL COMMENT '入库数量', `num` decimal(10, 2) NOT NULL COMMENT '入库数量',
PRIMARY KEY (`id`) USING BTREE, PRIMARY KEY (`id`) USING BTREE,
UNIQUE INDEX `pid_cid_unique_idx`(`pid`, `cid`) USING BTREE COMMENT '同一采购入库单不能有重复分类的商品' 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 -- 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 '商品分类名称', `cname` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '商品分类名称',
`num` decimal(10, 2) NOT NULL COMMENT '出库数量', `num` decimal(10, 2) NOT NULL COMMENT '出库数量',
PRIMARY KEY (`id`) USING BTREE 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 -- Table structure for biz_stock
@ -226,7 +226,7 @@ CREATE TABLE `biz_stock` (
PRIMARY KEY (`id`) USING BTREE, PRIMARY KEY (`id`) USING BTREE,
UNIQUE INDEX `cid_cgrkid_unique_idx`(`cid`, `cgrkid`) USING BTREE, UNIQUE INDEX `cid_cgrkid_unique_idx`(`cid`, `cgrkid`) USING BTREE,
INDEX `cdate_idx`(`ctime`) 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 -- Table structure for msg
@ -297,7 +297,7 @@ CREATE TABLE `rec_attachment` (
PRIMARY KEY (`id`) USING BTREE, PRIMARY KEY (`id`) USING BTREE,
INDEX `pid_idx`(`pid`) USING BTREE, INDEX `pid_idx`(`pid`) USING BTREE,
INDEX `url_idx`(`url`) 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 -- Table structure for rec_login_history
@ -315,7 +315,7 @@ CREATE TABLE `rec_login_history` (
INDEX `uid_idx`(`uid`) USING BTREE, INDEX `uid_idx`(`uid`) USING BTREE,
INDEX `type_idx`(`type`) USING BTREE, INDEX `type_idx`(`type`) USING BTREE,
INDEX `time_idx`(`time`) 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 -- 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 (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 (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 (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 -- 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 '错误信息', `error` text CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL COMMENT '错误信息',
`type` int(11) NOT NULL COMMENT '0失败、1成功', `type` int(11) NOT NULL COMMENT '0失败、1成功',
PRIMARY KEY (`id`) USING BTREE 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 -- 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 (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 (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 (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 -- Table structure for stat_finish_order
@ -514,7 +532,7 @@ CREATE TABLE `stat_finish_order` (
`sell` int(11) NOT NULL COMMENT '销售订单完成数', `sell` int(11) NOT NULL COMMENT '销售订单完成数',
`time` bigint(20) NOT NULL COMMENT '完成时间', `time` bigint(20) NOT NULL COMMENT '完成时间',
PRIMARY KEY (`id`) USING BTREE 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 -- 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 (129, 0, 0, 1594137600000);
INSERT INTO `stat_finish_order` VALUES (130, 0, 0, 1594224000000); 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 (131, 0, 0, 1594310400000);
INSERT INTO `stat_finish_order` VALUES (132, 0, 0, 1594396800000);
-- ---------------------------- -- ----------------------------
-- Table structure for stat_profit_goods -- Table structure for stat_profit_goods
@ -584,7 +603,7 @@ CREATE TABLE `stat_profit_total` (
`profit` decimal(10, 2) NOT NULL COMMENT '毛利润', `profit` decimal(10, 2) NOT NULL COMMENT '毛利润',
`time` bigint(20) NOT NULL, `time` bigint(20) NOT NULL,
PRIMARY KEY (`id`) USING BTREE 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 -- 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 (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 (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 (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 -- Table structure for sys_category
@ -669,7 +689,7 @@ CREATE TABLE `sys_customer` (
UNIQUE INDEX `name_unique_idx`(`name`) USING BTREE, UNIQUE INDEX `name_unique_idx`(`name`) USING BTREE,
INDEX `status_idx`(`status`) USING BTREE, INDEX `status_idx`(`status`) USING BTREE,
INDEX `ctime_idx`(`ctime`) 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 -- Records of sys_customer
@ -687,7 +707,7 @@ CREATE TABLE `sys_department` (
`status` int(11) NOT NULL DEFAULT 1 COMMENT '0禁用,1正常', `status` int(11) NOT NULL DEFAULT 1 COMMENT '0禁用,1正常',
PRIMARY KEY (`id`) USING BTREE, PRIMARY KEY (`id`) USING BTREE,
UNIQUE INDEX `pid_name_unique_idx`(`pid`, `name`) 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 -- 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 (303, 300, '删除', '/del', 0, 100, 1);
INSERT INTO `sys_resource` VALUES (350, 200, '接口管理', '/resource', 1, 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 (351, 350, '修改', '/update', 1, 100, 1);
INSERT INTO `sys_resource` VALUES (360, 200, '系统监控', '/monitor', 1, 100, 1);
-- ---------------------------- -- ----------------------------
-- Table structure for sys_role -- Table structure for sys_role
@ -47298,7 +47317,7 @@ CREATE TABLE `sys_supplier` (
UNIQUE INDEX `name_unique_idx`(`name`) USING BTREE, UNIQUE INDEX `name_unique_idx`(`name`) USING BTREE,
INDEX `ctime_idx`(`ctime`) USING BTREE, INDEX `ctime_idx`(`ctime`) USING BTREE,
INDEX `status_idx`(`status`) 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 -- 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 (1, 'admin', 'e10adc3949ba59abbe56e057f20f883e', NULL, NULL, 1582184632922, 1, 1);
INSERT INTO `sys_user` VALUES (47, 'toesbieya', 'e10adc3949ba59abbe56e057f20f883e', 1, NULL, 1592803978422, 0, 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; SET FOREIGN_KEY_CHECKS = 1;

@ -54,11 +54,6 @@
<artifactId>commons-pool2</artifactId> <artifactId>commons-pool2</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
<!--mysql数据库相关--> <!--mysql数据库相关-->
<dependency> <dependency>
<groupId>org.mybatis.spring.boot</groupId> <groupId>org.mybatis.spring.boot</groupId>

@ -3,13 +3,11 @@ package com.toesbieya.my;
import org.mybatis.spring.annotation.MapperScan; import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication @SpringBootApplication
@MapperScan("com.toesbieya.my.mapper") @MapperScan("com.toesbieya.my.mapper")
@EnableScheduling @EnableScheduling
@EnableCaching
public class MyApplication { public class MyApplication {
public static void main(String[] args) { public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args); SpringApplication.run(MyApplication.class, args);

@ -1,8 +1,7 @@
package com.toesbieya.my.aspect; package com.toesbieya.my.aspect;
import com.toesbieya.my.annoation.Lock; import com.toesbieya.my.annoation.Lock;
import com.toesbieya.my.module.redis.LockHelper; import com.toesbieya.my.utils.RedisUtil;
import com.toesbieya.my.module.redis.RedisLockHelper;
import com.toesbieya.my.utils.Result; import com.toesbieya.my.utils.Result;
import com.toesbieya.my.utils.SpringUtil; import com.toesbieya.my.utils.SpringUtil;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
@ -11,7 +10,6 @@ import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature; import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order; import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import java.lang.reflect.Method; import java.lang.reflect.Method;
@ -22,7 +20,7 @@ import java.util.ArrayList;
@Slf4j @Slf4j
@Order(Integer.MAX_VALUE - 1) @Order(Integer.MAX_VALUE - 1)
public class LockAspect { public class LockAspect {
private final ThreadLocal<ArrayList<LockHelper>> lockHelperThreadLocal = new ThreadLocal<>(); private final ThreadLocal<ArrayList<RedisUtil.Locker>> lockerThreadLocal = new ThreadLocal<>();
@Pointcut("@annotation(com.toesbieya.my.annoation.Lock)&&execution(com.toesbieya.my.utils.Result com.toesbieya.my..*.*(..))") @Pointcut("@annotation(com.toesbieya.my.annoation.Lock)&&execution(com.toesbieya.my.utils.Result com.toesbieya.my..*.*(..))")
public void pointCut() { public void pointCut() {
@ -37,21 +35,23 @@ public class LockAspect {
if (values.length <= 0) { if (values.length <= 0) {
return point.proceed(); return point.proceed();
} }
ArrayList<LockHelper> locks = new ArrayList<>(); ArrayList<RedisUtil.Locker> locks = new ArrayList<>();
String[] parameterNames = signature.getParameterNames(); String[] parameterNames = signature.getParameterNames();
Object[] args = point.getArgs(); Object[] args = point.getArgs();
for (String v : values) { for (String v : values) {
String lockKey = (String) SpringUtil.spell(v, parameterNames, args); String lockKey = (String) SpringUtil.spell(v, parameterNames, args);
//跳过空值 //跳过空值
if (StringUtils.isEmpty(lockKey)) continue; if (StringUtils.isEmpty(lockKey)) continue;
LockHelper lockHelper = new RedisLockHelper(lockKey);
if (!lockHelper.lock()) { RedisUtil.Locker locker = new RedisUtil.Locker(lockKey);
locks.forEach(LockHelper::close); if (!locker.lock()) {
locks.forEach(RedisUtil.Locker::close);
return Result.fail("操作失败,请刷新后重试"); return Result.fail("操作失败,请刷新后重试");
} }
locks.add(lockHelper); locks.add(locker);
} }
lockHelperThreadLocal.set(locks); lockerThreadLocal.set(locks);
return point.proceed(); return point.proceed();
} }
@ -66,10 +66,10 @@ public class LockAspect {
} }
private void unlock() { private void unlock() {
ArrayList<LockHelper> locks = lockHelperThreadLocal.get(); ArrayList<RedisUtil.Locker> locks = lockerThreadLocal.get();
if (!CollectionUtils.isEmpty(locks)) { if (locks != null) {
locks.forEach(LockHelper::close); locks.forEach(RedisUtil.Locker::close);
lockHelperThreadLocal.remove(); lockerThreadLocal.remove();
} }
} }
} }

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

@ -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<Object> defaultRedisSerializer() {
return new JsonRedisSerializer<>(Object.class);
}
private class JsonRedisSerializer<T> implements RedisSerializer<T> {
private final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
private final Class<T> clazz;
public JsonRedisSerializer(Class<T> 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);
}
}
}

@ -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";
}

@ -3,16 +3,10 @@ package com.toesbieya.my.config;
import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer; import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.time.Duration;
@Configuration @Configuration
public class RedisConfig { public class RedisConfig {
@Bean @Bean
@ -21,6 +15,8 @@ public class RedisConfig {
redisTemplate.setConnectionFactory(factory); redisTemplate.setConnectionFactory(factory);
FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class); FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);
fastJsonRedisSerializer.setFastJsonConfig(FastJsonConfigFactory.defaultConfig());
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
// 设置值(value)的序列化采用FastJsonRedisSerializer。 // 设置值(value)的序列化采用FastJsonRedisSerializer。
@ -35,21 +31,4 @@ public class RedisConfig {
redisTemplate.afterPropertiesSet(); redisTemplate.afterPropertiesSet();
return redisTemplate; 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();
}
} }

@ -1,27 +1,15 @@
package com.toesbieya.my.config; package com.toesbieya.my.config;
import com.corundumstudio.socketio.SocketIOServer; import lombok.Data;
import com.corundumstudio.socketio.annotation.SpringAnnotationScanner; import org.springframework.boot.context.properties.ConfigurationProperties;
import com.toesbieya.my.constant.SocketConstant; import org.springframework.stereotype.Component;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration @Component
@ConfigurationProperties("socket")
@Data
public class SocketConfig { public class SocketConfig {
private String hostname = "localhost";
@Bean private Integer port = 12580;
public SocketIOServer socketIOServer() { private Integer maxFramePayloadLength = 1024 * 1024;
com.corundumstudio.socketio.Configuration config = new com.corundumstudio.socketio.Configuration(); private Integer maxHttpContentLength = 1024 * 1024;
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);
}
} }

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

@ -1,7 +1,5 @@
package com.toesbieya.my.config; 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.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.toesbieya.my.interceptor.RateControlInterceptor; import com.toesbieya.my.interceptor.RateControlInterceptor;
import com.toesbieya.my.interceptor.SecurityInterceptor; import com.toesbieya.my.interceptor.SecurityInterceptor;
@ -22,33 +20,19 @@ import java.util.List;
public class WebConfig implements WebMvcConfigurer { public class WebConfig implements WebMvcConfigurer {
@Override @Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { public void configureMessageConverters(List<HttpMessageConverter<?>> 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--) { for (int i = converters.size() - 1; i >= 0; i--) {
if (converters.get(i) instanceof MappingJackson2HttpMessageConverter) { if (converters.get(i) instanceof MappingJackson2HttpMessageConverter) {
converters.remove(i); converters.remove(i);
} }
} }
FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter(); FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
FastJsonConfig config = new FastJsonConfig(); fastJsonHttpMessageConverter.setFastJsonConfig(FastJsonConfigFactory.defaultConfig());
config.setSerializerFeatures(
SerializerFeature.WriteMapNullValue, // 是否输出值为null的字段,默认为false,我们将它打开
SerializerFeature.WriteDateUseDateFormat,
SerializerFeature.WriteNullListAsEmpty,
SerializerFeature.DisableCircularReferenceDetect // 禁用循环引用
);
fastJsonHttpMessageConverter.setFastJsonConfig(config);
// 添加支持的MediaTypes;不添加时默认为*/*,也就是默认支持全部
// 但是MappingJackson2HttpMessageConverter里面支持的MediaTypes为application/json
// 参考它的做法, fastjson也只添加application/json的MediaType
List<MediaType> fastMediaTypes = new ArrayList<>(); List<MediaType> fastMediaTypes = new ArrayList<>();
fastMediaTypes.add(MediaType.APPLICATION_JSON); fastMediaTypes.add(MediaType.APPLICATION_JSON);
fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes); fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes);
converters.add(fastJsonHttpMessageConverter); converters.add(fastJsonHttpMessageConverter);
} }

@ -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";
}

@ -1,8 +1,6 @@
package com.toesbieya.my.constant; package com.toesbieya.my.constant;
public class SessionConstant { public class SessionConstant {
public static String REDIS_NAMESPACE = "spring:session:sessions:"; public static String REDIS_NAMESPACE = "sessions:";
public static String USER_KEY = "user";
public static String TOKEN_KEY = "X-Token"; public static String TOKEN_KEY = "X-Token";
public static Integer PREDICT_MAX_USER = 128;
} }

@ -1,12 +1,14 @@
package com.toesbieya.my.constant; package com.toesbieya.my.constant;
import com.toesbieya.my.utils.YmlUtil;
public class SocketConstant { public class SocketConstant {
public static final String HOSTNAME = (String) YmlUtil.get("socket.hostname"); public static String REDIS_EVENT_TOPIC_SEND = "socket:event:send";
public static final int PORT = (int) YmlUtil.get("socket.port"); public static int REDIS_EVENT_SPECIFIC = 0;
public static final int MAX_FRAME_PAYLOAD = (int) YmlUtil.get("socket.max-frame-payload"); public static int REDIS_EVENT_BROADCAST = 1;
public static final int MAX_HTTP_CONTENT = (int) YmlUtil.get("socket.max-http-content"); public static int REDIS_EVENT_LOGOUT = 2;
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_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";
} }

@ -1,115 +1,89 @@
package com.toesbieya.my.controller; package com.toesbieya.my.controller;
import com.toesbieya.my.enumeration.RecLoginHistoryEnum; import com.toesbieya.my.model.vo.LoginParam;
import com.toesbieya.my.model.entity.SysUser; import com.toesbieya.my.model.vo.PasswordUpdateParam;
import com.toesbieya.my.model.vo.update.UserUpdatePwd; import com.toesbieya.my.model.vo.RegisterParam;
import com.toesbieya.my.service.RecService; import com.toesbieya.my.model.vo.UserVo;
import com.toesbieya.my.service.SysUserService; import com.toesbieya.my.service.AccountService;
import com.toesbieya.my.utils.IpUtil; import com.toesbieya.my.utils.IpUtil;
import com.toesbieya.my.utils.Result; import com.toesbieya.my.utils.Result;
import com.toesbieya.my.utils.Util; import com.toesbieya.my.utils.SessionUtil;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource; import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession; import javax.validation.Valid;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.net.URLDecoder; import java.net.URLDecoder;
import java.util.Map;
@RestController @RestController
@RequestMapping("account") @RequestMapping("account")
public class AccountController { public class AccountController {
@Resource @Resource
private SysUserService userService; private AccountService accountService;
@Resource
private RecService recService;
@Resource
private HttpSession session;
@PostMapping("login") @PostMapping("login")
public Result login(HttpServletRequest request, @RequestBody Map<String, String> map) { public Result login(HttpServletRequest request, @Valid @RequestBody LoginParam param) {
String username = map.get("username"); return accountService.login(param, IpUtil.getIp(request));
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<String, String> 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);
} }
@GetMapping("logout") @GetMapping("logout")
public Result logout(HttpServletRequest request) { public Result logout(HttpServletRequest request) {
SysUser user = Util.getUser(); UserVo user = SessionUtil.get();
if (user != null) { return accountService.logout(user, IpUtil.getIp(request));
recService.insertLoginHistory(user, IpUtil.getIp(request), RecLoginHistoryEnum.LOGOUT); }
}
session.invalidate(); @PostMapping("register")
return Result.success("登出成功"); public Result register(@Valid @RequestBody RegisterParam param) {
return accountService.register(param);
} }
@PostMapping("updatePwd") @PostMapping("updatePwd")
public Result updatePwd(@RequestBody UserUpdatePwd vo) { public Result updatePwd(@RequestBody PasswordUpdateParam param) {
SysUser user = Util.getUser(); UserVo user = SessionUtil.get();
vo.setId(user.getId()); param.setId(user.getId());
String errMsg = validateUpdatePwdParam(vo); String errMsg = validateUpdatePwdParam(param);
if (errMsg != null) return Result.fail(errMsg); if (errMsg != null) return Result.fail(errMsg);
vo.setOld_pwd(DigestUtils.md5DigestAsHex(vo.getOld_pwd().getBytes())); return accountService.updatePwd(param);
vo.setNew_pwd(DigestUtils.md5DigestAsHex(vo.getNew_pwd().getBytes()));
return userService.updatePwd(vo);
} }
@GetMapping("updateAvatar") @GetMapping("updateAvatar")
public Result updateAvatar(@RequestParam String key) throws UnsupportedEncodingException { public Result updateAvatar(@RequestParam String key) throws UnsupportedEncodingException {
if (StringUtils.isEmpty(key)) return Result.fail("参数错误"); 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") @GetMapping("validate")
public Result validate(@RequestParam String pwd) { public Result validate(@RequestParam String pwd) {
SysUser current = Util.getUser(); UserVo current = SessionUtil.get();
if (!pwd.equals(current.getPwd())) return Result.fail("校验失败");
if (!pwd.equals(current.getPwd())) {
return Result.fail("校验失败");
}
return Result.success("校验通过"); return Result.success("校验通过");
} }
@GetMapping("checkName") @GetMapping("checkName")
public Result checkName(@RequestParam String name) { public Result checkName(@RequestParam(required = false) Integer id, @RequestParam String name) {
return Result.success(userService.checkName(name) ? null : "该用户名已存在"); if (StringUtils.isEmpty(name)) {
} return Result.success();
private String validate(String username, String password) {
if ((StringUtils.isEmpty(username)
|| StringUtils.isEmpty(password)
|| username.length() > 20
|| password.length() != 32)) {
return "用户名或密码输入有误";
} }
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 (vo.getId() == null) return "修改失败,参数错误";
if (StringUtils.isEmpty(vo.getOld_pwd())) return "修改失败,原密码不能为空"; if (StringUtils.isEmpty(vo.getOld_pwd())) return "修改失败,原密码不能为空";
if (StringUtils.isEmpty(vo.getNew_pwd())) return "修改失败,新密码不能为空"; if (StringUtils.isEmpty(vo.getNew_pwd())) return "修改失败,新密码不能为空";
if (vo.getOld_pwd().equals(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; return null;
} }
} }

@ -3,12 +3,12 @@ package com.toesbieya.my.controller;
import com.toesbieya.my.enumeration.BizDocumentStatusEnum; import com.toesbieya.my.enumeration.BizDocumentStatusEnum;
import com.toesbieya.my.model.entity.BizPurchaseInbound; import com.toesbieya.my.model.entity.BizPurchaseInbound;
import com.toesbieya.my.model.entity.BizPurchaseInboundSub; 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.search.PurchaseInboundSearch;
import com.toesbieya.my.model.vo.update.DocumentStatusUpdate; import com.toesbieya.my.model.vo.update.DocumentStatusUpdate;
import com.toesbieya.my.service.BizPurchaseInboundService; import com.toesbieya.my.service.BizPurchaseInboundService;
import com.toesbieya.my.utils.Result; 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.CollectionUtils;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
@ -51,7 +51,7 @@ public class BizPurchaseInboundController {
String errMsg = validateSub(inbound.getData()); String errMsg = validateSub(inbound.getData());
if (errMsg != null) return Result.fail(errMsg); if (errMsg != null) return Result.fail(errMsg);
SysUser user = Util.getUser(); UserVo user = SessionUtil.get();
inbound.setCid(user.getId()); inbound.setCid(user.getId());
inbound.setCname(user.getName()); inbound.setCname(user.getName());
inbound.setCtime(System.currentTimeMillis()); inbound.setCtime(System.currentTimeMillis());
@ -79,7 +79,7 @@ public class BizPurchaseInboundController {
inbound.setStatus(BizDocumentStatusEnum.WAIT_VERIFY.getCode()); inbound.setStatus(BizDocumentStatusEnum.WAIT_VERIFY.getCode());
if (isFirst) { if (isFirst) {
SysUser user = Util.getUser(); UserVo user = SessionUtil.get();
inbound.setCid(user.getId()); inbound.setCid(user.getId());
inbound.setCname(user.getName()); inbound.setCname(user.getName());
inbound.setCtime(System.currentTimeMillis()); inbound.setCtime(System.currentTimeMillis());
@ -89,18 +89,18 @@ public class BizPurchaseInboundController {
@PostMapping("withdraw") @PostMapping("withdraw")
public Result withdraw(@RequestBody DocumentStatusUpdate vo) { public Result withdraw(@RequestBody DocumentStatusUpdate vo) {
return purchaseInboundService.withdraw(vo, Util.getUser()); return purchaseInboundService.withdraw(vo, SessionUtil.get());
} }
@PostMapping("pass") @PostMapping("pass")
public Result pass(@RequestBody DocumentStatusUpdate vo) { public Result pass(@RequestBody DocumentStatusUpdate vo) {
if (StringUtils.isEmpty(vo.getPid())) return Result.fail("参数错误"); if (StringUtils.isEmpty(vo.getPid())) return Result.fail("参数错误");
return purchaseInboundService.pass(vo, Util.getUser()); return purchaseInboundService.pass(vo, SessionUtil.get());
} }
@PostMapping("reject") @PostMapping("reject")
public Result reject(@RequestBody DocumentStatusUpdate vo) { public Result reject(@RequestBody DocumentStatusUpdate vo) {
return purchaseInboundService.reject(vo, Util.getUser()); return purchaseInboundService.reject(vo, SessionUtil.get());
} }
@GetMapping("del") @GetMapping("del")

@ -3,12 +3,12 @@ package com.toesbieya.my.controller;
import com.toesbieya.my.enumeration.BizDocumentStatusEnum; import com.toesbieya.my.enumeration.BizDocumentStatusEnum;
import com.toesbieya.my.model.entity.BizPurchaseOrder; import com.toesbieya.my.model.entity.BizPurchaseOrder;
import com.toesbieya.my.model.entity.BizPurchaseOrderSub; 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.search.PurchaseOrderSearch;
import com.toesbieya.my.model.vo.update.DocumentStatusUpdate; import com.toesbieya.my.model.vo.update.DocumentStatusUpdate;
import com.toesbieya.my.service.BizPurchaseOrderService; import com.toesbieya.my.service.BizPurchaseOrderService;
import com.toesbieya.my.utils.Result; 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.CollectionUtils;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
@ -56,9 +56,9 @@ public class BizPurchaseOrderController {
String errMsg = validateSub(order.getData()); String errMsg = validateSub(order.getData());
if (errMsg != null) return Result.fail(errMsg); if (errMsg != null) return Result.fail(errMsg);
SysUser sysUser = Util.getUser(); UserVo user = SessionUtil.get();
order.setCid(sysUser.getId()); order.setCid(user.getId());
order.setCname(sysUser.getName()); order.setCname(user.getName());
order.setCtime(System.currentTimeMillis()); order.setCtime(System.currentTimeMillis());
order.setStatus(BizDocumentStatusEnum.DRAFT.getCode()); order.setStatus(BizDocumentStatusEnum.DRAFT.getCode());
@ -85,9 +85,9 @@ public class BizPurchaseOrderController {
order.setStatus(BizDocumentStatusEnum.WAIT_VERIFY.getCode()); order.setStatus(BizDocumentStatusEnum.WAIT_VERIFY.getCode());
if (isFirst) { if (isFirst) {
SysUser sysUser = Util.getUser(); UserVo user = SessionUtil.get();
order.setCid(sysUser.getId()); order.setCid(user.getId());
order.setCname(sysUser.getName()); order.setCname(user.getName());
order.setCtime(System.currentTimeMillis()); order.setCtime(System.currentTimeMillis());
} }
@ -96,17 +96,17 @@ public class BizPurchaseOrderController {
@PostMapping("withdraw") @PostMapping("withdraw")
public Result withdraw(@RequestBody DocumentStatusUpdate vo) { public Result withdraw(@RequestBody DocumentStatusUpdate vo) {
return purchaseOrderService.withdraw(vo, Util.getUser()); return purchaseOrderService.withdraw(vo, SessionUtil.get());
} }
@PostMapping("pass") @PostMapping("pass")
public Result pass(@RequestBody DocumentStatusUpdate vo) { public Result pass(@RequestBody DocumentStatusUpdate vo) {
return purchaseOrderService.pass(vo, Util.getUser()); return purchaseOrderService.pass(vo, SessionUtil.get());
} }
@PostMapping("reject") @PostMapping("reject")
public Result reject(@RequestBody DocumentStatusUpdate vo) { public Result reject(@RequestBody DocumentStatusUpdate vo) {
return purchaseOrderService.reject(vo, Util.getUser()); return purchaseOrderService.reject(vo, SessionUtil.get());
} }
@GetMapping("del") @GetMapping("del")

@ -3,12 +3,12 @@ package com.toesbieya.my.controller;
import com.toesbieya.my.enumeration.BizDocumentStatusEnum; import com.toesbieya.my.enumeration.BizDocumentStatusEnum;
import com.toesbieya.my.model.entity.BizSellOrder; import com.toesbieya.my.model.entity.BizSellOrder;
import com.toesbieya.my.model.entity.BizSellOrderSub; 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.search.SellOrderSearch;
import com.toesbieya.my.model.vo.update.DocumentStatusUpdate; import com.toesbieya.my.model.vo.update.DocumentStatusUpdate;
import com.toesbieya.my.service.BizSellOrderService; import com.toesbieya.my.service.BizSellOrderService;
import com.toesbieya.my.utils.Result; 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.CollectionUtils;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
@ -56,7 +56,7 @@ public class BizSellOrderController {
String errMsg = validateSub(order.getData()); String errMsg = validateSub(order.getData());
if (errMsg != null) return Result.fail(errMsg); if (errMsg != null) return Result.fail(errMsg);
SysUser user = Util.getUser(); UserVo user = SessionUtil.get();
order.setCid(user.getId()); order.setCid(user.getId());
order.setCname(user.getName()); order.setCname(user.getName());
@ -86,7 +86,8 @@ public class BizSellOrderController {
order.setStatus(BizDocumentStatusEnum.WAIT_VERIFY.getCode()); order.setStatus(BizDocumentStatusEnum.WAIT_VERIFY.getCode());
if (isFirst) { if (isFirst) {
SysUser user = Util.getUser(); UserVo user = SessionUtil.get();
order.setCid(user.getId()); order.setCid(user.getId());
order.setCname(user.getName()); order.setCname(user.getName());
order.setCtime(System.currentTimeMillis()); order.setCtime(System.currentTimeMillis());
@ -97,17 +98,17 @@ public class BizSellOrderController {
@PostMapping("withdraw") @PostMapping("withdraw")
public Result withdraw(@RequestBody DocumentStatusUpdate vo) { public Result withdraw(@RequestBody DocumentStatusUpdate vo) {
return sellOrderService.withdraw(vo, Util.getUser()); return sellOrderService.withdraw(vo, SessionUtil.get());
} }
@PostMapping("pass") @PostMapping("pass")
public Result pass(@RequestBody DocumentStatusUpdate vo) { public Result pass(@RequestBody DocumentStatusUpdate vo) {
return sellOrderService.pass(vo, Util.getUser()); return sellOrderService.pass(vo, SessionUtil.get());
} }
@PostMapping("reject") @PostMapping("reject")
public Result reject(@RequestBody DocumentStatusUpdate vo) { public Result reject(@RequestBody DocumentStatusUpdate vo) {
return sellOrderService.reject(vo, Util.getUser()); return sellOrderService.reject(vo, SessionUtil.get());
} }
@GetMapping("del") @GetMapping("del")

@ -3,12 +3,12 @@ package com.toesbieya.my.controller;
import com.toesbieya.my.enumeration.BizDocumentStatusEnum; import com.toesbieya.my.enumeration.BizDocumentStatusEnum;
import com.toesbieya.my.model.entity.BizSellOutbound; import com.toesbieya.my.model.entity.BizSellOutbound;
import com.toesbieya.my.model.entity.BizSellOutboundSub; 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.search.SellOutboundSearch;
import com.toesbieya.my.model.vo.update.DocumentStatusUpdate; import com.toesbieya.my.model.vo.update.DocumentStatusUpdate;
import com.toesbieya.my.service.BizSellOutboundService; import com.toesbieya.my.service.BizSellOutboundService;
import com.toesbieya.my.utils.Result; 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.CollectionUtils;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
@ -51,7 +51,8 @@ public class BizSellOutboundController {
String errMsg = validateSub(outbound.getData()); String errMsg = validateSub(outbound.getData());
if (errMsg != null) return Result.fail(errMsg); if (errMsg != null) return Result.fail(errMsg);
SysUser user = Util.getUser(); UserVo user = SessionUtil.get();
outbound.setCid(user.getId()); outbound.setCid(user.getId());
outbound.setCname(user.getName()); outbound.setCname(user.getName());
outbound.setCtime(System.currentTimeMillis()); outbound.setCtime(System.currentTimeMillis());
@ -79,9 +80,10 @@ public class BizSellOutboundController {
outbound.setStatus(BizDocumentStatusEnum.WAIT_VERIFY.getCode()); outbound.setStatus(BizDocumentStatusEnum.WAIT_VERIFY.getCode());
if (isFirst) { if (isFirst) {
SysUser sysUser = Util.getUser(); UserVo user = SessionUtil.get();
outbound.setCid(sysUser.getId());
outbound.setCname(sysUser.getName()); outbound.setCid(user.getId());
outbound.setCname(user.getName());
outbound.setCtime(System.currentTimeMillis()); outbound.setCtime(System.currentTimeMillis());
} }
return sellOutboundService.commit(outbound); return sellOutboundService.commit(outbound);
@ -89,18 +91,18 @@ public class BizSellOutboundController {
@PostMapping("withdraw") @PostMapping("withdraw")
public Result withdraw(@RequestBody DocumentStatusUpdate vo) { public Result withdraw(@RequestBody DocumentStatusUpdate vo) {
return sellOutboundService.withdraw(vo, Util.getUser()); return sellOutboundService.withdraw(vo, SessionUtil.get());
} }
@PostMapping("pass") @PostMapping("pass")
public Result pass(@RequestBody DocumentStatusUpdate vo) { public Result pass(@RequestBody DocumentStatusUpdate vo) {
if (StringUtils.isEmpty(vo.getPid())) return Result.fail("参数错误"); if (StringUtils.isEmpty(vo.getPid())) return Result.fail("参数错误");
return sellOutboundService.pass(vo, Util.getUser()); return sellOutboundService.pass(vo, SessionUtil.get());
} }
@PostMapping("reject") @PostMapping("reject")
public Result reject(@RequestBody DocumentStatusUpdate vo) { public Result reject(@RequestBody DocumentStatusUpdate vo) {
return sellOutboundService.reject(vo, Util.getUser()); return sellOutboundService.reject(vo, SessionUtil.get());
} }
@GetMapping("del") @GetMapping("del")

@ -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());
}
}

@ -2,12 +2,12 @@ package com.toesbieya.my.controller;
import com.toesbieya.my.constant.MsgConstant; import com.toesbieya.my.constant.MsgConstant;
import com.toesbieya.my.model.entity.Msg; 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.MsgPersonalSearch;
import com.toesbieya.my.model.vo.search.MsgSearch; import com.toesbieya.my.model.vo.search.MsgSearch;
import com.toesbieya.my.service.MsgService; import com.toesbieya.my.service.MsgService;
import com.toesbieya.my.utils.Result; 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.util.StringUtils;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
@ -29,7 +29,8 @@ public class MsgController {
String errMsg = validateAdd(msg); String errMsg = validateAdd(msg);
if (errMsg != null) return Result.fail(errMsg); if (errMsg != null) return Result.fail(errMsg);
SysUser user = Util.getUser(); UserVo user = SessionUtil.get();
setAddInfo(user, msg); setAddInfo(user, msg);
return msgService.add(msg); return msgService.add(msg);
@ -52,8 +53,10 @@ public class MsgController {
if (errMsg == null && !isFirstCreate) errMsg = validateUpdate(msg); if (errMsg == null && !isFirstCreate) errMsg = validateUpdate(msg);
if (errMsg != null) return Result.fail(errMsg); if (errMsg != null) return Result.fail(errMsg);
SysUser user = Util.getUser(); UserVo user = SessionUtil.get();
if (isFirstCreate) setAddInfo(user, msg); if (isFirstCreate) setAddInfo(user, msg);
msg.setPid(user.getId()); msg.setPid(user.getId());
msg.setPname(user.getName()); msg.setPname(user.getName());
msg.setPtime(System.currentTimeMillis()); msg.setPtime(System.currentTimeMillis());
@ -66,7 +69,8 @@ public class MsgController {
public Result withdraw(@RequestBody Msg msg) { public Result withdraw(@RequestBody Msg msg) {
if (msg.getId() == null) return Result.fail("参数错误"); if (msg.getId() == null) return Result.fail("参数错误");
SysUser user = Util.getUser(); UserVo user = SessionUtil.get();
msg.setWid(user.getId()); msg.setWid(user.getId());
msg.setWname(user.getName()); msg.setWname(user.getName());
msg.setWtime(System.currentTimeMillis()); msg.setWtime(System.currentTimeMillis());
@ -82,23 +86,25 @@ public class MsgController {
@PostMapping("user/search") @PostMapping("user/search")
public Result searchPersonal(@RequestBody MsgPersonalSearch vo) { public Result searchPersonal(@RequestBody MsgPersonalSearch vo) {
SysUser user = Util.getUser(); UserVo user = SessionUtil.get();
vo.setUid(user.getId()); vo.setUid(user.getId());
vo.setCtime(user.getCtime()); vo.setCtime(user.getCtime());
return Result.success(msgService.searchPersonal(vo)); return Result.success(msgService.searchPersonal(vo));
} }
@GetMapping("user/read") @GetMapping("user/read")
public Result read(@RequestParam Integer id) { public Result read(@RequestParam Integer id) {
return msgService.read(Util.getUser(), id); return msgService.read(SessionUtil.get(), id);
} }
@GetMapping("user/readAll") @GetMapping("user/readAll")
public Result 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.setCid(user.getId());
msg.setCname(user.getName()); msg.setCname(user.getName());
msg.setCtime(System.currentTimeMillis()); msg.setCtime(System.currentTimeMillis());

@ -1,12 +1,12 @@
package com.toesbieya.my.controller; 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.LoginHistorySearch;
import com.toesbieya.my.model.vo.search.UserActionSearch; import com.toesbieya.my.model.vo.search.UserActionSearch;
import com.toesbieya.my.service.RecService; import com.toesbieya.my.service.RecService;
import com.toesbieya.my.utils.DateUtil; import com.toesbieya.my.utils.DateUtil;
import com.toesbieya.my.utils.Result; 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.PostMapping;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
@ -22,7 +22,8 @@ public class RecController {
@PostMapping("searchLoginHistory") @PostMapping("searchLoginHistory")
public Result searchLoginHistory(@RequestBody LoginHistorySearch vo) { public Result searchLoginHistory(@RequestBody LoginHistorySearch vo) {
SysUser user = Util.getUser(); UserVo user = SessionUtil.get();
vo.setUid(user.getId()); vo.setUid(user.getId());
vo.setStartTime(DateUtil.getTimestampBeforeNow(7)); vo.setStartTime(DateUtil.getTimestampBeforeNow(7));
@ -31,7 +32,8 @@ public class RecController {
@PostMapping("searchUserAction") @PostMapping("searchUserAction")
public Result searchUserAction(@RequestBody UserActionSearch vo) { public Result searchUserAction(@RequestBody UserActionSearch vo) {
SysUser user = Util.getUser(); UserVo user = SessionUtil.get();
vo.setUid(user.getId()); vo.setUid(user.getId());
vo.setStartTime(DateUtil.getTimestampBeforeNow(7)); vo.setStartTime(DateUtil.getTimestampBeforeNow(7));

@ -28,8 +28,7 @@ public class SysDepartmentController {
public Result add(@RequestBody SysDepartment department) { public Result add(@RequestBody SysDepartment department) {
if (null == department.getPid() if (null == department.getPid()
|| StringUtils.isEmpty(department.getName()) || StringUtils.isEmpty(department.getName())
|| null == department.getStatus() || null == department.getStatus()) {
) {
return Result.fail("添加失败,参数错误"); return Result.fail("添加失败,参数错误");
} }
return departmentService.add(department); return departmentService.add(department);
@ -40,8 +39,7 @@ public class SysDepartmentController {
if (null == department.getId() if (null == department.getId()
|| null == department.getPid() || null == department.getPid()
|| StringUtils.isEmpty(department.getName()) || StringUtils.isEmpty(department.getName())
|| null == department.getStatus() || null == department.getStatus()) {
) {
return Result.fail("修改失败,参数错误"); return Result.fail("修改失败,参数错误");
} }
return departmentService.update(department); return departmentService.update(department);

@ -1,24 +1,21 @@
package com.toesbieya.my.controller; package com.toesbieya.my.controller;
import com.toesbieya.my.model.entity.SysRole; 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.model.vo.search.RoleSearch;
import com.toesbieya.my.service.SysRoleService; import com.toesbieya.my.service.SysRoleService;
import com.toesbieya.my.utils.Result; 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.util.StringUtils;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource; import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
@RequestMapping("system/role") @RequestMapping("system/role")
@RestController @RestController
public class SysRoleController { public class SysRoleController {
@Resource @Resource
private SysRoleService roleService; private SysRoleService roleService;
@Resource
private HttpSession session;
@GetMapping("get") @GetMapping("get")
public Result get() { public Result get() {
@ -37,7 +34,8 @@ public class SysRoleController {
return Result.fail("添加失败,参数错误"); return Result.fail("添加失败,参数错误");
} }
SysUser user = Util.getUser(); UserVo user = SessionUtil.get();
role.setCid(user.getId()); role.setCid(user.getId());
role.setCname(user.getName()); role.setCname(user.getName());
role.setCtime(System.currentTimeMillis()); role.setCtime(System.currentTimeMillis());

@ -42,7 +42,6 @@ public class SysUserController {
if (errMsg != null) { if (errMsg != null) {
return Result.fail(errMsg); return Result.fail(errMsg);
} }
userService.setUpdateAction(user);
return userService.update(user); return userService.update(user);
} }

@ -1,11 +1,8 @@
package com.toesbieya.my.interceptor; 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.module.request.RequestModule;
import com.toesbieya.my.utils.IpUtil; import com.toesbieya.my.utils.*;
import com.toesbieya.my.utils.Result;
import com.toesbieya.my.utils.ThreadUtil;
import com.toesbieya.my.utils.Util;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.HandlerInterceptor;
@ -16,29 +13,34 @@ import javax.servlet.http.HttpServletResponse;
public class RateControlInterceptor implements HandlerInterceptor { public class RateControlInterceptor implements HandlerInterceptor {
@Override @Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { 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; if (user.getAdmin() == 1) return true;
String url = request.getServletPath(); String url = request.getServletPath();
String ip = IpUtil.getIp(request); String ip = IpUtil.getIp(request);
int result = RequestModule.pass(url, ip); int result = RequestModule.pass(url, ip);
switch (result) { switch (result) {
case -1: case -1:
log.warn("限流拦截,服务的总请求频率超出,url:{},用户:{},ip:{}", url, user.getName(), ip); log.warn("限流拦截,服务的总请求频率超出,url:{},用户:{},ip:{}", url, user.getName(), ip);
Util.responseJson(response, Result.overload()); WebUtil.responseJson(response, Result.overload());
break; break;
case 0: case 0:
log.warn("限流拦截,ip已被暂时拉黑,url:{},用户:{},ip:{}", url, user.getName(), ip); log.warn("限流拦截,ip已被暂时拉黑,url:{},用户:{},ip:{}", url, user.getName(), ip);
Util.responseJson(response, Result.tooManyRequest()); WebUtil.responseJson(response, Result.tooManyRequest());
break; break;
case -2: case -2:
log.warn("限流拦截,ip的请求频率超出,url:{},用户:{},ip:{}", url, user.getName(), ip); log.warn("限流拦截,ip的请求频率超出,url:{},用户:{},ip:{}", url, user.getName(), ip);
Util.responseJson(response, Result.tooManyRequest()); WebUtil.responseJson(response, Result.tooManyRequest());
break; break;
case 1: case 1:
return true; return true;
} }
ThreadUtil.clearUser(); ThreadUtil.clearUser();
return false; return false;
} }
} }

@ -1,66 +1,45 @@
package com.toesbieya.my.interceptor; package com.toesbieya.my.interceptor;
import com.toesbieya.my.constant.SessionConstant; import com.toesbieya.my.model.vo.UserVo;
import com.toesbieya.my.model.entity.SysUser;
import com.toesbieya.my.module.PermissionModule; import com.toesbieya.my.module.PermissionModule;
import com.toesbieya.my.module.request.RequestModule; import com.toesbieya.my.module.request.RequestModule;
import com.toesbieya.my.utils.IpUtil; import com.toesbieya.my.utils.*;
import com.toesbieya.my.utils.Result;
import com.toesbieya.my.utils.ThreadUtil;
import com.toesbieya.my.utils.Util;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@Slf4j @Slf4j
public class SecurityInterceptor implements HandlerInterceptor { public class SecurityInterceptor implements HandlerInterceptor {
@Override @Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HttpSession httpSession = request.getSession();
String url = request.getServletPath(); String url = request.getServletPath();
String method = request.getMethod(); String method = request.getMethod();
String ip = IpUtil.getIp(request); String ip = IpUtil.getIp(request);
if (!RequestModule.urlExistMapping(url, method)) { if (!RequestModule.urlExistMapping(url, method)) {
Util.responseJson(response, Result.notfound()); WebUtil.responseJson(response, Result.notfound());
log.error("请求地址不存在:{},{},IP:{}", url, method, ip); log.error("请求地址不存在:{},{},IP:{}", url, method, ip);
ThreadUtil.clearUser(); ThreadUtil.clearUser();
return false; return false;
} }
SysUser sysUser = Util.getUser(httpSession); UserVo user = SessionUtil.get(request);
if (sysUser == null
|| request.getHeader(SessionConstant.TOKEN_KEY) == null if (user == null) {
|| !request.getHeader(SessionConstant.TOKEN_KEY).equals(httpSession.getAttribute(SessionConstant.TOKEN_KEY))) { WebUtil.responseJson(response, Result.requireLogin());
Util.responseJson(response, Result.requireLogin());
ThreadUtil.clearUser(); ThreadUtil.clearUser();
return false; return false;
} }
if (!PermissionModule.authority(sysUser, url)) { if (!PermissionModule.authority(user, url)) {
Util.responseJson(response, Result.noPermission()); WebUtil.responseJson(response, Result.noPermission());
log.warn("权限拦截,访问路径:{},用户:{},IP:{}", url, sysUser.getName(), ip); log.warn("权限拦截,访问路径:{},用户:{},IP:{}", url, user.getName(), ip);
ThreadUtil.clearUser(); ThreadUtil.clearUser();
return false; return false;
} }
ThreadUtil.setUser(sysUser);
return true; 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 {
}
} }

@ -1,18 +1,17 @@
package com.toesbieya.my.mapper; package com.toesbieya.my.mapper;
import com.toesbieya.my.model.entity.SysUser; 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.search.UserSearch;
import com.toesbieya.my.model.vo.update.UserUpdatePwd;
import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Param;
import java.util.List; import java.util.List;
public interface SysUserMapper { public interface SysUserMapper {
SysUser getById(@Param("id") Integer id);
SysUser getByNameAndPwd(@Param("name") String name, @Param("pwd") String pwd); SysUser getByNameAndPwd(@Param("name") String name, @Param("pwd") String pwd);
List<SysUser> search(UserSearch vo); List<UserVo> search(UserSearch vo);
boolean isNameExist(@Param("name") String name, @Param("id") Integer id); 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 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); int updateAvatar(@Param("id") Integer id, @Param("avatar") String avatar);
} }

@ -4,37 +4,16 @@ import lombok.AllArgsConstructor;
import lombok.Data; import lombok.Data;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.util.HashSet;
@Data @Data
@AllArgsConstructor @AllArgsConstructor
@NoArgsConstructor @NoArgsConstructor
public class SysUser implements Serializable { public class SysUser {
private static final long serialVersionUID = 9527L;
private Integer id; private Integer id;
private String name; private String name;
private String pwd; private String pwd;
private Integer role; private Integer role;
private String role_name;
private String avatar; private String avatar;
private Long ctime; private Long ctime;
private Integer admin; private Integer admin;
private Integer status; private Integer status;
private Boolean online;
private HashSet<Integer> 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();
}
} }

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

@ -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<String, Integer> resources;
public LoginSuccessInfo(SysUser user) {
this.id = user.getId();
this.name = user.getName();
this.avatar = user.getAvatar();
this.admin = user.getAdmin();
}
}

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

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

@ -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<Integer> resource_ids;
private Map<String, Integer> 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());
}
}

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

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

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

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

@ -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<DiskInfo> diskInfos;
private Long timestamp;
private Integer expire;
}

@ -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();
}
}

@ -1,20 +1,18 @@
package com.toesbieya.my.module; package com.toesbieya.my.module;
import com.toesbieya.my.model.entity.SysResource; 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 com.toesbieya.my.service.SysResourceService;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
import javax.annotation.Resource; import javax.annotation.Resource;
import java.time.Instant; import java.time.Instant;
import java.time.temporal.ChronoUnit; import java.time.temporal.ChronoUnit;
import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
@Component
@Slf4j @Slf4j
public class PermissionModule { public class PermissionModule {
private final static ConcurrentHashMap<String, Integer> urlMap = new ConcurrentHashMap<>(128); private final static ConcurrentHashMap<String, Integer> urlMap = new ConcurrentHashMap<>(128);
@ -22,13 +20,17 @@ public class PermissionModule {
@Resource @Resource
private SysResourceService resourceService; private SysResourceService resourceService;
public static boolean authority(SysUser sysUser, String url) { public static boolean authority(UserVo user, String url) {
if (sysUser.getAdmin() == 1 || !needAuthority(url)) { if (user.getAdmin() == 1 || !needAuthority(url)) {
return true; return true;
} }
if (adminUrlMap.containsKey(url)) return false; if (adminUrlMap.containsKey(url)) return false;
HashSet<Integer> ids = sysUser.getResource_ids();
Set<Integer> ids = user.getResource_ids();
if (ids == null) return false; if (ids == null) return false;
return ids.contains(urlMap.get(url)); return ids.contains(urlMap.get(url));
} }
@ -41,6 +43,7 @@ public class PermissionModule {
Instant start = Instant.now(); Instant start = Instant.now();
List<SysResource> resources = resourceService.getAll(); List<SysResource> resources = resourceService.getAll();
if (resources != null) { if (resources != null) {
for (SysResource p : resources) { for (SysResource p : resources) {
if (p.getAdmin() == 1) { if (p.getAdmin() == 1) {
@ -49,7 +52,9 @@ public class PermissionModule {
else urlMap.put(p.getUrl(), p.getId()); else urlMap.put(p.getUrl(), p.getId());
} }
} }
Instant end = Instant.now(); Instant end = Instant.now();
log.info("权限模块启动成功,耗时:{}毫秒", ChronoUnit.MILLIS.between(start, end)); log.info("权限模块启动成功,耗时:{}毫秒", ChronoUnit.MILLIS.between(start, end));
} }
} }

@ -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.DateUtil;
import com.toesbieya.my.utils.RedisUtil; import com.toesbieya.my.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
@ -19,9 +20,6 @@ import java.util.Map;
@Slf4j @Slf4j
@DependsOn("redisUtil") @DependsOn("redisUtil")
public class RedisModule { public class RedisModule {
public static final String DOCUMENTS_KEY = "documentsID";
public static final String[] DOCUMENTS_TYPE = {"CGDD", "CGRK", "CGTH", "XSDD", "XSCK", "XSTH"};
@PostConstruct @PostConstruct
public void init() { public void init() {
Instant start = Instant.now(); Instant start = Instant.now();
@ -34,17 +32,17 @@ public class RedisModule {
//初始化单据ID //初始化单据ID
private void initDocumentsID() { private void initDocumentsID() {
String[] fields = new String[DOCUMENTS_TYPE.length + 1]; String[] fields = new String[DocumentConstant.DOCUMENT_TYPE.length + 1];
fields[0] = "date"; fields[0] = "date";
System.arraycopy(DOCUMENTS_TYPE, 0, fields, 1, fields.length - 1); System.arraycopy(DocumentConstant.DOCUMENT_TYPE, 0, fields, 1, fields.length - 1);
List<Object> result = RedisUtil.hmget(DOCUMENTS_KEY, fields); List<Object> result = RedisUtil.hmget(DocumentConstant.DOCUMENT_TYPE_REDIS_KEY, fields);
long now = DateUtil.getTimestampNow(); long now = DateUtil.getTimestampNow();
//日期不是今天时,更新全部,初始值为1 //日期不是今天时,更新全部,初始值为1
if (null == result.get(0) || now != (long) result.get(0)) { if (null == result.get(0) || now != (long) result.get(0)) {
updateAllDocument(now); updateAllDocument(now);
log.info("更新【{}】种单据ID成功", DOCUMENTS_TYPE.length); log.info("更新【{}】种单据ID成功", DocumentConstant.DOCUMENT_TYPE.length);
return; return;
} }
@ -55,11 +53,11 @@ public class RedisModule {
for (int i = 1; i < resultSize; i++) { for (int i = 1; i < resultSize; i++) {
if (result.get(i) == null) { if (result.get(i) == null) {
updateNum++; updateNum++;
update.put(DOCUMENTS_TYPE[i - 1], 1); update.put(DocumentConstant.DOCUMENT_TYPE[i - 1], 1);
} }
} }
if (updateNum > 0) { if (updateNum > 0) {
RedisUtil.hmset(DOCUMENTS_KEY, update); RedisUtil.hmset(DocumentConstant.DOCUMENT_TYPE_REDIS_KEY, update);
log.info("更新增加的单据【{}】种", updateNum); log.info("更新增加的单据【{}】种", updateNum);
} }
} }
@ -67,24 +65,30 @@ public class RedisModule {
private void updateAllDocument(long now) { private void updateAllDocument(long now) {
Map<String, Object> map = new HashMap<>(); Map<String, Object> map = new HashMap<>();
map.put("date", now); map.put("date", now);
for (String v : DOCUMENTS_TYPE) { for (String v : DocumentConstant.DOCUMENT_TYPE) {
map.put(v, 1); map.put(v, 1);
} }
RedisUtil.hmset(DOCUMENTS_KEY, map); RedisUtil.hmset(DocumentConstant.DOCUMENT_TYPE_REDIS_KEY, map);
} }
//每天零点初始化单据ID //每天零点初始化单据ID
@Async("scheduledExecutor") @Async("scheduledExecutor")
@Scheduled(cron = "1 0 0 */1 * ?") @Scheduled(cron = "1 0 0 */1 * ?")
public void autoRefreshDocumentID() { public void autoRefreshDocumentID() {
log.info("开始定时更新单据ID......当前共有【{}】种待更新......", DOCUMENTS_TYPE.length); log.info("开始定时更新单据ID......当前共有【{}】种待更新......", DocumentConstant.DOCUMENT_TYPE.length);
try (LockHelper locker = new RedisLockHelper(RedisLockType.UPDATE_DOCUMENT_ID)) {
String lockKey = DocumentConstant.UPDATE_DOCUMENTS_LOCK_KEY;
try (RedisUtil.Locker locker = new RedisUtil.Locker(lockKey)) {
if (!locker.lock()) { if (!locker.lock()) {
log.error("定时更新单据ID失败,获取锁【{}】失败", RedisLockType.UPDATE_DOCUMENT_ID); log.error("定时更新单据ID失败,获取锁【{}】失败", lockKey);
return; return;
} }
updateAllDocument(DateUtil.getTimestampNow()); updateAllDocument(DateUtil.getTimestampNow());
log.info("定时更新单据ID结束,成功更新【{}】种", DOCUMENTS_TYPE.length);
log.info("定时更新单据ID结束,成功更新【{}】种", DocumentConstant.DOCUMENT_TYPE.length);
} catch (Exception e) { } catch (Exception e) {
log.error("定时更新单据ID失败", e); log.error("定时更新单据ID失败", e);
} }

@ -6,9 +6,8 @@ import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.annotation.OnConnect; import com.corundumstudio.socketio.annotation.OnConnect;
import com.corundumstudio.socketio.annotation.OnDisconnect; import com.corundumstudio.socketio.annotation.OnDisconnect;
import com.corundumstudio.socketio.annotation.OnEvent; import com.corundumstudio.socketio.annotation.OnEvent;
import com.toesbieya.my.constant.SessionConstant;
import com.toesbieya.my.constant.SocketConstant; import com.toesbieya.my.constant.SocketConstant;
import com.toesbieya.my.utils.RedisUtil; import com.toesbieya.my.utils.SessionUtil;
import lombok.Data; import lombok.Data;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -23,7 +22,7 @@ import java.util.function.BiConsumer;
@Component @Component
@Slf4j @Slf4j
public class SocketModule { public class SocketModule {
private static final ConcurrentHashMap<Integer, UserObject> socketMap = new ConcurrentHashMap<>(SessionConstant.PREDICT_MAX_USER); private static final ConcurrentHashMap<Integer, UserObject> socketMap = new ConcurrentHashMap<>(128);
private static SocketIOServer server; private static SocketIOServer server;
@Autowired @Autowired
@ -38,10 +37,15 @@ public class SocketModule {
public static void sendEvent(String event, Integer uid, Object data, BiConsumer<UserObject, SocketIOClient> consumer) { public static void sendEvent(String event, Integer uid, Object data, BiConsumer<UserObject, SocketIOClient> consumer) {
UserObject obj = socketMap.get(uid); UserObject obj = socketMap.get(uid);
if (obj == null) return; if (obj == null) return;
SocketIOClient client = server.getClient(obj.getUuid()); SocketIOClient client = server.getClient(obj.getUuid());
if (client == null) return; if (client == null) return;
client.sendEvent(event, data); client.sendEvent(event, data);
if (consumer != null) consumer.accept(obj, client); if (consumer != null) consumer.accept(obj, client);
} }
@ -53,11 +57,26 @@ public class SocketModule {
return uid != null && socketMap.containsKey(uid); 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 @OnConnect
public void onConnect(SocketIOClient client) { public void onConnect(SocketIOClient client) {
UserObject obj = new UserObject(client); UserObject obj = new UserObject(client);
Integer uid = obj.getUid(); Integer uid = obj.getUid();
if (socketMap.containsKey(uid)) logout(uid, "该账号在其他位置登录");
if (socketMap.containsKey(uid)) {
logout(uid, "该账号在其他位置登录");
}
else socketMap.put(uid, obj); else socketMap.put(uid, obj);
} }
@ -66,48 +85,32 @@ public class SocketModule {
UserObject obj = new UserObject(client); UserObject obj = new UserObject(client);
Integer uid = obj.getUid(); Integer uid = obj.getUid();
UserObject already = socketMap.get(uid); UserObject already = socketMap.get(uid);
if (already == null) return; if (already == null) return;
//只有sessionID相同时才移除
if (obj.getSessionID().equals(already.getSessionID())) { //只有token相同时才移除
if (obj.getToken().equals(already.getToken())) {
socketMap.remove(uid); socketMap.remove(uid);
} }
} }
@OnEvent("text") @OnEvent("text")
public void onEvent(SocketIOClient client, AckRequest ackRequest, String data) { public void onEvent(SocketIOClient client, AckRequest ackRequest, String data) {
System.out.println(getIp(client) + ":客户端:************" + data);
client.sendEvent("response", "后台得到了数据"); 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 @Data
private static class UserObject { private static class UserObject {
private Integer uid;//用户id private Integer uid; //用户id
private String sessionID;//redis中的sessionID private String token; //redis中的token
private UUID uuid;//socketClient自己的sessionID private UUID uuid; //socketClient自己的sessionID
public UserObject(SocketIOClient client) { public UserObject(SocketIOClient client) {
Map<String, List<String>> params = client.getHandshakeData().getUrlParams(); Map<String, List<String>> params = client.getHandshakeData().getUrlParams();
List<String> list = params.get("id"); List<String> list = params.get("id");
this.uid = Integer.valueOf(list.get(0)); this.uid = Integer.valueOf(list.get(0));
list = params.get("session_id"); list = params.get("token");
this.sessionID = list.get(0); this.token = list.get(0);
this.uuid = client.getSessionId(); this.uuid = client.getSessionId();
} }
} }

@ -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();
}

@ -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<Boolean> 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<Boolean> 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);
}
}
}

@ -1,5 +0,0 @@
package com.toesbieya.my.module.redis;
public class RedisLockType {
public static final String UPDATE_DOCUMENT_ID = "UPDATE_DOCUMENTS";
}

@ -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<String, Integer> userResourcesUrlMap = null;
Set<Integer> userResourcesIdSet = null;
//获取用户的所有权限url
if (roleId != null) {
List<SysResource> 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);
}
}

@ -13,14 +13,12 @@ import com.toesbieya.my.mapper.BizPurchaseInboundMapper;
import com.toesbieya.my.mapper.BizPurchaseOrderMapper; import com.toesbieya.my.mapper.BizPurchaseOrderMapper;
import com.toesbieya.my.mapper.BizStockMapper; import com.toesbieya.my.mapper.BizStockMapper;
import com.toesbieya.my.model.entity.*; 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.export.PurchaseInboundExport;
import com.toesbieya.my.model.vo.result.PageResult; import com.toesbieya.my.model.vo.result.PageResult;
import com.toesbieya.my.model.vo.search.PurchaseInboundSearch; import com.toesbieya.my.model.vo.search.PurchaseInboundSearch;
import com.toesbieya.my.model.vo.update.DocumentStatusUpdate; import com.toesbieya.my.model.vo.update.DocumentStatusUpdate;
import com.toesbieya.my.utils.ExcelUtil; import com.toesbieya.my.utils.*;
import com.toesbieya.my.utils.RedisUtil;
import com.toesbieya.my.utils.Result;
import com.toesbieya.my.utils.Util;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
@ -108,7 +106,7 @@ public class BizPurchaseInboundService {
@UserAction("'撤回采购入库单'+#vo.id") @UserAction("'撤回采购入库单'+#vo.id")
@Lock("#vo.id") @Lock("#vo.id")
@Tx @Tx
public Result withdraw(DocumentStatusUpdate vo, SysUser user) { public Result withdraw(DocumentStatusUpdate vo, UserVo user) {
String id = vo.getId(); String id = vo.getId();
String info = vo.getInfo(); String info = vo.getInfo();
@ -135,7 +133,7 @@ public class BizPurchaseInboundService {
@UserAction("'通过采购入库单'+#vo.id") @UserAction("'通过采购入库单'+#vo.id")
@Lock({"#vo.pid", "#vo.id"}) @Lock({"#vo.pid", "#vo.id"})
@Tx @Tx
public Result pass(DocumentStatusUpdate vo, SysUser user) { public Result pass(DocumentStatusUpdate vo, UserVo user) {
String id = vo.getId(); String id = vo.getId();
String info = vo.getInfo(); String info = vo.getInfo();
String pid = vo.getPid(); String pid = vo.getPid();
@ -202,7 +200,7 @@ public class BizPurchaseInboundService {
@UserAction("'驳回采购入库单'+#vo.id") @UserAction("'驳回采购入库单'+#vo.id")
@Lock("#vo.id") @Lock("#vo.id")
@Tx @Tx
public Result reject(DocumentStatusUpdate vo, SysUser user) { public Result reject(DocumentStatusUpdate vo, UserVo user) {
String id = vo.getId(); String id = vo.getId();
String info = vo.getInfo(); String info = vo.getInfo();
@ -240,7 +238,7 @@ public class BizPurchaseInboundService {
String err = checkOrder(doc.getPid(), doc.getData()); String err = checkOrder(doc.getPid(), doc.getData());
if (err != null) return Result.fail(err); if (err != null) return Result.fail(err);
String id = RedisUtil.getDocumentID("CGRK"); String id = DocumentUtil.getDocumentID("CGRK");
if (StringUtils.isEmpty(id)) return Result.fail("获取单号失败"); if (StringUtils.isEmpty(id)) return Result.fail("获取单号失败");
doc.setId(id); doc.setId(id);

@ -9,12 +9,13 @@ import com.toesbieya.my.enumeration.BizDocumentStatusEnum;
import com.toesbieya.my.mapper.BizDocumentHistoryMapper; import com.toesbieya.my.mapper.BizDocumentHistoryMapper;
import com.toesbieya.my.mapper.BizPurchaseOrderMapper; import com.toesbieya.my.mapper.BizPurchaseOrderMapper;
import com.toesbieya.my.model.entity.*; 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.export.PurchaseOrderExport;
import com.toesbieya.my.model.vo.result.PageResult; import com.toesbieya.my.model.vo.result.PageResult;
import com.toesbieya.my.model.vo.search.PurchaseOrderSearch; import com.toesbieya.my.model.vo.search.PurchaseOrderSearch;
import com.toesbieya.my.model.vo.update.DocumentStatusUpdate; 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.ExcelUtil;
import com.toesbieya.my.utils.RedisUtil;
import com.toesbieya.my.utils.Result; import com.toesbieya.my.utils.Result;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@ -99,7 +100,7 @@ public class BizPurchaseOrderService {
@UserAction("'撤回采购订单'+#vo.id") @UserAction("'撤回采购订单'+#vo.id")
@Lock("#vo.id") @Lock("#vo.id")
@Tx @Tx
public Result withdraw(DocumentStatusUpdate vo, SysUser user) { public Result withdraw(DocumentStatusUpdate vo, UserVo user) {
String id = vo.getId(); String id = vo.getId();
String info = vo.getInfo(); String info = vo.getInfo();
@ -126,7 +127,7 @@ public class BizPurchaseOrderService {
@UserAction("'通过采购订单'+#vo.id") @UserAction("'通过采购订单'+#vo.id")
@Lock("#vo.id") @Lock("#vo.id")
@Tx @Tx
public Result pass(DocumentStatusUpdate vo, SysUser user) { public Result pass(DocumentStatusUpdate vo, UserVo user) {
String id = vo.getId(); String id = vo.getId();
String info = vo.getInfo(); String info = vo.getInfo();
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
@ -154,7 +155,7 @@ public class BizPurchaseOrderService {
@UserAction("'驳回采购订单'+#vo.id") @UserAction("'驳回采购订单'+#vo.id")
@Lock("#vo.id") @Lock("#vo.id")
@Tx @Tx
public Result reject(DocumentStatusUpdate vo, SysUser user) { public Result reject(DocumentStatusUpdate vo, UserVo user) {
String id = vo.getId(); String id = vo.getId();
String info = vo.getInfo(); String info = vo.getInfo();
@ -189,7 +190,7 @@ public class BizPurchaseOrderService {
} }
private Result addOrder(BizPurchaseOrder doc) { private Result addOrder(BizPurchaseOrder doc) {
String id = RedisUtil.getDocumentID("CGDD"); String id = DocumentUtil.getDocumentID("CGDD");
if (StringUtils.isEmpty(id)) return Result.fail("获取单号失败"); if (StringUtils.isEmpty(id)) return Result.fail("获取单号失败");
doc.setId(id); doc.setId(id);

@ -10,14 +10,15 @@ import com.toesbieya.my.mapper.BizDocumentHistoryMapper;
import com.toesbieya.my.mapper.BizSellOrderMapper; import com.toesbieya.my.mapper.BizSellOrderMapper;
import com.toesbieya.my.mapper.BizStockMapper; import com.toesbieya.my.mapper.BizStockMapper;
import com.toesbieya.my.model.entity.*; 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.export.SellOrderExport;
import com.toesbieya.my.model.vo.result.PageResult; import com.toesbieya.my.model.vo.result.PageResult;
import com.toesbieya.my.model.vo.result.StockSearchResult; import com.toesbieya.my.model.vo.result.StockSearchResult;
import com.toesbieya.my.model.vo.search.SellOrderSearch; import com.toesbieya.my.model.vo.search.SellOrderSearch;
import com.toesbieya.my.model.vo.search.StockSearch; import com.toesbieya.my.model.vo.search.StockSearch;
import com.toesbieya.my.model.vo.update.DocumentStatusUpdate; 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.ExcelUtil;
import com.toesbieya.my.utils.RedisUtil;
import com.toesbieya.my.utils.Result; import com.toesbieya.my.utils.Result;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@ -107,7 +108,7 @@ public class BizSellOrderService {
@UserAction("'撤回销售订单'+#vo.id") @UserAction("'撤回销售订单'+#vo.id")
@Lock("#vo.id") @Lock("#vo.id")
@Tx @Tx
public Result withdraw(DocumentStatusUpdate vo, SysUser user) { public Result withdraw(DocumentStatusUpdate vo, UserVo user) {
String id = vo.getId(); String id = vo.getId();
String info = vo.getInfo(); String info = vo.getInfo();
@ -134,7 +135,7 @@ public class BizSellOrderService {
@UserAction("'通过销售订单'+#vo.id") @UserAction("'通过销售订单'+#vo.id")
@Lock("#vo.id") @Lock("#vo.id")
@Tx @Tx
public Result pass(DocumentStatusUpdate vo, SysUser user) { public Result pass(DocumentStatusUpdate vo, UserVo user) {
String id = vo.getId(); String id = vo.getId();
String info = vo.getInfo(); String info = vo.getInfo();
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
@ -162,7 +163,7 @@ public class BizSellOrderService {
@UserAction("'驳回销售订单'+#vo.id") @UserAction("'驳回销售订单'+#vo.id")
@Lock("#vo.id") @Lock("#vo.id")
@Tx @Tx
public Result reject(DocumentStatusUpdate vo, SysUser user) { public Result reject(DocumentStatusUpdate vo, UserVo user) {
String id = vo.getId(); String id = vo.getId();
String info = vo.getInfo(); String info = vo.getInfo();
@ -200,7 +201,7 @@ public class BizSellOrderService {
String err = checkStock(doc.getData()); String err = checkStock(doc.getData());
if (err != null) return Result.fail(err); if (err != null) return Result.fail(err);
String id = RedisUtil.getDocumentID("XSDD"); String id = DocumentUtil.getDocumentID("XSDD");
if (StringUtils.isEmpty(id)) return Result.fail("获取单号失败"); if (StringUtils.isEmpty(id)) return Result.fail("获取单号失败");
doc.setId(id); doc.setId(id);

@ -13,14 +13,12 @@ import com.toesbieya.my.mapper.BizSellOrderMapper;
import com.toesbieya.my.mapper.BizSellOutboundMapper; import com.toesbieya.my.mapper.BizSellOutboundMapper;
import com.toesbieya.my.mapper.BizStockMapper; import com.toesbieya.my.mapper.BizStockMapper;
import com.toesbieya.my.model.entity.*; 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.export.SellOutboundExport;
import com.toesbieya.my.model.vo.result.PageResult; import com.toesbieya.my.model.vo.result.PageResult;
import com.toesbieya.my.model.vo.search.SellOutboundSearch; import com.toesbieya.my.model.vo.search.SellOutboundSearch;
import com.toesbieya.my.model.vo.update.DocumentStatusUpdate; import com.toesbieya.my.model.vo.update.DocumentStatusUpdate;
import com.toesbieya.my.utils.ExcelUtil; import com.toesbieya.my.utils.*;
import com.toesbieya.my.utils.RedisUtil;
import com.toesbieya.my.utils.Result;
import com.toesbieya.my.utils.Util;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
@ -112,7 +110,7 @@ public class BizSellOutboundService {
@UserAction("'撤回销售出库单'+#vo.id") @UserAction("'撤回销售出库单'+#vo.id")
@Lock("#vo.id") @Lock("#vo.id")
@Tx @Tx
public Result withdraw(DocumentStatusUpdate vo, SysUser user) { public Result withdraw(DocumentStatusUpdate vo, UserVo user) {
String id = vo.getId(); String id = vo.getId();
String info = vo.getInfo(); String info = vo.getInfo();
@ -139,7 +137,7 @@ public class BizSellOutboundService {
@UserAction("'通过销售出库单'+#vo.id") @UserAction("'通过销售出库单'+#vo.id")
@Lock({"#vo.pid", "#vo.id"}) @Lock({"#vo.pid", "#vo.id"})
@Tx @Tx
public Result pass(DocumentStatusUpdate vo, SysUser user) { public Result pass(DocumentStatusUpdate vo, UserVo user) {
String id = vo.getId(); String id = vo.getId();
String info = vo.getInfo(); String info = vo.getInfo();
String pid = vo.getPid(); String pid = vo.getPid();
@ -202,7 +200,7 @@ public class BizSellOutboundService {
@UserAction("'驳回销售出库单'+#vo.id") @UserAction("'驳回销售出库单'+#vo.id")
@Lock("#vo.id") @Lock("#vo.id")
@Tx @Tx
public Result reject(DocumentStatusUpdate vo, SysUser user) { public Result reject(DocumentStatusUpdate vo, UserVo user) {
String id = vo.getId(); String id = vo.getId();
String info = vo.getInfo(); String info = vo.getInfo();
@ -240,7 +238,7 @@ public class BizSellOutboundService {
String err = check(doc.getPid(), doc.getData()); String err = check(doc.getPid(), doc.getData());
if (err != null) return Result.fail(err); if (err != null) return Result.fail(err);
String id = RedisUtil.getDocumentID("XSCK"); String id = DocumentUtil.getDocumentID("XSCK");
if (StringUtils.isEmpty(id)) return Result.fail("获取单号失败"); if (StringUtils.isEmpty(id)) return Result.fail("获取单号失败");
doc.setId(id); doc.setId(id);

@ -6,7 +6,7 @@ import com.toesbieya.my.constant.SocketConstant;
import com.toesbieya.my.mapper.MsgMapper; import com.toesbieya.my.mapper.MsgMapper;
import com.toesbieya.my.model.entity.Msg; import com.toesbieya.my.model.entity.Msg;
import com.toesbieya.my.model.entity.MsgState; 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.result.PageResult;
import com.toesbieya.my.model.vo.search.MsgPersonalSearch; import com.toesbieya.my.model.vo.search.MsgPersonalSearch;
import com.toesbieya.my.model.vo.search.MsgSearch; import com.toesbieya.my.model.vo.search.MsgSearch;
@ -83,12 +83,13 @@ public class MsgService {
return result; return result;
} }
public Result read(SysUser user, int id) { public Result read(UserVo user, int id) {
if (msgMapper.checkRead(id, user.getId())) { if (msgMapper.checkRead(id, user.getId())) {
return Result.success(); return Result.success();
} }
MsgState state = new MsgState(); MsgState state = new MsgState();
state.setMid(id); state.setMid(id);
state.setUid(user.getId()); state.setUid(user.getId());
state.setTime(System.currentTimeMillis()); state.setTime(System.currentTimeMillis());
@ -96,7 +97,7 @@ public class MsgService {
return Result.success(msgMapper.insertState(state)); return Result.success(msgMapper.insertState(state));
} }
public Result readAll(SysUser user) { public Result readAll(UserVo user) {
MsgPersonalSearch vo = new MsgPersonalSearch(); MsgPersonalSearch vo = new MsgPersonalSearch();
vo.setUid(user.getId()); vo.setUid(user.getId());
vo.setCtime(user.getCtime()); vo.setCtime(user.getCtime());

@ -9,7 +9,7 @@ import com.toesbieya.my.mapper.RecUserActionMapper;
import com.toesbieya.my.model.entity.RecAttachment; import com.toesbieya.my.model.entity.RecAttachment;
import com.toesbieya.my.model.entity.RecLoginHistory; import com.toesbieya.my.model.entity.RecLoginHistory;
import com.toesbieya.my.model.entity.RecUserAction; 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.result.PageResult;
import com.toesbieya.my.model.vo.search.LoginHistorySearch; import com.toesbieya.my.model.vo.search.LoginHistorySearch;
import com.toesbieya.my.model.vo.search.UserActionSearch; import com.toesbieya.my.model.vo.search.UserActionSearch;
@ -66,7 +66,7 @@ public class RecService {
} }
@Async("dbInsertExecutor") @Async("dbInsertExecutor")
public void insertLoginHistory(SysUser user, String ip, RecLoginHistoryEnum historyEnum) { public void insertLoginHistory(UserVo user, String ip, RecLoginHistoryEnum historyEnum) {
RecLoginHistory history = RecLoginHistory.builder() RecLoginHistory history = RecLoginHistory.builder()
.uid(user.getId()) .uid(user.getId())
.uname(user.getName()) .uname(user.getName())

@ -3,29 +3,17 @@ package com.toesbieya.my.service;
import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageHelper;
import com.toesbieya.my.annoation.Tx; import com.toesbieya.my.annoation.Tx;
import com.toesbieya.my.annoation.UserAction; 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.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.entity.SysUser;
import com.toesbieya.my.model.vo.UserVo;
import com.toesbieya.my.model.vo.result.PageResult; import com.toesbieya.my.model.vo.result.PageResult;
import com.toesbieya.my.model.vo.search.UserSearch; 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.module.SocketModule;
import com.toesbieya.my.utils.QiniuUtil;
import com.toesbieya.my.utils.Result; 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.stereotype.Service;
import org.springframework.util.DigestUtils; import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import javax.annotation.Resource; import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List; import java.util.List;
@Service @Service
@ -33,88 +21,16 @@ public class SysUserService {
private static final String DEFAULT_PWD = DigestUtils.md5DigestAsHex("123456".getBytes()); private static final String DEFAULT_PWD = DigestUtils.md5DigestAsHex("123456".getBytes());
@Resource @Resource
private SysUserMapper userMapper; 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<String, Object> userVo = new HashMap<>();
List<SysResource> resources;
HashMap<String, Integer> userResourcesUrlMap = new HashMap<>(); public PageResult<UserVo> search(UserSearch vo) {
PageHelper.startPage(vo.getPage(), vo.getPageSize());
HashSet<Integer> 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);
userMapper.add(user); List<UserVo> users = userMapper.search(vo);
return Result.success("注册成功");
}
public PageResult<SysUser> search(UserSearch vo) { for (UserVo user : users) {
PageHelper.startPage(vo.getPage(), vo.getPageSize());
List<SysUser> users = userMapper.search(vo);
for (SysUser user : users) {
user.setOnline(SocketModule.online(user.getId())); user.setOnline(SocketModule.online(user.getId()));
} }
return new PageResult<>(users); return new PageResult<>(users);
} }
@ -131,7 +47,7 @@ public class SysUserService {
return Result.success("添加成功"); return Result.success("添加成功");
} }
@UserAction @UserAction("'修改用户:'+#user.name")
public Result update(SysUser user) { public Result update(SysUser user) {
if (userMapper.isNameExist(user.getName(), user.getId())) { if (userMapper.isNameExist(user.getName(), user.getId())) {
return Result.fail("该用户名称已存在"); return Result.fail("该用户名称已存在");
@ -163,34 +79,4 @@ public class SysUserService {
int rows = userMapper.resetPwd(user.getId(), DEFAULT_PWD); int rows = userMapper.resetPwd(user.getId(), DEFAULT_PWD);
return rows > 0 ? Result.success() : Result.fail("重置失败,未匹配到用户"); 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)));
}
} }

@ -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<Long> 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);
}
}

@ -48,11 +48,11 @@ public class ExcelUtil {
int size = list.size(); int size = list.size();
if (size == 0) { if (size == 0) {
Util.responseJson(response, Result.fail("当前没有能导出的数据")); WebUtil.responseJson(response, Result.fail("当前没有能导出的数据"));
return; return;
} }
else if (size < 10000) { else if (size < 10000) {
Util.responseJson(response, Result.success(list)); WebUtil.responseJson(response, Result.success(list));
return; return;
} }

@ -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<DiskInfo> getDiskInfo() {
FileSystem fileSystem = SYSTEM_INFO.getOperatingSystem().getFileSystem();
OSFileStore[] fsArray = fileSystem.getFileStores();
List<DiskInfo> list = new ArrayList<>();
for (OSFileStore fs : fsArray) {
list.add(new DiskInfo(fs));
}
return list;
}
}

@ -5,24 +5,41 @@ import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration; import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region; import com.qiniu.storage.Region;
import com.qiniu.util.Auth; import com.qiniu.util.Auth;
import com.toesbieya.my.config.QiniuConfig;
import lombok.extern.slf4j.Slf4j; 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 @Slf4j
@Component
@DependsOn("redisUtil")
public class QiniuUtil { public class QiniuUtil {
private static final String ACCESS_KEY = (String) YmlUtil.get("qiniu.access-key"); private static QiniuConfig config;
private static final String SECRET_KEY = (String) YmlUtil.get("qiniu.secret-key"); private static Auth AUTH ;
private static final String BUCKET = (String) YmlUtil.get("qiniu.bucket"); private static BucketManager BUCKET_MANAGER;
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"); @Autowired
private static final Auth AUTH = Auth.create(ACCESS_KEY, SECRET_KEY); public QiniuUtil(QiniuConfig config) {
private static final BucketManager BUCKET_MANAGER = new BucketManager(AUTH, new Configuration(Region.huadong())); 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() { public static String getToken() {
String token = (String) RedisUtil.get(REDIS_CACHE_KEY); String token = (String) RedisUtil.get(config.getRedisCacheKey());
if (token == null) { if (token == null) {
token = AUTH.uploadToken(BUCKET); token = AUTH.uploadToken(config.getBucket());
RedisUtil.set(REDIS_CACHE_KEY, token, TOKEN_EXPIRES); RedisUtil.set(config.getRedisCacheKey(), token, config.getTokenExpire());
} }
return token; return token;
@ -30,7 +47,7 @@ public class QiniuUtil {
public static void delete(String key) { public static void delete(String key) {
try { try {
BUCKET_MANAGER.delete(BUCKET, key); BUCKET_MANAGER.delete(config.getBucket(), key);
} catch (QiniuException e) { } catch (QiniuException e) {
log.info("七牛云删除单个文件失败,{}", e.getMessage()); log.info("七牛云删除单个文件失败,{}", e.getMessage());
} }
@ -38,7 +55,7 @@ public class QiniuUtil {
public static void deleteBatch(String... key) { public static void deleteBatch(String... key) {
BucketManager.BatchOperations batchOperations = new BucketManager.BatchOperations(); BucketManager.BatchOperations batchOperations = new BucketManager.BatchOperations();
batchOperations.addDeleteOp(BUCKET, key); batchOperations.addDeleteOp(config.getBucket(), key);
try { try {
BUCKET_MANAGER.batch(batchOperations); BUCKET_MANAGER.batch(batchOperations);
} catch (QiniuException e) { } catch (QiniuException e) {

@ -1,36 +1,27 @@
package com.toesbieya.my.utils; package com.toesbieya.my.utils;
import com.alibaba.fastjson.JSONObject;
import com.google.common.io.ByteStreams; 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 lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.RedisTemplate; 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.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript; import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.io.Closeable;
import java.io.IOException; import java.io.IOException;
import java.time.format.DateTimeFormatter;
import java.util.*; import java.util.*;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@Component @Component
@Slf4j @Slf4j
public class RedisUtil { public class RedisUtil {
private static String GET_DOCUMENT_ID_SCRIPT = null;
private static String INCREMENT_AND_EXPIRE_SCRIPT = null; private static String INCREMENT_AND_EXPIRE_SCRIPT = null;
private static StringRedisTemplate stringRedisTemplate;
private static RedisTemplate<Object, Object> redisTemplate; private static RedisTemplate<Object, Object> redisTemplate;
static { static {
try { 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())); INCREMENT_AND_EXPIRE_SCRIPT = new String(ByteStreams.toByteArray(new ClassPathResource("/script/increase_and_expire.lua").getInputStream()));
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
@ -38,13 +29,12 @@ public class RedisUtil {
} }
@Autowired @Autowired
public RedisUtil(StringRedisTemplate stringRedisTemplate, RedisTemplate<Object, Object> redisTemplate) { public RedisUtil(RedisTemplate<Object, Object> redisTemplate) {
RedisUtil.stringRedisTemplate = stringRedisTemplate;
RedisUtil.redisTemplate = redisTemplate; RedisUtil.redisTemplate = redisTemplate;
} }
public static boolean exist(String key) { public static boolean exist(String key) {
Boolean result = stringRedisTemplate.hasKey(key); Boolean result = redisTemplate.hasKey(key);
return result != null && result; return result != null && result;
} }
@ -54,16 +44,8 @@ public class RedisUtil {
return result == null ? 0 : result; return result == null ? 0 : result;
} }
public static void del(String key) { public static void expireImmediately(String key) {
stringRedisTemplate.delete(key); redisTemplate.expire(key, 0L, TimeUnit.MILLISECONDS);
}
public static void expire(String key) {
stringRedisTemplate.expire(key, 0L, TimeUnit.MILLISECONDS);
}
public static Set<String> keys(String key) {
return stringRedisTemplate.keys(key + '*');
} }
public static Object get(String key) { public static Object get(String key) {
@ -90,32 +72,44 @@ public class RedisUtil {
redisTemplate.opsForHash().putAll(key, map); redisTemplate.opsForHash().putAll(key, map);
} }
public static String getDocumentID(String type) { public static <T> T execute(RedisScript<T> script, List<Object> keys, Object... args) {
if (!Arrays.asList(RedisModule.DOCUMENTS_TYPE).contains(type)) { return redisTemplate.execute(script, keys, args);
log.error("单据类型有误,【{}】不存在", type); }
return null;
}
RedisScript<Long> redisScript = new DefaultRedisScript<>(GET_DOCUMENT_ID_SCRIPT, Long.class); public static RedisTemplate<Object, Object> getRedisTemplate() {
Long result = stringRedisTemplate.execute( return redisTemplate;
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 SysUser getUserByRedisKey(String key) { public static class Locker implements Closeable {
JSONObject o = (JSONObject) redisTemplate.opsForHash().get(key, "sessionAttr:" + SessionConstant.USER_KEY); private final String key;
if (o == null) { private final String value;
return null; 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() { public boolean lock() {
return stringRedisTemplate; String LOCK_LUA_SCRIPT = "return redis.call('set',KEYS[1],ARGV[1],'EX',ARGV[2],'NX')";
RedisScript<Boolean> 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<Boolean> 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);
}
}
} }
} }

@ -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);
}
}

@ -1,23 +1,26 @@
package com.toesbieya.my.utils; package com.toesbieya.my.utils;
import com.toesbieya.my.model.entity.RecUserAction; 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; import javax.servlet.http.HttpServletRequest;
public class ThreadUtil { public class ThreadUtil {
private static final ThreadLocal<RecUserAction> THREAD_LOCAL_USER_ACTION = new ThreadLocal<>(); private static final ThreadLocal<RecUserAction> THREAD_LOCAL_USER_ACTION = new ThreadLocal<>();
private static final ThreadLocal<SysUser> THREAD_LOCAL_USER = new ThreadLocal<>(); private static final ThreadLocal<UserVo> THREAD_LOCAL_USER = new ThreadLocal<>();
public static void quicklySetAction(HttpServletRequest request) { public static void quicklySetAction(HttpServletRequest request) {
SysUser user = getUser(); UserVo user = SessionUtil.get(request);
if (null == user) return; if (null == user) return;
RecUserAction userAction = RecUserAction.builder() RecUserAction userAction = RecUserAction.builder()
.uid(user.getId()) .uid(user.getId())
.uname(user.getName()) .uname(user.getName())
.ip(IpUtil.getIp(request)) .ip(IpUtil.getIp(request))
.url(request.getServletPath()) .url(request.getServletPath())
.build(); .build();
setAction(userAction); setAction(userAction);
} }
@ -29,11 +32,11 @@ public class ThreadUtil {
THREAD_LOCAL_USER_ACTION.set(action); THREAD_LOCAL_USER_ACTION.set(action);
} }
public static SysUser getUser() { public static UserVo getUser() {
return THREAD_LOCAL_USER.get(); return THREAD_LOCAL_USER.get();
} }
public static void setUser(SysUser user) { public static void setUser(UserVo user) {
THREAD_LOCAL_USER.set(user); THREAD_LOCAL_USER.set(user);
} }

@ -1,23 +1,16 @@
package com.toesbieya.my.utils; 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.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 javax.validation.constraints.NotNull;
import java.io.IOException;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.io.StringWriter; import java.io.StringWriter;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.text.DecimalFormat; 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.function.Predicate;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@ -28,7 +21,9 @@ public class Util {
} }
public static List<Integer> str2List(@NotNull String string) { public static List<Integer> str2List(@NotNull String string) {
if (StringUtils.isEmpty(string)) return new ArrayList<>(0); if (StringUtils.isEmpty(string)) {
return Collections.emptyList();
}
return Arrays.stream(string.split(",")) return Arrays.stream(string.split(","))
.map(i -> Integer.parseInt(i.trim())) .map(i -> Integer.parseInt(i.trim()))
.collect(Collectors.toList()); .collect(Collectors.toList());
@ -46,13 +41,6 @@ public class Util {
return o == null ? defaultValue : o; 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) { public static boolean isInteger(String str) {
Pattern pattern = Pattern.compile("^[-+]?[\\d]*$"); Pattern pattern = Pattern.compile("^[-+]?[\\d]*$");
return pattern.matcher(str).matches(); return pattern.matcher(str).matches();
@ -66,24 +54,6 @@ public class Util {
return stringWriter.toString(); 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) { public static String formatByte(long byteNumber) {
//换算单位 //换算单位
double FORMAT = 1024.0; double FORMAT = 1024.0;
@ -104,9 +74,31 @@ public class Util {
} }
public static <T> T find(Iterable<T> list, Predicate<T> predicate) { public static <T> T find(Iterable<T> list, Predicate<T> predicate) {
if (list == null) return null;
for (T t : list) { for (T t : list) {
if (predicate.test(t)) return t; if (predicate.test(t)) return t;
} }
return null; return null;
} }
public static <T> int findIndex(Iterable<T> list, Predicate<T> predicate) {
int i = -1;
if (list == null) return i;
for (T t : list) {
i++;
if (predicate.test(t)) return i;
}
return -1;
}
public static <T> boolean some(Iterable<T> list, Predicate<T> predicate) {
int index = findIndex(list, predicate);
return index > -1;
}
} }

@ -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();
}
}

@ -37,24 +37,16 @@
where id = #{id} where id = #{id}
and admin = 0 and admin = 0
</delete> </delete>
<select id="getById" resultType="com.toesbieya.my.model.entity.SysUser">
select a.*,
if(a.admin = 1, '超级管理员', b.name) role_name
from sys_user a
left join sys_role b on a.role = b.id
where a.id = #{id}
</select>
<select id="getByNameAndPwd" resultType="com.toesbieya.my.model.entity.SysUser"> <select id="getByNameAndPwd" resultType="com.toesbieya.my.model.entity.SysUser">
select a.*, select a.*,b.name role_name
if(a.admin = 1, '超级管理员', b.name) role_name
from sys_user a from sys_user a
left join sys_role b on a.role = b.id left join sys_role b on a.role = b.id
where a.name = #{name} where a.name = #{name}
and a.pwd = #{pwd} and a.pwd = #{pwd}
</select> </select>
<select id="search" resultType="com.toesbieya.my.model.entity.SysUser" <select id="search" resultType="com.toesbieya.my.model.vo.UserVo"
parameterType="com.toesbieya.my.model.vo.search.UserSearch"> parameterType="com.toesbieya.my.model.vo.search.UserSearch">
select a.id, a.name, a.avatar, a.status, a.role, a.admin, a.ctime,if(a.admin = 1, '超级管理员', b.name) role_name select a.id, a.name, a.avatar, a.status, a.role, a.admin, a.ctime,b.name role_name
from sys_user a from sys_user a
left join sys_role b on a.role=b.id left join sys_role b on a.role=b.id
where a.admin=0 where a.admin=0

Loading…
Cancel
Save