♻️ Refactoring code. close #I50BA0 后台报错使用国际化文件定义

This commit is contained in:
qraddx 2022-03-30 11:12:56 +08:00
parent af31ba4fe7
commit 1ec839c959
9 changed files with 93 additions and 13 deletions

View File

@ -36,7 +36,7 @@ CREATE TABLE `config_info` (
-- Records of config_info -- Records of config_info
-- ---------------------------- -- ----------------------------
BEGIN; BEGIN;
INSERT INTO `config_info` VALUES (1, 'application-dev.yml', 'DEFAULT_GROUP', '# 加解密根密码\njasypt:\n encryptor:\n password: pig #根密码\n\n# Spring 相关\n\nspring:\n mvc:\n pathmatch:\n matching-strategy: ant_path_matcher\n redis:\n host: pig-redis\n cloud:\n sentinel:\n eager: true\n transport:\n dashboard: pig-sentinel:5003\n\n# 暴露监控端点\nmanagement:\n endpoints:\n web:\n exposure:\n include: \"*\" \n endpoint:\n health:\n show-details: ALWAYS\n\n\n# feign 配置\nfeign:\n sentinel:\n enabled: true\n okhttp:\n enabled: true\n httpclient:\n enabled: false\n client:\n config:\n default:\n connectTimeout: 10000\n readTimeout: 10000\n compression:\n request:\n enabled: true\n response:\n enabled: true\n\n# mybaits-plus配置\nmybatis-plus:\n mapper-locations: classpath:/mapper/*Mapper.xml\n global-config:\n banner: false\n db-config:\n id-type: auto\n table-underline: true\n logic-delete-value: 1\n logic-not-delete-value: 0\n configuration:\n map-underscore-to-camel-case: true\n\n# spring security 配置\nsecurity:\n oauth2:\n resource:\n loadBalanced: true\n token-info-uri: http://pig-auth/oauth/check_token\n # 通用放行URL服务个性化请在对应配置文件覆盖\n ignore:\n urls:\n - /v3/api-docs\n - /v2/api-docs\n - /actuator/**\n - /user/registerUser\n# swagger 配置\nswagger:\n enabled: true\n title: Pig Swagger API\n gateway: http://${GATEWAY_HOST:pig-gateway}:${GATEWAY-PORT:9999}\n token-url: ${swagger.gateway}/auth/oauth/token\n services:\n pig-upms-biz: admin\n pig-codegen: gen', 'fe841b616618e0d7dfdfbb78ff08dc93', '2019-11-29 16:31:20', '2022-03-27 23:19:22', '', '0:0:0:0:0:0:0:1', '', '', '', '', '', 'yaml', ''); INSERT INTO `config_info` VALUES (1, 'application-dev.yml', 'DEFAULT_GROUP', '# 加解密根密码\njasypt:\n encryptor:\n password: pig #根密码\n\n# Spring 相关\n\nspring:\n mvc:\n pathmatch:\n matching-strategy: ant_path_matcher\n redis:\n host: pig-redis\n cloud:\n sentinel:\n eager: true\n transport:\n dashboard: pig-sentinel:5003\n\n# 暴露监控端点\nmanagement:\n endpoints:\n web:\n exposure:\n include: \"*\" \n endpoint:\n health:\n show-details: ALWAYS\n\n\n# feign 配置\nfeign:\n sentinel:\n enabled: true\n okhttp:\n enabled: true\n httpclient:\n enabled: false\n client:\n config:\n default:\n connectTimeout: 10000\n readTimeout: 10000\n compression:\n request:\n enabled: true\n response:\n enabled: true\n\n# mybaits-plus配置\nmybatis-plus:\n mapper-locations: classpath:/mapper/*Mapper.xml\n global-config:\n banner: false\n db-config:\n id-type: auto\n table-underline: true\n logic-delete-value: 1\n logic-not-delete-value: 0\n configuration:\n map-underscore-to-camel-case: true\n\n# spring security 配置\nsecurity:\n oauth2:\n resource:\n loadBalanced: true\n token-info-uri: http://pig-auth/oauth/check_token\n # 通用放行URL服务个性化请在对应配置文件覆盖\n ignore:\n urls:\n - /v3/api-docs\n - /actuator/**\n\n# swagger 配置\nswagger:\n enabled: true\n title: Pig Swagger API\n gateway: http://${GATEWAY_HOST:pig-gateway}:${GATEWAY-PORT:9999}\n token-url: ${swagger.gateway}/auth/oauth/token\n services:\n pig-upms-biz: admin\n pig-codegen: gen', '8d9ffc03cef9e316905d4f86d1914e6b', '2019-11-29 16:31:20', '2022-03-30 10:48:26', 'nacos', '127.0.0.1', '', '', '', '', '', 'yaml', '');
INSERT INTO `config_info` VALUES (2, 'pig-auth-dev.yml', 'DEFAULT_GROUP', '# 数据源\nspring:\n datasource:\n type: com.zaxxer.hikari.HikariDataSource\n driver-class-name: com.mysql.cj.jdbc.Driver\n username: root\n password: root\n url: jdbc:mysql://pig-mysql:3306/pig?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true&allowPublicKeyRetrieval=true\n freemarker:\n allow-request-override: false\n allow-session-override: false\n cache: true\n charset: UTF-8\n check-template-location: true\n content-type: text/html\n enabled: true\n expose-request-attributes: false\n expose-session-attributes: false\n expose-spring-macro-helpers: true\n prefer-file-system-access: true\n suffix: .ftl\n template-loader-path: classpath:/templates/', '58b1b48a2888f49e667864be32edf9c1', '2019-11-29 16:31:48', '2020-01-01 18:30:58', NULL, '127.0.0.1', '', '', '认证中心配置', 'null', 'null', 'yaml', 'null'); INSERT INTO `config_info` VALUES (2, 'pig-auth-dev.yml', 'DEFAULT_GROUP', '# 数据源\nspring:\n datasource:\n type: com.zaxxer.hikari.HikariDataSource\n driver-class-name: com.mysql.cj.jdbc.Driver\n username: root\n password: root\n url: jdbc:mysql://pig-mysql:3306/pig?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true&allowPublicKeyRetrieval=true\n freemarker:\n allow-request-override: false\n allow-session-override: false\n cache: true\n charset: UTF-8\n check-template-location: true\n content-type: text/html\n enabled: true\n expose-request-attributes: false\n expose-session-attributes: false\n expose-spring-macro-helpers: true\n prefer-file-system-access: true\n suffix: .ftl\n template-loader-path: classpath:/templates/', '58b1b48a2888f49e667864be32edf9c1', '2019-11-29 16:31:48', '2020-01-01 18:30:58', NULL, '127.0.0.1', '', '', '认证中心配置', 'null', 'null', 'yaml', 'null');
INSERT INTO `config_info` VALUES (3, 'pig-codegen-dev.yml', 'DEFAULT_GROUP', '## spring security 配置\nsecurity:\n oauth2:\n client:\n client-id: ENC(27v1agvAug87ANOVnbKdsw==)\n client-secret: ENC(VbnkopxrwgbFVKp+UxJ2pg==)\n scope: server\n\n# 数据源配置\nspring:\n datasource:\n type: com.zaxxer.hikari.HikariDataSource\n driver-class-name: com.mysql.cj.jdbc.Driver\n username: root\n password: root\n url: jdbc:mysql://pig-mysql:3306/pig_codegen?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true&allowPublicKeyRetrieval=true\n resources:\n static-locations: classpath:/static/,classpath:/views/\n\n# 直接放行URL\nignore:\n urls:\n - /v2/api-docs\n - /actuator/**\n', 'abc702838b34d11b46e96143ccd9f367', '2019-11-29 16:32:12', '2019-11-29 16:32:12', NULL, '127.0.0.1', '', '', '代码生成配置', NULL, NULL, 'yaml', NULL); INSERT INTO `config_info` VALUES (3, 'pig-codegen-dev.yml', 'DEFAULT_GROUP', '## spring security 配置\nsecurity:\n oauth2:\n client:\n client-id: ENC(27v1agvAug87ANOVnbKdsw==)\n client-secret: ENC(VbnkopxrwgbFVKp+UxJ2pg==)\n scope: server\n\n# 数据源配置\nspring:\n datasource:\n type: com.zaxxer.hikari.HikariDataSource\n driver-class-name: com.mysql.cj.jdbc.Driver\n username: root\n password: root\n url: jdbc:mysql://pig-mysql:3306/pig_codegen?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true&allowPublicKeyRetrieval=true\n resources:\n static-locations: classpath:/static/,classpath:/views/\n\n# 直接放行URL\nignore:\n urls:\n - /v2/api-docs\n - /actuator/**\n', 'abc702838b34d11b46e96143ccd9f367', '2019-11-29 16:32:12', '2019-11-29 16:32:12', NULL, '127.0.0.1', '', '', '代码生成配置', NULL, NULL, 'yaml', NULL);
INSERT INTO `config_info` VALUES (4, 'pig-gateway-dev.yml', 'DEFAULT_GROUP', 'spring:\n cloud:\n gateway:\n locator:\n enabled: true\n routes:\n # 认证中心\n - id: pig-auth\n uri: lb://pig-auth\n predicates:\n - Path=/auth/**\n filters:\n # 验证码处理\n - ValidateCodeGatewayFilter\n # 前端密码解密\n - PasswordDecoderFilter\n #UPMS 模块\n - id: pig-upms-biz\n uri: lb://pig-upms-biz\n predicates:\n - Path=/admin/**\n filters:\n # 限流配置\n - name: RequestRateLimiter\n args:\n key-resolver: \'#{@remoteAddrKeyResolver}\'\n redis-rate-limiter.replenishRate: 100\n redis-rate-limiter.burstCapacity: 200\n # 代码生成模块\n - id: pig-codegen\n uri: lb://pig-codegen\n predicates:\n - Path=/gen/**\n # demo模块\n - id: pig-demo\n uri: lb://demo-biz\n predicates:\n - Path=/demo/**\n - id: openapi\n uri: http://localhost:${server.port}\n predicates:\n - Path=/v3/api-docs/**\n filters:\n - RewritePath=/v3/api-docs/(?<path>.*), /$\\{path}/v3/api-docs\n\ngateway:\n encode-key: \'thanks,pig4cloud\'\n ignore-clients:\n - test', 'dbf00e83f80de7f011d244ea1ce5686e', '2019-11-29 16:32:42', '2022-03-27 23:19:33', '', '0:0:0:0:0:0:0:1', '', '', '网关配置', '', '', 'yaml', ''); INSERT INTO `config_info` VALUES (4, 'pig-gateway-dev.yml', 'DEFAULT_GROUP', 'spring:\n cloud:\n gateway:\n locator:\n enabled: true\n routes:\n # 认证中心\n - id: pig-auth\n uri: lb://pig-auth\n predicates:\n - Path=/auth/**\n filters:\n # 验证码处理\n - ValidateCodeGatewayFilter\n # 前端密码解密\n - PasswordDecoderFilter\n #UPMS 模块\n - id: pig-upms-biz\n uri: lb://pig-upms-biz\n predicates:\n - Path=/admin/**\n filters:\n # 限流配置\n - name: RequestRateLimiter\n args:\n key-resolver: \'#{@remoteAddrKeyResolver}\'\n redis-rate-limiter.replenishRate: 100\n redis-rate-limiter.burstCapacity: 200\n # 代码生成模块\n - id: pig-codegen\n uri: lb://pig-codegen\n predicates:\n - Path=/gen/**\n # demo模块\n - id: pig-demo\n uri: lb://demo-biz\n predicates:\n - Path=/demo/**\n - id: openapi\n uri: http://localhost:${server.port}\n predicates:\n - Path=/v3/api-docs/**\n filters:\n - RewritePath=/v3/api-docs/(?<path>.*), /$\\{path}/v3/api-docs\n\ngateway:\n encode-key: \'thanks,pig4cloud\'\n ignore-clients:\n - test', 'dbf00e83f80de7f011d244ea1ce5686e', '2019-11-29 16:32:42', '2022-03-27 23:19:33', '', '0:0:0:0:0:0:0:1', '', '', '网关配置', '', '', 'yaml', '');

View File

@ -18,13 +18,14 @@ package com.pig4cloud.pig.common.core.config;
import cn.hutool.core.date.DatePattern; import cn.hutool.core.date.DatePattern;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.format.FormatterRegistry; import org.springframework.format.FormatterRegistry;
import org.springframework.format.datetime.standard.DateTimeFormatterRegistrar; import org.springframework.format.datetime.standard.DateTimeFormatterRegistrar;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.time.format.DateTimeFormatter;
import static org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication.Type.SERVLET; import static org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication.Type.SERVLET;
/** /**
@ -55,4 +56,15 @@ public class WebMvcConfiguration implements WebMvcConfigurer {
registrar.registerFormatters(registry); registrar.registerFormatters(registry);
} }
/**
* 系统国际化文件配置
* @return MessageSource
*/
@Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename("classpath:i18n/messages");
return messageSource;
}
} }

View File

@ -0,0 +1,21 @@
package com.pig4cloud.pig.common.core.exception;
/**
* 错误编码
*
* @author lengleng
* @date 2022/3/30
*/
public interface ErrorCodes {
/**
* 系统编码错误
*/
String SYS_PARAM_CONFIG_ERROR = "sys.param.config.error";
/**
* 用户已存在
*/
String SYS_USER_USERNAME_EXISTING = "sys.user.username.existing";
}

View File

@ -0,0 +1,38 @@
package com.pig4cloud.pig.common.core.util;
import cn.hutool.extra.spring.SpringUtil;
import lombok.experimental.UtilityClass;
import org.springframework.context.MessageSource;
import java.util.Locale;
/**
* i18n 工具类
*
* @author lengleng
* @date 2022/3/30
*/
@UtilityClass
public class MsgUtils {
/**
* 通过code 获取中文错误信息
* @param code
* @return
*/
public String getMessage(String code) {
MessageSource messageSource = SpringUtil.getBean("messageSource");
return messageSource.getMessage(code, null, Locale.CHINA);
}
/**
* 通过code 和参数获取中文错误信息
* @param code
* @return
*/
public String getMessage(String code, Object... objects) {
MessageSource messageSource = SpringUtil.getBean("messageSource");
return messageSource.getMessage(code, objects, Locale.CHINA);
}
}

View File

@ -0,0 +1,2 @@
sys.user.username.existing={0} \u7528\u6237\u540D\u5DF2\u5B58\u5728
sys.param.config.error={0} \u7CFB\u7EDF\u53C2\u6570\u914D\u7F6E\u9519\u8BEF

View File

@ -26,7 +26,7 @@ import static org.springframework.boot.autoconfigure.condition.ConditionalOnWebA
/** /**
* @author lengleng * @author lengleng
* @date 2019-06-24 * @date 2022年01月06日
* <p> * <p>
* 注入自定义错误处理 * 注入自定义错误处理
*/ */
@ -34,7 +34,7 @@ import static org.springframework.boot.autoconfigure.condition.ConditionalOnWebA
public class PigSecurityMessageSourceConfiguration implements WebMvcConfigurer { public class PigSecurityMessageSourceConfiguration implements WebMvcConfigurer {
@Bean @Bean
public MessageSource messageSource() { public MessageSource securityMessageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.addBasenames("classpath:org/springframework/security/messages"); messageSource.addBasenames("classpath:org/springframework/security/messages");
return messageSource; return messageSource;

View File

@ -221,10 +221,11 @@ public class UserController {
* @param userDto 用户信息 * @param userDto 用户信息
* @return success/false * @return success/false
*/ */
@Inner(value = false)
@SysLog("注册用户") @SysLog("注册用户")
@PostMapping("/registerUser") @PostMapping("/registerUser")
public R<Boolean> registerUser(@RequestBody UserDTO userDto) { public R<Boolean> registerUser(@RequestBody UserDTO userDto) {
return R.ok(userService.registerUser(userDto)); return userService.registerUser(userDto);
} }
} }

View File

@ -120,6 +120,6 @@ public interface SysUserService extends IService<SysUser> {
* @param userDto 用户信息 * @param userDto 用户信息
* @return success/false * @return success/false
*/ */
Boolean registerUser(UserDTO userDto); R<Boolean> registerUser(UserDTO userDto);
} }

View File

@ -18,7 +18,6 @@ package com.pig4cloud.pig.admin.service.impl;
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil; import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.core.toolkit.Wrappers;
@ -36,6 +35,8 @@ import com.pig4cloud.pig.admin.service.SysUserService;
import com.pig4cloud.pig.common.core.constant.CacheConstants; import com.pig4cloud.pig.common.core.constant.CacheConstants;
import com.pig4cloud.pig.common.core.constant.CommonConstants; import com.pig4cloud.pig.common.core.constant.CommonConstants;
import com.pig4cloud.pig.common.core.constant.enums.MenuTypeEnum; import com.pig4cloud.pig.common.core.constant.enums.MenuTypeEnum;
import com.pig4cloud.pig.common.core.exception.ErrorCodes;
import com.pig4cloud.pig.common.core.util.MsgUtils;
import com.pig4cloud.pig.common.core.util.R; import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.plugin.excel.vo.ErrorMessage; import com.pig4cloud.plugin.excel.vo.ErrorMessage;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
@ -364,20 +365,25 @@ public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> impl
* @return success/false * @return success/false
*/ */
@Override @Override
public Boolean registerUser(UserDTO userDto) { public R<Boolean> registerUser(UserDTO userDto) {
// 判断用户名是否存在 // 判断用户名是否存在
SysUser sysUser = this.getOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUsername, userDto.getUsername())); SysUser sysUser = this.getOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUsername, userDto.getUsername()));
Assert.isNull(sysUser, "用户名存在!"); if (sysUser != null) {
return R.failed(MsgUtils.getMessage(ErrorCodes.SYS_USER_USERNAME_EXISTING, userDto.getUsername()));
}
// 获取默认角色编码 // 获取默认角色编码
String defaultRole = ParamResolver.getStr("REGISTER_DEFAULT_ROLE"); String defaultRole = ParamResolver.getStr("USER_DEFAULT_ROLE");
// 默认角色 // 默认角色
SysRole sysRole = sysRoleMapper SysRole sysRole = sysRoleMapper
.selectOne(Wrappers.<SysRole>lambdaQuery().eq(SysRole::getRoleCode, defaultRole)); .selectOne(Wrappers.<SysRole>lambdaQuery().eq(SysRole::getRoleCode, defaultRole));
Assert.isTrue(ObjectUtil.isNotEmpty(sysRole), "系统参数配置错误!");
if (sysRole == null) {
return R.failed(MsgUtils.getMessage(ErrorCodes.SYS_PARAM_CONFIG_ERROR, "USER_DEFAULT_ROLE"));
}
userDto.setRole(Collections.singletonList(sysRole.getRoleId())); userDto.setRole(Collections.singletonList(sysRole.getRoleId()));
return saveUser(userDto); return R.ok(saveUser(userDto));
} }
} }