初始化工程

dev
张平 2023-12-07 15:35:35 +08:00
parent bcb104e713
commit 78430643d3
23 changed files with 1358 additions and 0 deletions

244
pom.xml 100644
View File

@ -0,0 +1,244 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.jinhaiqimeng</groupId>
<artifactId>sysManageMicroservice</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>sysManageMicroservice</name>
<description>系统管理中台</description>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-boot.version>2.6.13</spring-boot.version>
<spring-cloud.version>2021.0.5</spring-cloud.version>
<spring-cloud-alibaba.version>2021.0.5.0</spring-cloud-alibaba.version>
<!-- mybatis-puls -->
<mybatis-plus.version>3.3.1.tmp</mybatis-plus.version>
<mybatis-generator.version>3.3.1.tmp</mybatis-generator.version>
<!-- hutool -->
<hutool.version>5.3.9</hutool.version>
<!-- swagger -->
<swagger.version>3.0.0</swagger.version>
<!-- mybatis -->
<mybatis.version>2.2.2</mybatis.version>
<!-- okhttp-->
<okhttp.version>11.10</okhttp.version>
<!-- fastjson-->
<fastjson.version>1.2.83</fastjson.version>
<!-- openfeign-->
<openfeign.version>2.2.6.RELEASE</openfeign.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- springcloud alibaba sentinel -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!-- <dependency>-->
<!-- <groupId>org.springframework.boot</groupId>-->
<!-- <artifactId>spring-boot-starter-data-redis</artifactId>-->
<!-- </dependency>-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>${openfeign.version}</version>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-okhttp</artifactId>
<version>${okhttp.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- alibaba dataSource -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.22</version>
</dependency>
<!-- MyBatis-Plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatis-plus.version}</version>
</dependency>
<!-- freemarker 模板引擎 -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
</dependency>
<!-- MyBatis-Plus 自动代码生成器 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>${mybatis-generator.version}</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>${hutool.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>${swagger.version}</version>
</dependency>
<!-- knife4j 3.0.2 相关依赖 -->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>3.0.2</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
<!-- fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>${spring-cloud-alibaba.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<repositories>
<repository>
<id>nexus</id>
<name>Nexus Repository</name>
<url>http://nexus.derunht.cn/repository/maven-public/</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
<!-- 私服仓库配置:从私服下载-->
<pluginRepositories>
<pluginRepository>
<id>nexus</id>
<name>Nexus Plugin Repository</name>
<url>http://nexus.derunht.cn/repository/maven-public/</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>1.4.2.RELEASE</version>
<configuration>
<!-- ⭐️设定启动类 -->
<mainClass>com.jinhaiqimeng.sysManageMicroservice.SysManageMicroserviceApplication</mainClass>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.3</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,13 @@
package com.jinhaiqimeng.sysManageMicroservice;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
public class ServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(SysManageMicroserviceApplication.class);
}
}

View File

@ -0,0 +1,17 @@
package com.jinhaiqimeng.sysManageMicroservice;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
@MapperScan(basePackages ="com.jinhaiqimeng.sysManageMicroservice.web.dao")
@EnableFeignClients(basePackages= "com.jinhaiqimeng.sysManageMicroservice.feign")
@SpringBootApplication
public class SysManageMicroserviceApplication {
public static void main(String[] args) {
SpringApplication.run(SysManageMicroserviceApplication.class, args);
}
}

View File

@ -0,0 +1,18 @@
package com.jinhaiqimeng.sysManageMicroservice.config;
import feign.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Feign
*/
@Configuration
public class FeignConfiguration {
@Bean
Logger.Level feignLevel() {
return Logger.Level.BASIC;
}
}

View File

@ -0,0 +1,39 @@
package com.jinhaiqimeng.sysManageMicroservice.config;
import feign.Feign;
import okhttp3.ConnectionPool;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.cloud.openfeign.FeignAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.TimeUnit;
/**
* @ClassName OpenFeignInterfaceConfiguration
* @Description OpenFeignConfig
* @Author chaixueteng
* @Date 2020/3/10 9:46
*/
@Configuration
@ConditionalOnClass(Feign.class)
@AutoConfigureBefore(FeignAutoConfiguration.class)
public class FeignOkHttpConfig {
@Bean
public okhttp3.OkHttpClient okHttpClient(){
return new okhttp3.OkHttpClient.Builder()
//设置连接超时
.connectTimeout(15, TimeUnit.SECONDS)
//设置读超时
.readTimeout(15, TimeUnit.SECONDS)
//是否自动重连
.retryOnConnectionFailure(true)
// 最大连接数、连接存活时间、存活时间单位(分钟)
.connectionPool(new ConnectionPool(200, 5, TimeUnit.MINUTES))
//构建OkHttpClient对象
.build();
}
}

View File

@ -0,0 +1,27 @@
package com.jinhaiqimeng.sysManageMicroservice.config;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.optimize.JsqlParserCountOptimize;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* @ClassName MyBatisPlusConfig
* @Description mybatisPlus
* @Author chaixueteng
* @Date 2020/3/11 10:33
*/
@Configuration
@EnableTransactionManagement
public class MyBatisPlusConfig {
/**
*
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
return new PaginationInterceptor();
}
}

View File

@ -0,0 +1,145 @@
package com.jinhaiqimeng.sysManageMicroservice.config;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
* @ClassName MybatisGenerator
* @Description mybatis
* @Author chaixueteng
* @Date 2020/3/11 10:34
*/
public class MybatisGenerator {
private static final String MYSQL_URL ="jdbc:mysql://120.46.194.248:13306/jinhaiqimengdb?useSSL=false";
private static final String MYSQL_DRIVE ="com.mysql.jdbc.Driver";
private static final String MYSQL_U ="orgMicroservice_user";
private static final String MYSQL_P ="!XkCEn#PWFcPq$hy";
/**
* <p>
*
* </p>
*/
@SuppressWarnings("resource")
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("请输入" + tip + "");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotEmpty(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "");
}
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
final String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor("cxj");
gc.setOpen(false);
gc.setServiceName("%sService");// service 命名方式
gc.setServiceImplName("%sServiceImpl");// service impl 命名方式
// 自定义文件命名,注意 %s 会自动填充表实体属性!
gc.setMapperName("%sDao");
gc.setXmlName("%sDao");
gc.setFileOverride(true);
gc.setActiveRecord(true);
gc.setEnableCache(false);// XML 二级缓存
gc.setBaseResultMap(true);// XML ResultMap
gc.setBaseColumnList(true);// XML columList
gc.setIdType(IdType.ASSIGN_ID);
gc.setSwagger2(true);
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl(MYSQL_URL);
// dsc.setSchemaName("public");
dsc.setDriverName(MYSQL_DRIVE);
dsc.setUsername(MYSQL_U);
dsc.setPassword(MYSQL_P);
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
//pc.setModuleName(scanner("模块名"));
pc.setParent("com.jinhaiqimeng.orgMicroservice.web");
pc.setEntity("entity");
pc.setService("service");
pc.setServiceImpl("service.impl");
pc.setController("controller");// 设置控制器包名
pc.setMapper("dao");
mpg.setPackageInfo(pc);
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {}
};
// 如果模板引擎是 freemarker
String templatePath = "/templates/mapper.xml.ftl";
// 自定义输出配置
List<FileOutConfig> focList = new ArrayList();
// 自定义配置会被优先输出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名
return projectPath + "/src/main/resources/mapping/"
+ tableInfo.getEntityName() + "Dao" + StringPool.DOT_XML;
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
//生成时 添加字段注解,解决数据库字段与实体类不一致问题 比如 mysql f_id pojoid
strategy.entityTableFieldAnnotationEnable(true);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setRestControllerStyle(true);
strategy.setInclude(scanner("表名"));
strategy.setControllerMappingHyphenStyle(true);
strategy.setEntityLombokModel(true);
strategy.setTablePrefix("t_org_microservice");
strategy.setFieldPrefix("f_");
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();;
}
}

View File

@ -0,0 +1,40 @@
package com.jinhaiqimeng.sysManageMicroservice.config;
import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
@Configuration
@EnableOpenApi
@EnableKnife4j
public class SwaggerConfig {
@Bean
Docket docket(){
// 设置 swagger的版本
return new Docket(DocumentationType.OAS_30)
// 选择生成接口文档
.select()
// 包所在的路径
.apis(RequestHandlerSelectors.basePackage("com.jinhaiqimeng.sysManageMicroservice.web.controller"))
// 当前包下所有接口都生成
.paths(PathSelectors.any())
.build()
// 接口文档初始化,也就是设置接口文档的详细信息,
.apiInfo(
new ApiInfoBuilder()
.description("系统管理中台接口文档")
.version("v1.0")
.title("API 测试文档")
.license("Apache 2.0")
.licenseUrl("http://www.apache.org/licenses/LICENSE-2.0")
.build()
);
}
}

View File

@ -0,0 +1,53 @@
package com.jinhaiqimeng.sysManageMicroservice.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ThreadPoolExecutor;
/**
* @ClassName ThreadPoolTaskConfig
* @Description 线
* @Author chaixueteng
* @Date 2020/3/14 14:41
*/
@Configuration
@EnableAsync
public class ThreadPoolTaskConfig {
/**
* 线线线0线
* 线线corePoolSize
* 线线maxPoolSize使
*/
/** 核心线程数(默认线程数) */
private static final int corePoolSize = 20;
/** 最大线程数 */
private static final int maxPoolSize = 100;
/** 允许线程空闲时间(单位:默认为秒) */
private static final int keepAliveTime = 10;
/** 缓冲队列大小 */
private static final int queueCapacity = 200;
/** 线程池名前缀 */
private static final String threadNamePrefix = "Async-Service-";
@Bean("taskExecutor") // bean的名称默认为首字母小写的方法名
public ThreadPoolTaskExecutor taskExecutor(){
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(corePoolSize);
executor.setMaxPoolSize(maxPoolSize);
executor.setQueueCapacity(queueCapacity);
executor.setKeepAliveSeconds(keepAliveTime);
executor.setThreadNamePrefix(threadNamePrefix);
// 线程池对拒绝任务的处理策略
// CallerRunsPolicy由调用线程提交任务的线程处理该任务
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
// 初始化
executor.initialize();
return executor;
}
}

View File

@ -0,0 +1,35 @@
package com.jinhaiqimeng.sysManageMicroservice.exception;
/**
*
* @author chaixueteng
*/
public class CommonException extends RuntimeException {
private int errorCode;
private String msg;
public CommonException(int errorCode, String msg) {
super(msg);
this.errorCode = errorCode;
this.msg = msg;
}
public String getMsg() {
return msg;
}
public int getErrorCode() {
return errorCode;
}
/**
* ,,
* @return a reference to this {@code Throwable} instance.
* @see Throwable#printStackTrace()
*/
@Override
public synchronized Throwable fillInStackTrace() {
return this;
}
}

View File

@ -0,0 +1,79 @@
package com.jinhaiqimeng.sysManageMicroservice.exception;
import cn.hutool.core.util.StrUtil;
import com.jinhaiqimeng.sysManageMicroservice.result.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;
@RestControllerAdvice
@Slf4j
public class MyControllerAdvice {
/**
* Exception
*
* @param e
* @return
*/
@ExceptionHandler(Exception.class)
public Object exceptionHandler(Exception e) {
log.error("Exception content ",e);
return ResponseResult.failed("系统错误,请联系管理员!");
}
/**
* TimeoutException
*
* @param e
* @return
*/
@ExceptionHandler(TimeoutException.class)
public Object exceptionHandler(TimeoutException e) {
log.error("Exception content ",e);
return ResponseResult.failed("执行超时!");
}
/**
* CommonException
*
* @param ex
* @return
*/
@ExceptionHandler(CommonException.class)
public Object exceptionHandler(CommonException ex) {
return ResponseResult.failed(ex.getMsg());
}
@ExceptionHandler(value = {BindException.class, ValidationException.class, MethodArgumentNotValidException.class})
public Object handleValidatedException(Exception e) {
String errorMsg = StrUtil.EMPTY;
if (e instanceof MethodArgumentNotValidException) {
// BeanValidation exception
MethodArgumentNotValidException ex = (MethodArgumentNotValidException) e;
errorMsg = ex.getBindingResult().getAllErrors().stream()
.map(ObjectError::getDefaultMessage)
.collect(Collectors.joining("; "));
} else if (e instanceof ConstraintViolationException) {
// BeanValidation GET simple param
ConstraintViolationException ex = (ConstraintViolationException) e;
errorMsg = ex.getConstraintViolations().stream()
.map(ConstraintViolation::getMessage)
.collect(Collectors.joining("; "));
} else if (e instanceof BindException) {
// BeanValidation GET object param
BindException ex = (BindException) e;
errorMsg = ex.getAllErrors().stream()
.map(ObjectError::getDefaultMessage)
.collect(Collectors.joining("; "));
}
return ResponseResult.failed(errorMsg);
}
}

View File

@ -0,0 +1,29 @@
package com.jinhaiqimeng.sysManageMicroservice.result;
/**
*
*
* @author shengn
*/
public enum ResponseCode {
SUCCESS(200, "success"),
FAILED(1, "system internal error");
private long code;
private String message;
private ResponseCode(long code, String message) {
this.code = code;
this.message = message;
}
public long getCode() {
return code;
}
public String getMessage() {
return message;
}
}

View File

@ -0,0 +1,98 @@
package com.jinhaiqimeng.sysManageMicroservice.result;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.NoArgsConstructor;
/**
* HTTP
*
* @author shengn
*/
@NoArgsConstructor
public class ResponseResult<T> {
private long status;
private String msg;
private T data;
protected ResponseResult(long code, String msg, T data) {
this.status = code;
this.msg = msg;
this.data = data;
}
/**
*
*
*/
public static <T> ResponseResult<T> success() {
return new ResponseResult<T>(ResponseCode.SUCCESS.getCode(), ResponseCode.SUCCESS.getMessage(), null);
}
/**
*
*
* @param data
*/
public static <T> ResponseResult<T> success(T data) {
return new ResponseResult<T>(ResponseCode.SUCCESS.getCode(), ResponseCode.SUCCESS.getMessage(), data);
}
/**
*
*
* @param data
* @param message
*/
public static <T> ResponseResult<T> success(T data, String message) {
return new ResponseResult<T>(ResponseCode.SUCCESS.getCode(), message, data);
}
/**
*
*
* @param message
*/
public static <T> ResponseResult<T> failed(String message) {
return new ResponseResult<T>(ResponseCode.FAILED.getCode(), message, null);
}
public static <T> ResponseResult<T> failed(Long code, String message) {
return new ResponseResult<>(code, message, null);
}
public long getStatus() {
return status;
}
public void setStatus(long status) {
this.status = status;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
@JsonIgnore
public boolean isSuccess() {
return ResponseCode.SUCCESS.getCode() == this.status;
}
@JsonIgnore
public boolean isFail() {
return !this.isSuccess();
}
}

View File

@ -0,0 +1,33 @@
package com.jinhaiqimeng.sysManageMicroservice.util;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* @author cxt
* @date 2023-10-31 8:38
*/
@Target({FIELD})
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = {EnumSensitiveWordValidator.class})
public @interface EnumSensitiveWord {
// 默认错误消息
String message() default "必须为指定值";
String value() default "";
//1 匹配敏感词,错误信息会返回敏感词信息 2:包含敏感词
int type() default 2;
// 分组
Class<?>[] groups() default {};
// 负载
Class<? extends Payload>[] payload() default {};
}

View File

@ -0,0 +1,64 @@
package com.jinhaiqimeng.sysManageMicroservice.util;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.jinhaiqimeng.sysManageMicroservice.result.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
/**
* @author cxt
* @date 2023-10-19 13:50
*/
@Component
@Slf4j
public class EnumSensitiveWordValidator implements ConstraintValidator<EnumSensitiveWord, String> {
@Autowired
ContentAuditingMicroservice contentAuditingMicroservice;
private int type;
@Override
public void initialize(EnumSensitiveWord constraintAnnotation) {
this.type = constraintAnnotation.type();
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
if (StrUtil.isBlank(value)){
return true;
}
PartMatchDTO partMatchDTO = new PartMatchDTO();
partMatchDTO.setContent(value);
partMatchDTO.setPartMatch(false);
if (1 == type){
ResponseResult<SensitiveWordsVO> responseResult = contentAuditingMicroservice.matchSensitiveWord(partMatchDTO);
if (responseResult.isFail()){
log.error("调用敏感词服务失败!"+responseResult.getMsg());
return true;
} else {
SensitiveWordsVO data1 = responseResult.getData();
if (CollUtil.isEmpty(data1.getSensitiveWords())){
return true;
}
context.disableDefaultConstraintViolation();//禁用默认的message的值
context.buildConstraintViolationWithTemplate("文本包含敏感词为:"+ JSON.toJSONString(data1.getSensitiveWords())).addConstraintViolation();
return false;
}
} else if (2 == type){
ResponseResult responseResult = contentAuditingMicroservice.containsSensitiveWord(partMatchDTO);
if (responseResult.isFail()){
log.error("调用敏感词服务失败!"+responseResult.getMsg());
return true;
} else {
boolean data1 = (boolean)responseResult.getData();
return !data1;
}
}
return false;
}
}

View File

@ -0,0 +1,41 @@
package com.jinhaiqimeng.sysManageMicroservice.util;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
*
*/
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER})
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = {EnumValueValidator.class})
public @interface EnumValue {
// 默认错误消息
String message() default "必须为指定值";
String[] strValues() default {};
int[] intValues() default {};
// 分组
Class<?>[] groups() default {};
// 负载
Class<? extends Payload>[] payload() default {};
// 指定多个时使用
@Target({FIELD, METHOD, PARAMETER, ANNOTATION_TYPE})
@Retention(RUNTIME)
@Documented
@interface List {
EnumValue[] value();
}
}

View File

@ -0,0 +1,37 @@
package com.jinhaiqimeng.sysManageMicroservice.util;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
/**
* @author cxt
* @date 2023-10-19 13:50
*/
public class EnumValueValidator implements ConstraintValidator<EnumValue, Object> {
private String[] strValues;
private int[] intValues;
@Override
public void initialize(EnumValue constraintAnnotation) {
strValues = constraintAnnotation.strValues();
intValues = constraintAnnotation.intValues();
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
if (value instanceof String) {
for (String s : strValues) {
if (s.equals(value)) {
return true;
}
}
} else if (value instanceof Integer) {
for (int s : intValues) {
if (s == ((Integer) value).intValue()) {
return true;
}
}
}
return false;
}
}

View File

@ -0,0 +1,17 @@
package com.jinhaiqimeng.sysManageMicroservice.util;
import cn.hutool.core.util.StrUtil;
/**
* @author cxt
* @date 2023-10-20 13:43
*/
public class SpecialReplaceUtil {
public static String replace(String value){
if (StrUtil.isNotBlank(value)){
value = value.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_");
}
return value;
}
}

View File

@ -0,0 +1,31 @@
//package com.jinhaiqimeng.sysManageMicroservice.web.service.impl;
//
//import cn.hutool.core.collection.CollUtil;
//import com.google.common.collect.Lists;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//
//import java.util.List;
//
///**
// * @author cxt
// * @date 2023-10-26 12:34
// */
//@Service
//public class UserServiceImpl implements UserService {
// @Autowired
// AllianceMemberDao allianceMemberDao;
//
// @Override
// public UserDTO getUserById(Long userId) {
// return allianceMemberDao.getUserById(userId);
// }
//
// @Override
// public List<UserDTO> getUserByIds(List<Long> userIds) {
// if (CollUtil.isEmpty(userIds)){
// return Lists.newArrayList();
// }
// return allianceMemberDao.getUserByIds(userIds);
// }
//}

View File

@ -0,0 +1,17 @@
//package com.jinhaiqimeng.sysManageMicroservice.web.service;
//
//import com.jinhaiqimeng.sysManageMicroservice.web.dto.alliance.JoinAllianceDTO;
//import com.baomidou.mybatisplus.extension.service.IService;
//
///**
// * <p>
// * 联盟入会申请 服务类
// * </p>
// *
// * @author cxj
// * @since 2023-10-20
// */
//public interface AllianceJoinApplyService extends IService<AllianceJoinApply> {
//
// void enterprisesJoinAllianceApply(JoinAllianceDTO joinAllianceDTO);
//}

View File

@ -0,0 +1,108 @@
# 应用服务 WEB 访问端口
server:
port: 8007
servlet:
context-path: /sysManageMicroservice
compression:
enabled: true
min-response-size: 1024
mime-types:
- image/png
- image/jpeg
- image/jpg
- text/html
- application/javascript
- text/css
- application/octet-stream
- application/json
spring:
jmx:
enabled: false
application:
name: sysManageMicroservice
http:
encoding:
charset: UTF-8
force: true
enabled: true
mvc:
pathmatch:
matching-strategy: ant_path_matcher
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver # mysql驱动包
url: jdbc:mysql://jinhaiqimengprod.internal.cn-north-4.mysql.rds.myhuaweicloud.com:13306/jinhaiqimengdb?useSSL=false&serverTimezone=Asia/Shanghai&zeroDateTimeBehavior=CONVERT_TO_NULL&allowMultiQueries=true # 数据库名称
username: sysManageMicroservice_user
password: kT7%d6$@jLsh
druid:
# 初始化大小,最小,最大
initial-size: 5
min-idle: 5
max-active: 20
# 配置获取连接等待超时的时间
max-wait: 60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
time-between-eviction-runs-millis: 60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
min-evictable-idle-time-millis: 300000
validation-query: SELECT 1 FROM DUAL
test-while-idle: true
test-on-borrow: false
test-on-return: false
# 打开PSCache并且指定每个连接上PSCache的大小
pool-prepared-statements: true
max-pool-prepared-statement-per-connection-size: 20
# 通过connectProperties属性来打开mergeSql功能慢SQL记录
connect-properties:
druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
# 合并多个DruidDataSource的监控数据
use-global-data-source-stat: true
filters: stat,wall
# redis:
# lettuce:
# pool:
# max-active: 200
# max-idle: 10
# min-idle: -1
# host: redis-6962c01f-a6ab-40c7-9ae1-6dcc29aeb6f3.cn-north-4.dcs.myhuaweicloud.com
# port: 6379
# password: juGmpEv*=p6!&*m6
# timeout: 1000
# database: 1
cloud:
sentinel:
transport:
# 控制台地址
dashboard: 127.0.0.1:8718
eager: true
# 声明式服务
feign:
# 开启okhttp客户端
okhttp:
enabled: true
# 请求与响应的压缩以提高通信效率
compression:
request:
enabled: true
min-request-size: 2048
mime-types: text/xml,application/xml,application/json
response:
enabled: true
httpclient:
enabled: false
logging:
config: classpath:logback-spring.xml
#mybatisPlus
mybatis-plus:
mapper-locations: classpath:mapping/*.xml #注意一定要对应mapper映射xml文件的所在路径
type-aliases-package: com.jinhaiqimeng.sysManageMicroservice.web.entity,com.jinhaiqimeng.orgMicroservice.web.dto # 注意:对应实体类的路径
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

View File

@ -0,0 +1,110 @@
# 应用服务 WEB 访问端口
server:
port: 8007
servlet:
context-path: /sysManageMicroservice
encoding:
charset: UTF-8
force: true
enabled: true
compression:
enabled: true
min-response-size: 1024
mime-types:
- image/png
- image/jpeg
- image/jpg
- text/html
- application/javascript
- text/css
- application/octet-stream
- application/json
spring:
jmx:
enabled: false
# 当前环境名称(注意:不可设置为 test 它是单元测试专用的名称)
profiles:
active: prod
application:
name: sysManageMicroservice
mvc:
pathmatch:
matching-strategy: ant_path_matcher
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver # mysql驱动包
url: jdbc:mysql://120.46.194.248:13306/jinhaiqimengdb?useSSL=false&serverTimezone=Asia/Shanghai&zeroDateTimeBehavior=CONVERT_TO_NULL&allowMultiQueries=true # 数据库名称
username: sysManageMicroservice_user
password: pEqzVsA$whvE
druid:
# 初始化大小,最小,最大
initial-size: 5
min-idle: 5
max-active: 20
# 配置获取连接等待超时的时间
max-wait: 60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
time-between-eviction-runs-millis: 60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
min-evictable-idle-time-millis: 300000
validation-query: SELECT 1 FROM DUAL
test-while-idle: true
test-on-borrow: false
test-on-return: false
# 打开PSCache并且指定每个连接上PSCache的大小
pool-prepared-statements: true
max-pool-prepared-statement-per-connection-size: 20
# 通过connectProperties属性来打开mergeSql功能慢SQL记录
connect-properties:
druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
# 合并多个DruidDataSource的监控数据
use-global-data-source-stat: true
filters: stat,wall
# redis:
# lettuce:
# pool:
# max-active: 200
# max-idle: 10
# min-idle: -1
# host: 120.46.171.171
# port: 6379
# password: bcd4@g2wp*PZv#&U
# timeout: 1000
# database: 1
cloud:
sentinel:
transport:
# 控制台地址
dashboard: 127.0.0.1:8718
eager: true
# 声明式服务
feign:
# 开启okhttp客户端
okhttp:
enabled: true
# 请求与响应的压缩以提高通信效率
compression:
request:
enabled: true
min-request-size: 2048
mime-types: text/xml,application/xml,application/json
response:
enabled: true
httpclient:
enabled: false
logging:
config: classpath:logback-spring.xml
#mybatisPlus
mybatis-plus:
mapper-locations: classpath:mapping/*.xml #注意一定要对应mapper映射xml文件的所在路径
type-aliases-package: com.jinhaiqimeng.sysManageMicroservice.web.entity,com.jinhaiqimeng.orgMicroservice.web.dto # 注意:对应实体类的路径
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

View File

@ -0,0 +1,63 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false" scan="false">
<!-- Log file path -->
<property name="log.path" value="${logPath:-${java.io.tmpdir:-.}}/logs" />
<!-- Console log output -->
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{MM-dd HH:mm:ss.SSS} %-5level [%logger{50}] - %msg%n</pattern>
</encoder>
</appender>
<!-- Log file debug output -->
<appender name="debug" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/debug.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${log.path}/debug.%d{yyyy-MM-dd}.%i.log.zip</fileNamePattern>
<maxFileSize>50MB</maxFileSize>
<maxHistory>30</maxHistory>
</rollingPolicy>
<encoder>
<pattern>%date [%thread] %-5level [%logger{50}] %file:%line - %msg%n</pattern>
</encoder>
<!--<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>DENY</onMatch>
<onMismatch>NEUTRAL</onMismatch>
</filter>-->
</appender>
<!-- Log file error output -->
<appender name="error" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/error.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${log.path}/error.%d{yyyy-MM-dd}.%i.log.zip</fileNamePattern>
<maxFileSize>50MB</maxFileSize>
<maxHistory>30</maxHistory>
</rollingPolicy>
<encoder>
<pattern>%date [%thread] %-5level [%logger{50}] %file:%line - %msg%n</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>ERROR</level>
</filter>
</appender>
<!-- Level: FATAL 0 ERROR 3 WARN 4 INFO 6 DEBUG 7 -->
<root level="WARN">
<appender-ref ref="console" />
<appender-ref ref="debug" />
<appender-ref ref="error" />
</root>
<!-- Project level setting -->
<include resource="org/springframework/boot/logging/logback/defaults.xml" />
<logger name="com.netflix.config.sources.URLConfigurationSource" level="ERROR" />
<logger name="org.springframework.boot.web.embedded" level="INFO" />
<logger name="org.springframework.cloud" level="INFO" />
<logger name="com.jinhaiqimeng.sysManageMicroservice" level="DEBUG" />
<logger name="org.springframework.boot.context.config.ConfigFileApplicationListener" level="DEBUG" />
</configuration>