Commit a1ba4041 by 刘宇峰

Merge remote-tracking branch 'origin/master'

2 parents 77d6d894 bdcbb08c
Showing 152 changed files with 4137 additions and 1495 deletions
...@@ -6,6 +6,7 @@ ...@@ -6,6 +6,7 @@
<groupId>com.glsx</groupId> <groupId>com.glsx</groupId>
<artifactId>rest-admin-framework</artifactId> <artifactId>rest-admin-framework</artifactId>
<version>2.0.0-SNAPSHOT</version> <version>2.0.0-SNAPSHOT</version>
<relativePath/>
</parent> </parent>
<artifactId>glsx-archetype-parent</artifactId> <artifactId>glsx-archetype-parent</artifactId>
...@@ -15,51 +16,11 @@ ...@@ -15,51 +16,11 @@
<properties> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target> <maven.compiler.target>1.8</maven.compiler.target>
<spring-cloud.version>Hoxton.SR9</spring-cloud.version>
<spring-cloud-alibaba.version>2.2.6.RELEASE</spring-cloud-alibaba.version>
<rest-admin-framework.version>2.0.0-SNAPSHOT</rest-admin-framework.version>
<!-- <repo.internal.snapshots.url>https://repo1.maven.org/maven2</repo.internal.snapshots.url>-->
<!-- <repo.internal.releases.url>https://repo1.maven.org/maven2</repo.internal.releases.url>-->
<!-- <repo.proxy.url>https://repo1.maven.org/maven2</repo.proxy.url>-->
<!-- <repo.external.url>https://repo1.maven.org/maven2</repo.external.url>-->
<local.nexus.snapshots.url>http://192.168.3.233/nexus/content/repositories/snapshots/</local.nexus.snapshots.url>
<local.nexus.releases.url>http://192.168.3.233/nexus/content/repositories/releases/</local.nexus.releases.url>
</properties> </properties>
<dependencies>
</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>
<!--spring cloud alibaba-->
<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>
<!--rest-admin-framework-->
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-framework-dependencies</artifactId>
<version>${rest-admin-framework.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build> <build>
<resources> <resources>
<resource> <resource>
......
...@@ -47,56 +47,11 @@ ...@@ -47,56 +47,11 @@
</resource> </resource>
</resources> </resources>
<pluginManagement> <plugins>
<plugins> <plugin>
<plugin> <groupId>org.mybatis.generator</groupId>
<groupId>org.apache.maven.plugins</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId>
<artifactId>maven-archetype-plugin</artifactId> </plugin>
<version>3.2.1</version> </plugins>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<encoding>utf-8</encoding>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
<configuration>
<encoding>UTF-8</encoding>
</configuration>
</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.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<classifier>exec</classifier>
</configuration>
</plugin>
<!-- 一个命令更新版本,mvn versions:set -DnewVersion=1.2-SNAPSHOT -->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>versions-maven-plugin</artifactId>
<version>2.7</version>
<configuration>
<generateBackupPoms>false</generateBackupPoms>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build> </build>
</project> </project>
\ No newline at end of file \ No newline at end of file
...@@ -47,11 +47,11 @@ ...@@ -47,11 +47,11 @@
<version>2.0.0-SNAPSHOT</version> <version>2.0.0-SNAPSHOT</version>
</dependency> </dependency>
<!-- dubbo api --> <!-- dubbo api -->
<!-- <dependency>--> <dependency>
<!-- <groupId>cn.com.glsx.scrm</groupId>--> <groupId>cn.com.glsx.scrm</groupId>
<!-- <artifactId>rpc-scrm-proxy-api</artifactId>--> <artifactId>rpc-scrm-proxy-api</artifactId>
<!-- <version>3.7.0-SNAPSHOT</version>--> <version>3.7.0-SNAPSHOT</version>
<!-- </dependency>--> </dependency>
</dependencies> </dependencies>
<build> <build>
......
...@@ -22,10 +22,8 @@ import static java.util.TimeZone.getTimeZone; ...@@ -22,10 +22,8 @@ import static java.util.TimeZone.getTimeZone;
@EnableDubbo @EnableDubbo
@EnableRestAdmin @EnableRestAdmin
@EnableDiscoveryClient @EnableDiscoveryClient
@EnableTransactionManagement
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
@EnableFeignClients(basePackages = {"cn.com.glsx.*.api"}) @EnableFeignClients(basePackages = {"cn.com.glsx.*.api"})
@SpringBootApplication(scanBasePackages = {"cn.com.glsx.*"}) @SpringBootApplication
public class Application { public class Application {
public static void main(String[] args) { public static void main(String[] args) {
......
package cn.com.glsx.admin.modules.service; package cn.com.glsx.admin.modules.service;
import cn.com.glsx.framework.core.beans.rpc.RpcResponse;
import cn.com.glsx.scrm.proxy.model.ScreenshotRequest;
import cn.com.glsx.scrm.proxy.model.ScreenshotResponse;
import cn.com.glsx.scrm.proxy.remote.ScreenshotRemote;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@Slf4j @Slf4j
@Service @Service
public class DubboDemoService { public class DubboDemoService {
// @DubboReference @DubboReference
// private ScreenshotRemote screenshotRemote; private ScreenshotRemote screenshotRemote;
public String screenshot(String url) { public String screenshot(String url) {
// RpcResponse<ScreenshotResponse> response = screenshotRemote.screenshot(ScreenshotRequest.builder().url(url).build()); RpcResponse<ScreenshotResponse> response = screenshotRemote.screenshot(ScreenshotRequest.builder().url(url).build());
// return response.getResult().getUrl(); return response.getResult().getUrl();
return "";
} }
} }
...@@ -12,7 +12,7 @@ import com.glsx.plat.exception.ResultException; ...@@ -12,7 +12,7 @@ import com.glsx.plat.exception.ResultException;
import com.glsx.plat.exception.SystemMessage; import com.glsx.plat.exception.SystemMessage;
import com.glsx.plat.jwt.base.ComJwtUser; import com.glsx.plat.jwt.base.ComJwtUser;
import com.glsx.plat.jwt.util.JwtUtils; import com.glsx.plat.jwt.util.JwtUtils;
import com.glsx.plat.web.utils.SessionUtils; import com.glsx.plat.common.utils.SessionUtils;
import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.beanutils.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders; import org.springframework.http.HttpHeaders;
......
...@@ -29,7 +29,6 @@ ...@@ -29,7 +29,6 @@
<groupId>com.glsx</groupId> <groupId>com.glsx</groupId>
<artifactId>rest-admin-core</artifactId> <artifactId>rest-admin-core</artifactId>
<version>1.0-SNAPSHOT</version> <version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency> </dependency>
<!-- feign --> <!-- feign -->
...@@ -37,7 +36,6 @@ ...@@ -37,7 +36,6 @@
<groupId>com.glsx</groupId> <groupId>com.glsx</groupId>
<artifactId>rest-admin-feign</artifactId> <artifactId>rest-admin-feign</artifactId>
<version>1.0-SNAPSHOT</version> <version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency> </dependency>
<!--oauth2认证--> <!--oauth2认证-->
......
...@@ -21,20 +21,14 @@ ...@@ -21,20 +21,14 @@
<dependency> <dependency>
<groupId>com.glsx</groupId> <groupId>com.glsx</groupId>
<artifactId>rest-admin-alliance</artifactId> <artifactId>rest-admin-alliance</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.glsx</groupId> <groupId>com.glsx</groupId>
<artifactId>rest-admin-core</artifactId> <artifactId>rest-admin-core</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.glsx</groupId> <groupId>com.glsx</groupId>
<artifactId>rest-admin-mybatis</artifactId> <artifactId>rest-admin-mybatis</artifactId>
<version>1.0.1-SNAPSHOT</version>
<scope>compile</scope>
</dependency> </dependency>
<!-- spring security --> <!-- spring security -->
<dependency> <dependency>
...@@ -45,7 +39,6 @@ ...@@ -45,7 +39,6 @@
<groupId>org.springframework.security.oauth</groupId> <groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId> <artifactId>spring-security-oauth2</artifactId>
<version>2.2.1.RELEASE</version> <version>2.2.1.RELEASE</version>
<scope>compile</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>jakarta.servlet</groupId> <groupId>jakarta.servlet</groupId>
......
...@@ -21,14 +21,10 @@ ...@@ -21,14 +21,10 @@
<dependency> <dependency>
<groupId>com.glsx</groupId> <groupId>com.glsx</groupId>
<artifactId>rest-admin-alliance</artifactId> <artifactId>rest-admin-alliance</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.glsx</groupId> <groupId>com.glsx</groupId>
<artifactId>rest-admin-mybatis</artifactId> <artifactId>rest-admin-mybatis</artifactId>
<version>1.0.1-SNAPSHOT</version>
<scope>compile</scope>
</dependency> </dependency>
<!-- spring security --> <!-- spring security -->
......
...@@ -9,7 +9,7 @@ ...@@ -9,7 +9,7 @@
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<packaging>war</packaging> <packaging>war</packaging>
<artifactId>glsx-rest-admin-gateway-server</artifactId> <artifactId>rest-admin-gateway-archetype</artifactId>
<properties> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
......
...@@ -2,6 +2,7 @@ package com.glsx.plat.gateway.exception; ...@@ -2,6 +2,7 @@ package com.glsx.plat.gateway.exception;
import com.glsx.plat.core.web.R; import com.glsx.plat.core.web.R;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.reactive.error.DefaultErrorAttributes; import org.springframework.boot.web.reactive.error.DefaultErrorAttributes;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
...@@ -9,6 +10,7 @@ import org.springframework.web.reactive.function.server.ServerRequest; ...@@ -9,6 +10,7 @@ import org.springframework.web.reactive.function.server.ServerRequest;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.Map; import java.util.Map;
import java.util.Objects;
/** /**
* @author payu * @author payu
...@@ -18,11 +20,11 @@ import java.util.Map; ...@@ -18,11 +20,11 @@ import java.util.Map;
public class GlobalErrorAttributes extends DefaultErrorAttributes { public class GlobalErrorAttributes extends DefaultErrorAttributes {
@Override @Override
public Map<String, Object> getErrorAttributes(ServerRequest request, boolean includeStackTrace) { public Map<String, Object> getErrorAttributes(ServerRequest request, ErrorAttributeOptions options) {
//简单返回 //简单返回
if (!includeStackTrace) return assembleError(request); if (Objects.isNull(options)) return assembleError(request);
Map<String, Object> map = super.getErrorAttributes(request, includeStackTrace); Map<String, Object> map = super.getErrorAttributes(request, options);
if (getError(request) instanceof GlobalException) { if (getError(request) instanceof GlobalException) {
GlobalException ex = (GlobalException) getError(request); GlobalException ex = (GlobalException) getError(request);
map.put(R.MSG_KEY, ex.getMessage()); map.put(R.MSG_KEY, ex.getMessage());
......
package com.glsx.plat.gateway.exception; package com.glsx.plat.gateway.exception;
import org.springframework.boot.autoconfigure.web.ResourceProperties; import org.springframework.boot.autoconfigure.web.WebProperties;
import org.springframework.boot.autoconfigure.web.reactive.error.AbstractErrorWebExceptionHandler; import org.springframework.boot.autoconfigure.web.reactive.error.AbstractErrorWebExceptionHandler;
import org.springframework.boot.web.reactive.error.ErrorAttributes; import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
...@@ -24,7 +24,7 @@ public class GlobalErrorWebExceptionHandler extends AbstractErrorWebExceptionHan ...@@ -24,7 +24,7 @@ public class GlobalErrorWebExceptionHandler extends AbstractErrorWebExceptionHan
public GlobalErrorWebExceptionHandler(GlobalErrorAttributes g, ApplicationContext applicationContext, public GlobalErrorWebExceptionHandler(GlobalErrorAttributes g, ApplicationContext applicationContext,
ServerCodecConfigurer serverCodecConfigurer) { ServerCodecConfigurer serverCodecConfigurer) {
super(g, new ResourceProperties(), applicationContext); super(g, new WebProperties.Resources(), applicationContext);
super.setMessageWriters(serverCodecConfigurer.getWriters()); super.setMessageWriters(serverCodecConfigurer.getWriters());
super.setMessageReaders(serverCodecConfigurer.getReaders()); super.setMessageReaders(serverCodecConfigurer.getReaders());
} }
......
...@@ -27,6 +27,7 @@ import reactor.core.publisher.Mono; ...@@ -27,6 +27,7 @@ import reactor.core.publisher.Mono;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.Arrays; import java.util.Arrays;
import java.util.Objects;
/** /**
* @author payu * @author payu
...@@ -36,7 +37,7 @@ import java.util.Arrays; ...@@ -36,7 +37,7 @@ import java.util.Arrays;
@RefreshScope @RefreshScope
public class AuthGlobalFilter implements GlobalFilter, Ordered { public class AuthGlobalFilter implements GlobalFilter, Ordered {
@Value("${auth.skip.urls}") @Value("${auth.skip.urls:#{null}}")
private String[] skipAuthUrls; private String[] skipAuthUrls;
@Autowired @Autowired
...@@ -57,7 +58,7 @@ public class AuthGlobalFilter implements GlobalFilter, Ordered { ...@@ -57,7 +58,7 @@ public class AuthGlobalFilter implements GlobalFilter, Ordered {
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
String url = exchange.getRequest().getURI().getPath(); String url = exchange.getRequest().getURI().getPath();
//跳过不需要验证的路径 //跳过不需要验证的路径
if (Arrays.asList(skipAuthUrls).contains(url)) { if (!Objects.isNull(skipAuthUrls) && Arrays.asList(skipAuthUrls).contains(url)) {
return chain.filter(exchange); return chain.filter(exchange);
} }
......
spring.application.name=rest-admin-gateway
logging.path=/data/java_log/jetty/${spring.application.name}/${spring.application.name}.log
spring.main.allow-bean-definition-overriding=true
#nacos config center
spring.cloud.nacos.config.server-addr=192.168.0.63:8868
spring.cloud.nacos.config.group=ARCHETYPE_GROUP
spring.cloud.nacos.config.prefix=${spring.application.name}
spring.profiles.active=dev
spring.cloud.nacos.config.file-extension=properties
#share config
spring.cloud.nacos.config.shared-configs[0].data-id=rest-microservice-share.properties
spring.cloud.nacos.config.shared-configs[0].group=ARCHETYPE_GROUP
spring.cloud.nacos.config.shared-configs[0].refresh=true
\ No newline at end of file \ No newline at end of file
spring.application.name=glsx-rest-admin-gateway
logging.path=/data/java_log/jetty/${spring.application.name}/${spring.application.name}.log
spring.main.allow-bean-definition-overriding=true
#nacos配置中心
spring.cloud.nacos.config.server-addr=192.168.0.63:8848
spring.cloud.nacos.config.group=DEV_GROUP
spring.cloud.nacos.config.prefix=glsx-rest-admin-gateway
#spring.profiles.active=DEV
#spring.cloud.nacos.config.file-extension=properties
#微服务sentinel、zipkin、actuator等公共配置
spring.cloud.nacos.config.shared-configs[0].data-id=glsx-rest-microservice-share.properties
spring.cloud.nacos.config.shared-configs[0].group=DEV_GROUP
spring.cloud.nacos.config.shared-configs[0].refresh=true
\ No newline at end of file \ No newline at end of file
...@@ -9,15 +9,14 @@ ...@@ -9,15 +9,14 @@
<relativePath/> <relativePath/>
</parent> </parent>
<artifactId>glsx-rest-admin-job-archetype</artifactId> <artifactId>rest-admin-job-archetype</artifactId>
<version>1.0-SNAPSHOT</version> <version>2.0.0-SNAPSHOT</version>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<packaging>pom</packaging> <packaging>pom</packaging>
<description>Microservice Scaffolding project for Spring Boot</description> <description>Microservice Scaffolding project for Spring Boot</description>
<modules> <modules>
<module>glsx-rest-admin-job</module> <module>rest-admin-job</module>
<module>glsx-rest-admin-job-dao</module>
</modules> </modules>
<properties> <properties>
...@@ -25,42 +24,25 @@ ...@@ -25,42 +24,25 @@
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target> <maven.compiler.target>1.8</maven.compiler.target>
<spring-cloud.version>Hoxton.SR9</spring-cloud.version> <curator.version>2.12.0</curator.version>
<spring-cloud-alibaba.version>2.2.6.RELEASE</spring-cloud-alibaba.version>
<rest-admin-framework.version>2.0.0-SNAPSHOT</rest-admin-framework.version>
<!-- <repo.internal.snapshots.url>https://repo1.maven.org/maven2</repo.internal.snapshots.url>-->
<!-- <repo.internal.releases.url>https://repo1.maven.org/maven2</repo.internal.releases.url>-->
<!-- <repo.proxy.url>https://repo1.maven.org/maven2</repo.proxy.url>-->
<!-- <repo.external.url>https://repo1.maven.org/maven2</repo.external.url>-->
</properties> </properties>
<dependencies>
</dependencies>
<dependencyManagement> <dependencyManagement>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.springframework.cloud</groupId> <groupId>org.apache.curator</groupId>
<artifactId>spring-cloud-dependencies</artifactId> <artifactId>curator-framework</artifactId>
<version>${spring-cloud.version}</version> <version>${curator.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency> </dependency>
<!--spring cloud alibaba-->
<dependency> <dependency>
<groupId>com.alibaba.cloud</groupId> <groupId>org.apache.curator</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId> <artifactId>curator-recipes</artifactId>
<version>${spring-cloud-alibaba.version}</version> <version>${curator.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency> </dependency>
<!--rest-admin-framework-->
<dependency> <dependency>
<groupId>com.glsx</groupId> <groupId>org.apache.curator</groupId>
<artifactId>rest-admin-framework-dependencies</artifactId> <artifactId>curator-client</artifactId>
<version>${rest-admin-framework.version}</version> <version>${curator.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency> </dependency>
</dependencies> </dependencies>
</dependencyManagement> </dependencyManagement>
...@@ -80,48 +62,5 @@ ...@@ -80,48 +62,5 @@
</includes> </includes>
</resource> </resource>
</resources> </resources>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-archetype-plugin</artifactId>
<version>3.1.2</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<encoding>utf-8</encoding>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
<configuration>
<encoding>UTF-8</encoding>
</configuration>
</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.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<classifier>exec</classifier>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build> </build>
</project> </project>
\ No newline at end of file \ No newline at end of file
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>glsx-rest-admin-job-archetype</artifactId>
<groupId>com.glsx</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<packaging>jar</packaging>
<artifactId>glsx-rest-admin-job-dao</artifactId>
<dependencies>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-mybatis</artifactId>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<plugins>
<!--mybatis 逆向生成插件-->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.7</version>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.7</version>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>3.4.1</version>
</dependency>
</dependencies>
<executions>
<execution>
<id>Generate MyBatis Artifacts</id>
<!-- <phase>package</phase>-->
<phase>deploy</phase>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
<configuration>
<!--允许移动生成的文件 -->
<verbose>true</verbose>
<!-- 是否覆盖 -->
<overwrite>true</overwrite>
<!-- 自动生成的配置 -->
<configurationFile>src/main/resources/config/generatorConfig.xml</configurationFile>
</configuration>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.admin.modules.entity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.glsx.plat.mybatis.base.BaseEntity;
import lombok.Data;
import lombok.experimental.Accessors;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
@Accessors(chain = true)
@Data
@Entity
@Table(name = "t_user")
public class User extends BaseEntity {
/**
* 帐号
*/
@Column(name = "account", length = 64)
private String account;
/**
* 密码
*/
@JsonIgnore
@Column(name = "password", length = 128)
private String password;
/**
* 用户名
*/
@Column(name = "username", length = 64)
private String username;
/**
* (真实)姓名
*/
@Column(name = "realname", length = 64)
private String realname;
/**
* 手机号
*/
@Column(name = "phone", length = 20)
private String phone;
/**
* 头像链接
*/
@Column(name = "avatar", length = 150)
private String avatar;
/**
* 加密盐
*/
private String salt;
}
package cn.com.glsx.admin.modules.mapper;
import cn.com.glsx.admin.modules.entity.User;
import cn.com.glsx.admin.modules.model.UserSearch;
import com.glsx.plat.mybatis.mapper.CommonBaseMapper;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface UserMapper extends CommonBaseMapper<User> {
List<User> selectList(UserSearch search);
User selectByPhone(String phone);
void logicDeleteById(Long id);
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.admin.modules.model;
import cn.hutool.db.Page;
import lombok.Data;
/**
* @author payu
*/
@Data
public class UserSearch extends Page {
private String term;
}
//package com.glsx.vasp.modules.repository;
//
//import com.glsx.vasp.modules.entity.User;
//import java.io.Serializable;
//
///**
// * UserRepository JPA
// */
//public interface IUserRepository extends BaseRepository<User, Long>, Serializable {
//
// User findByUsername(String username);
//
//}
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE generatorConfiguration PUBLIC
"-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<!-- 配置生成器 -->
<generatorConfiguration>
<!--classPathEntry:数据库的JDBC驱动,换成你自己的驱动位置 可选 -->
<!-- <classPathEntry location="F://jdbc//mysql-connector-java-8.0.18.jar"/>-->
<!-- 一个数据库一个context -->
<context id="DB2Tables" targetRuntime="Mybatis3">
<!-- 自动识别数据库关键字,默认false,如果设置为true,根据SqlReservedWords中定义的关键字列表;一般保留默认值,遇到数据库关键字(Java关键字),使用columnOverride覆盖 -->
<property name="autoDelimitKeywords" value="true"/>
<!-- 生成的Java文件的编码 -->
<property name="javaFileEncoding" value="utf-8"/>
<!-- beginningDelimiter和endingDelimiter:指明数据库的用于标记数据库对象名的符号,比如ORACLE就是双引号,MYSQL默认是`反引号; -->
<property name="beginningDelimiter" value="`"/>
<property name="endingDelimiter" value="`"/>
<!-- 格式化java代码 -->
<property name="javaFormatter" value="org.mybatis.generator.api.dom.DefaultJavaFormatter"/>
<!-- 格式化XML代码 -->
<property name="xmlFormatter" value="org.mybatis.generator.api.dom.DefaultXmlFormatter"/>
<plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>
<plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>
<!-- 配置 tk.mybatis 插件 -->
<plugin type="tk.mybatis.mapper.generator.MapperPlugin">
<property name="mappers" value="com.glsx.plat.mybatis.mapper.CommonBaseMapper"/>
</plugin>
<!--配置生成注释信息,最多配置一个 -->
<commentGenerator>
<!-- 阻止生成注释包含时间戳 默认为false -->
<property name="suppressDate" value="true"/>
<!-- 注释是否添加数据库表的备注信息 默认为false -->
<property name="addRemarkComments" value="true"/>
</commentGenerator>
<!-- jdbc连接-->
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://192.168.3.222:3307/newgps?serverTimezone=Asia/Shanghai&amp;useUnicode=true&amp;characterEncoding=utf8&amp;useSSL=false&amp;allowPublicKeyRetrieval=true"
userId="root"
password="Msd^*$@online">
<!--防止生成其他库同名表-->
<property name="nullCatalogMeansCurrent" value="true"/>
</jdbcConnection>
<!-- 类型转换 -->
<javaTypeResolver>
<!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) -->
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 生成实体类地址 -->
<javaModelGenerator targetPackage="cn.com.glsx.admin.modules.entity" targetProject="src/main/java">
<!-- 是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="true"/>
<!-- 从数据库返回的值去掉前后空格 -->
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- 生成mapper.xml文件存放地址 -->
<sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!-- 生成接口dao type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象 type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象 type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口 -->
<javaClientGenerator targetPackage="cn.com.glsx.admin.modules.mapper" targetProject="src/main/java" type="XMLMAPPER">
<property name="enableSubPackages" value="false"/>
</javaClientGenerator>
<!-- table可以有多个,每个数据库中的表都可以写一个table,tableName表示要匹配的数据库表,也可以在tableName属性中通过使用%通配符来匹配所有数据库表,只有匹配的表才会自动生成文件 enableSelectByPrimaryKey相应的配置表示是否生成相应的接口 -->
<table tableName="smart_devide_status" domainObjectName="DeviceStatus" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"/>
</context>
</generatorConfiguration>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.com.glsx.vasp.modules.mapper.UserMapper">
<resultMap id="BaseResultMap" type="cn.com.glsx.vasp.modules.entity.User">
<id column="id" jdbcType="INTEGER" property="id"/>
<result column="phone" jdbcType="VARCHAR" property="phone"/>
<result column="wx_openid" jdbcType="VARCHAR" property="wxOpenid"/>
<result column="mini_openid" jdbcType="VARCHAR" property="miniOpenid"/>
<result column="enable_status" jdbcType="TINYINT" property="enableStatus"/>
<result column="delete_status" jdbcType="TINYINT" property="deleteStatus"/>
<result column="created_date" jdbcType="TIMESTAMP" property="createdDate"/>
<result column="updated_date" jdbcType="TIMESTAMP" property="updatedDate"/>
</resultMap>
<select id="selectList" resultMap="BaseResultMap">
select * from t_user
</select>
<select id="selectByPhone" parameterType="java.lang.String" resultMap="BaseResultMap">
select * from t_user where phone = #{phone}
</select>
<update id="logicDeleteById" parameterType="java.lang.Long">
update t_user set delete_status = -1 where id = #{id}
</update>
</mapper>
\ No newline at end of file \ No newline at end of file
...@@ -11,37 +11,30 @@ ...@@ -11,37 +11,30 @@
<packaging>war</packaging> <packaging>war</packaging>
<description>Microservice Scaffolding Project Base on Spring Cloud</description> <description>Microservice Scaffolding Project Base on Spring Cloud</description>
<artifactId>glsx-rest-admin-job</artifactId> <artifactId>rest-admin-job</artifactId>
<dependencies> <dependencies>
<!-- 运行环境上下文 -->
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-context</artifactId>
<exclusions>
<exclusion>
<artifactId>checker-qual</artifactId>
<groupId>org.checkerframework</groupId>
</exclusion>
</exclusions>
</dependency>
<!-- 接入微服务组件联盟 配置、注册、网关、链路、监控等 ,单体应用无需引入(logback-spring.xml与logstash相关内容需要注释掉)--> <!-- 接入微服务组件联盟 配置、注册、网关、链路、监控等 ,单体应用无需引入(logback-spring.xml与logstash相关内容需要注释掉)-->
<dependency> <dependency>
<groupId>com.glsx</groupId> <groupId>com.glsx</groupId>
<artifactId>rest-admin-alliance</artifactId> <artifactId>rest-admin-alliance</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.glsx</groupId> <groupId>com.glsx</groupId>
<artifactId>rest-admin-elasticjob</artifactId> <artifactId>rest-admin-elasticjob</artifactId>
</dependency> </dependency>
<!-- dao示例 -->
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-job-dao</artifactId>
<version>2.0.0-SNAPSHOT</version>
</dependency>
</dependencies> </dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<version>3.1.1</version>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>
</project> </project>
\ No newline at end of file \ No newline at end of file
...@@ -3,9 +3,9 @@ package cn.com.glsx; ...@@ -3,9 +3,9 @@ package cn.com.glsx;
import com.glsx.plat.context.EnableRestAdmin; import com.glsx.plat.context.EnableRestAdmin;
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.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration;
import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.EnableMBeanExport;
import org.springframework.jmx.support.RegistrationPolicy;
import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
...@@ -20,8 +20,7 @@ import static java.util.TimeZone.getTimeZone; ...@@ -20,8 +20,7 @@ import static java.util.TimeZone.getTimeZone;
@EnableRestAdmin @EnableRestAdmin
@EnableDiscoveryClient @EnableDiscoveryClient
@EnableTransactionManagement @EnableTransactionManagement
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING) @SpringBootApplication(exclude = {MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})
@SpringBootApplication(scanBasePackages = {"cn.com.glsx"})
public class Application { public class Application {
public static void main(String[] args) { public static void main(String[] args) {
......
...@@ -11,8 +11,6 @@ import com.glsx.plat.core.constant.BasicConstants; ...@@ -11,8 +11,6 @@ import com.glsx.plat.core.constant.BasicConstants;
*/ */
public final class Constants extends BasicConstants { public final class Constants extends BasicConstants {
public final static String SERVER_NAME = "glsx_rest_admin"; public final static String SERVER_NAME = "rest-admin-job";
} }
package cn.com.glsx.scheduler.common.exception;
import com.glsx.plat.exception.SystemMessage;
import lombok.Getter;
import lombok.Setter;
/**
* @author payu
*/
@Setter
@Getter
public class AdminException extends RuntimeException {
private int errorCode;
public AdminException() {
}
public AdminException(String message) {
super(message);
}
public AdminException(int errorCode, String message) {
super(message);
this.errorCode = errorCode;
}
public AdminException of(SystemMessage message) {
return new AdminException(message.getCode(), message.getMsg());
}
public AdminException(Throwable cause) {
super(cause);
}
public AdminException(String message, Throwable cause) {
super(message, cause);
}
}
package cn.com.glsx.scheduler.common.exception;
import com.glsx.plat.core.web.R;
import com.glsx.plat.exception.ExceptionLevel;
import com.glsx.plat.exception.GlobalExceptionHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.binding.BindingException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
* 全局异常处理
*
* @author payu
*/
@Slf4j
@RestControllerAdvice
public class AdminExceptionHandler extends GlobalExceptionHandler {
@ExceptionHandler(AdminException.class)
public R handleAdminException(AdminException e) {
return R.error(e.getMessage());
}
/**
* 引入Feign服务的话
*
* @param e
* @return
*/
// @ExceptionHandler(FeignException.class)
// public R handleFeignException(FeignException e) {
// return R.error(e.status(), e.getMessage());
// }
/**
* Mybatis BindingException
*
* @param e
* @return
*/
@ExceptionHandler(BindingException.class)
public R handleBindingException(BindingException e) {
return R.error(e.getMessage());
}
@Override
protected void saveException(Exception e, ExceptionLevel level) {
super.saveException(e, level);
}
}
package cn.com.glsx.scheduler.modules.job; package cn.com.glsx.scheduler.modules.job;
import cn.com.glsx.scheduler.modules.service.MySimpleJobService; import cn.com.glsx.scheduler.modules.service.RestSimpleJobService;
import com.dangdang.ddframe.job.api.ShardingContext; import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob; import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.dangdang.elasticjob.lite.annotation.ElasticSimpleJob; import com.dangdang.elasticjob.lite.annotation.ElasticSimpleJob;
...@@ -13,11 +13,11 @@ import java.util.Date; ...@@ -13,11 +13,11 @@ import java.util.Date;
@Slf4j @Slf4j
@Component @Component
@ElasticSimpleJob(jobName = "MySimpleJob", cron = "0/30 * * * * ?") @ElasticSimpleJob("0/10 * * * * ?")
public class MySimpleJob implements SimpleJob { public class RestSimpleJob implements SimpleJob {
@Autowired @Autowired
private MySimpleJobService simpleJobService; private RestSimpleJobService simpleJobService;
@Override @Override
public void execute(ShardingContext shardingContext) { public void execute(ShardingContext shardingContext) {
...@@ -34,7 +34,7 @@ public class MySimpleJob implements SimpleJob { ...@@ -34,7 +34,7 @@ public class MySimpleJob implements SimpleJob {
String normalDate = DateUtils.formatNormal(new Date()); String normalDate = DateUtils.formatNormal(new Date());
log.info("---------------{}-开始----------------", normalDate); log.info("---------------{}-开始----------------", normalDate);
simpleJobService.simpleJob("张三 " + normalDate); simpleJobService.simpleJob("张三 " + normalDate);
log.info("---------------{}-结束--------------", normalDate); log.info("---------------{}-结束--------------", DateUtils.formatNormal(new Date()));
} }
} }
package cn.com.glsx.scheduler.modules.service; package cn.com.glsx.scheduler.modules.service;
import cn.com.glsx.admin.modules.mapper.UserMapper; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
/** /**
* @author liuyf * @author liuyf
* @date 2021年01月26日 下午2:37:40 * @date 2021年01月26日 下午2:37:40
*/ */
@Slf4j
@Service @Service
public class MySimpleJobService { public class RestSimpleJobService {
@Autowired
private UserMapper userMapper;
public void simpleJob(String name) { public void simpleJob(String name) {
try {
log.info("do something for job");
Thread.sleep(10000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("呼叫:" + name); System.out.println("呼叫:" + name);
} }
......
#项目名称 #项目名称
spring.application.name=glsx-rest-admin-job spring.application.name=rest-admin-job
#日志路径(logback-spring.xml读取,不要加入配置中心) #日志路径(logback-spring.xml读取,不要加入配置中心)
logging.path=/data/java_log/jetty/${spring.application.name}/${spring.application.name}.log logging.path=/data/java_log/jetty/${spring.application.name}/${spring.application.name}.log
#nacos配置中心 #nacos配置中心
spring.cloud.nacos.config.server-addr=192.168.0.63:8848 spring.cloud.nacos.config.server-addr=192.168.0.63:8868
#nacos配置id,完整dataId=${spring.cloud.nacos.config.prefix}-${spring.profiles.active}.${file-extension(由新增配置时选的文件类型决定)} #nacos配置id,完整dataId=${spring.cloud.nacos.config.prefix}-${spring.profiles.active}.${file-extension(由新增配置时选的文件类型决定)}
#示例:http://192.168.0.63:8848/nacos/v1/cs/configs?dataId=glsx-rest-admin.properties&group=DEV_GROUP #示例:http://192.168.0.63:8848/nacos/v1/cs/configs?dataId=glsx-rest-admin.properties&group=DEV_GROUP
spring.cloud.nacos.config.group=DEV_GROUP spring.cloud.nacos.config.group=ARCHETYPE_GROUP
#配置prefix,默认值同${spring.application.name} #配置prefix,默认值同${spring.application.name}
spring.cloud.nacos.config.prefix=${spring.application.name} spring.cloud.nacos.config.prefix=${spring.application.name}
#配置开发环境 #配置开发环境
...@@ -18,11 +18,13 @@ spring.profiles.active=dev ...@@ -18,11 +18,13 @@ spring.profiles.active=dev
spring.cloud.nacos.config.file-extension=properties spring.cloud.nacos.config.file-extension=properties
#微服务sentinel、zipkin、actuator等公共配置 #微服务sentinel、zipkin、actuator等公共配置
spring.cloud.nacos.config.shared-configs[0].data-id=glsx-rest-microservice-share.properties spring.cloud.nacos.config.shared-configs[0].data-id=rest-microservice-share.properties
spring.cloud.nacos.config.shared-configs[0].group=DEV_GROUP spring.cloud.nacos.config.shared-configs[0].group=ARCHETYPE_GROUP
spring.cloud.nacos.config.shared-configs[0].refresh=true spring.cloud.nacos.config.shared-configs[0].refresh=true
#数据库、redis等公共配置 #数据库、redis等公共配置
spring.cloud.nacos.config.shared-configs[1].group=DEV_GROUP spring.cloud.nacos.config.shared-configs[1].group=ARCHETYPE_GROUP
spring.cloud.nacos.config.shared-configs[1].data-id=glsx-rest-admin-share.properties spring.cloud.nacos.config.shared-configs[1].data-id=rest-admin-share-dev.properties
spring.cloud.nacos.config.shared-configs[1].refresh=true spring.cloud.nacos.config.shared-configs[1].refresh=true
spring.main.allow-circular-references=true
\ No newline at end of file \ No newline at end of file
package cn.com.glsx; package cn.com.glsx;
import cn.com.glsx.scheduler.modules.service.MySimpleJobService; import cn.com.glsx.scheduler.modules.service.RestSimpleJobService;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
...@@ -12,11 +12,11 @@ import org.springframework.test.context.junit4.SpringRunner; ...@@ -12,11 +12,11 @@ import org.springframework.test.context.junit4.SpringRunner;
public class DemoApplicationTests { public class DemoApplicationTests {
@Autowired @Autowired
private MySimpleJobService mySimpleJobService; private RestSimpleJobService restSimpleJobService;
@Test @Test
public void testJob() { public void testJob() {
mySimpleJobService.simpleJob("13800138000"); restSimpleJobService.simpleJob("13800138000");
} }
} }
\ No newline at end of file \ No newline at end of file
...@@ -10,60 +10,25 @@ ...@@ -10,60 +10,25 @@
<relativePath/> <relativePath/>
</parent> </parent>
<artifactId>gslx-rest-admin-kafka-archetype</artifactId> <artifactId>rest-admin-kafka-archetype</artifactId>
<version>1.0-SNAPSHOT</version> <version>1.0-SNAPSHOT</version>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<packaging>pom</packaging> <packaging>pom</packaging>
<modules>
<module>glsx-rest-admin-kafka-producer</module>
<module>glsx-rest-admin-kafka-consumer</module>
</modules>
<properties> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target> <maven.compiler.target>1.8</maven.compiler.target>
<spring-cloud.version>Hoxton.SR9</spring-cloud.version>
<spring-cloud-alibaba.version>2.2.6.RELEASE</spring-cloud-alibaba.version>
<rest-admin-framework.version>2.0.0-SNAPSHOT</rest-admin-framework.version>
<!-- <repo.internal.snapshots.url>https://repo1.maven.org/maven2</repo.internal.snapshots.url>-->
<!-- <repo.internal.releases.url>https://repo1.maven.org/maven2</repo.internal.releases.url>-->
<!-- <repo.proxy.url>https://repo1.maven.org/maven2</repo.proxy.url>-->
<!-- <repo.external.url>https://repo1.maven.org/maven2</repo.external.url>-->
</properties> </properties>
<dependencies> <dependencies>
</dependencies> </dependencies>
<dependencyManagement> <modules>
<dependencies> <module>rest-admin-kafka-producer</module>
<dependency> <module>rest-admin-kafka-consumer</module>
<groupId>org.springframework.cloud</groupId> </modules>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!--spring cloud alibaba-->
<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>
<!--rest-admin-framework-->
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-framework-dependencies</artifactId>
<version>${rest-admin-framework.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build> <build>
<resources> <resources>
...@@ -80,48 +45,5 @@ ...@@ -80,48 +45,5 @@
</includes> </includes>
</resource> </resource>
</resources> </resources>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-archetype-plugin</artifactId>
<version>3.1.2</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<encoding>utf-8</encoding>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
<configuration>
<encoding>UTF-8</encoding>
</configuration>
</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.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<classifier>exec</classifier>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build> </build>
</project> </project>
\ No newline at end of file \ No newline at end of file
...@@ -3,14 +3,14 @@ ...@@ -3,14 +3,14 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent> <parent>
<artifactId>gslx-rest-admin-kafka-archetype</artifactId> <artifactId>rest-admin-kafka-archetype</artifactId>
<groupId>com.glsx</groupId> <groupId>com.glsx</groupId>
<version>1.0-SNAPSHOT</version> <version>1.0-SNAPSHOT</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<packaging>war</packaging> <packaging>war</packaging>
<artifactId>glsx-rest-admin-kafka-consumer</artifactId> <artifactId>rest-admin-kafka-consumer</artifactId>
<properties> <properties>
<maven.deploy.skip>true</maven.deploy.skip> <maven.deploy.skip>true</maven.deploy.skip>
......
...@@ -3,14 +3,14 @@ ...@@ -3,14 +3,14 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent> <parent>
<artifactId>gslx-rest-admin-kafka-archetype</artifactId> <artifactId>rest-admin-kafka-archetype</artifactId>
<groupId>com.glsx</groupId> <groupId>com.glsx</groupId>
<version>1.0-SNAPSHOT</version> <version>1.0-SNAPSHOT</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<packaging>war</packaging> <packaging>war</packaging>
<artifactId>glsx-rest-admin-kafka-producer</artifactId> <artifactId>rest-admin-kafka-producer</artifactId>
<properties> <properties>
<maven.deploy.skip>true</maven.deploy.skip> <maven.deploy.skip>true</maven.deploy.skip>
......
...@@ -77,7 +77,7 @@ ...@@ -77,7 +77,7 @@
<dependency> <dependency>
<groupId>org.mybatis.generator</groupId> <groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId> <artifactId>mybatis-generator-core</artifactId>
<version>1.3.7</version> <version>1.4.1</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>tk.mybatis</groupId> <groupId>tk.mybatis</groupId>
......
...@@ -50,7 +50,7 @@ ...@@ -50,7 +50,7 @@
<dependency> <dependency>
<groupId>org.mybatis.generator</groupId> <groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId> <artifactId>mybatis-generator-core</artifactId>
<version>1.3.7</version> <version>1.4.1</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>tk.mybatis</groupId> <groupId>tk.mybatis</groupId>
......
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
<parent> <parent>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId> <artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.12.RELEASE</version> <version>2.6.13</version>
</parent> </parent>
<groupId>com.glsx</groupId> <groupId>com.glsx</groupId>
...@@ -23,16 +23,18 @@ ...@@ -23,16 +23,18 @@
<maven.compiler.source>8</maven.compiler.source> <maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target> <maven.compiler.target>8</maven.compiler.target>
<spring-cloud.version>Hoxton.SR12</spring-cloud.version> <!-- 版本说明:https://github.com/alibaba/spring-cloud-alibaba/wiki/%E7%89%88%E6%9C%AC%E8%AF%B4%E6%98%8E-->
<spring-cloud-alibaba.version>2.2.9.RELEASE</spring-cloud-alibaba.version> <spring-cloud.version>2021.0.5</spring-cloud.version>
<spring-cloud-alibaba.version>2021.0.5.0</spring-cloud-alibaba.version>
<revision>2.0.0-SNAPSHOT</revision> <revision>2.0.0-SNAPSHOT</revision>
<!-- 本地发布服务器 --> <!-- 本地发布服务器 -->
<local.nexus.snapshots.url>http://127.0.0.1:8081/repository/maven-snapshots/</local.nexus.snapshots.url> <!-- <local.nexus.snapshots.url>http://127.0.0.1:8081/repository/maven-snapshots/</local.nexus.snapshots.url>-->
<local.nexus.releases.url>http://127.0.0.1:8081/repository/maven-releases/</local.nexus.releases.url> <!-- <local.nexus.releases.url>http://127.0.0.1:8081/repository/maven-releases/</local.nexus.releases.url>-->
<!-- <local.nexus.snapshots.url>http://192.168.3.233/nexus/content/repositories/snapshots/</local.nexus.snapshots.url>--> <local.nexus.snapshots.url>http://192.168.3.233/nexus/content/repositories/snapshots/
<!-- <local.nexus.releases.url>http://192.168.3.233/nexus/content/repositories/releases/</local.nexus.releases.url>--> </local.nexus.snapshots.url>
<local.nexus.releases.url>http://192.168.3.233/nexus/content/repositories/releases/</local.nexus.releases.url>
</properties> </properties>
<distributionManagement> <distributionManagement>
......
...@@ -16,8 +16,24 @@ ...@@ -16,8 +16,24 @@
<properties> <properties>
<maven.compiler.source>8</maven.compiler.source> <maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target> <maven.compiler.target>8</maven.compiler.target>
<commons.lang.version>2.6</commons.lang.version>
<commons.fileupload.version>1.4</commons.fileupload.version>
<commons.io.version>2.11.0</commons.io.version>
<commons.codec.version>1.10</commons.codec.version>
<commons.lang3.version>3.12.0</commons.lang3.version>
<commons.collections4.version>4.4</commons.collections4.version>
<fastjson.version>1.2.76</fastjson.version> <fastjson.version>1.2.76</fastjson.version>
<fastjson2.version>2.0.3</fastjson2.version>
<javassist.version>3.26.0-GA</javassist.version>
<guava.version>22.0</guava.version> <guava.version>22.0</guava.version>
<hutool.version>5.7.20</hutool.version>
<pagehelper.version>5.3.0</pagehelper.version>
<jackson.version>2.13.3</jackson.version>
<joda.time.version>2.12.5</joda.time.version>
<persistence.version>1.0</persistence.version>
<pagehelper.boot.version>1.4.2</pagehelper.boot.version>
<jsqlparser.version>4.4</jsqlparser.version>
<mybatis.generator.version>1.4.1</mybatis.generator.version>
<org.mapstruct.version>1.5.2.Final</org.mapstruct.version> <org.mapstruct.version>1.5.2.Final</org.mapstruct.version>
</properties> </properties>
...@@ -26,19 +42,69 @@ ...@@ -26,19 +42,69 @@
<dependency> <dependency>
<groupId>org.javassist</groupId> <groupId>org.javassist</groupId>
<artifactId>javassist</artifactId> <artifactId>javassist</artifactId>
<version>3.26.0-GA</version> <version>${javassist.version}</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>${hutool.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.google.guava</groupId> <groupId>com.google.guava</groupId>
<artifactId>guava</artifactId> <artifactId>guava</artifactId>
<version>${guava.version}</version> <version>${guava.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.alibaba</groupId> <groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId> <artifactId>fastjson</artifactId>
<version>${fastjson.version}</version> <version>${fastjson.version}</version>
</dependency> </dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>${pagehelper.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>${persistence.version}</version>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>${org.mapstruct.version}</version>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>${org.mapstruct.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>${joda.time.version}</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>${pagehelper.boot.version}</version>
</dependency>
<dependency>
<groupId>com.github.jsqlparser</groupId>
<artifactId>jsqlparser</artifactId>
<version>${jsqlparser.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>${mybatis.generator.version}</version>
</dependency>
<dependency> <dependency>
<groupId>com.glsx</groupId> <groupId>com.glsx</groupId>
...@@ -182,6 +248,11 @@ ...@@ -182,6 +248,11 @@
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.glsx</groupId> <groupId>com.glsx</groupId>
<artifactId>rest-admin-mybatis-generator</artifactId>
<version>${revision}</version>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-office</artifactId> <artifactId>rest-admin-office</artifactId>
<version>${revision}</version> <version>${revision}</version>
</dependency> </dependency>
...@@ -232,11 +303,6 @@ ...@@ -232,11 +303,6 @@
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.glsx</groupId> <groupId>com.glsx</groupId>
<artifactId>rest-admin-swagger2</artifactId>
<version>${revision}</version>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-swagger3</artifactId> <artifactId>rest-admin-swagger3</artifactId>
<version>${revision}</version> <version>${revision}</version>
</dependency> </dependency>
......
...@@ -43,6 +43,7 @@ ...@@ -43,6 +43,7 @@
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target> <maven.compiler.target>1.8</maven.compiler.target>
<curator.version>2.12.0</curator.version>
</properties> </properties>
<dependencyManagement> <dependencyManagement>
...@@ -71,6 +72,22 @@ ...@@ -71,6 +72,22 @@
<type>pom</type> <type>pom</type>
<scope>import</scope> <scope>import</scope>
</dependency> </dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-framework</artifactId>
<version>${curator.version}</version>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>${curator.version}</version>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-client</artifactId>
<version>${curator.version}</version>
</dependency>
</dependencies> </dependencies>
</dependencyManagement> </dependencyManagement>
...@@ -94,6 +111,7 @@ ...@@ -94,6 +111,7 @@
<module>rest-admin-redis</module> <module>rest-admin-redis</module>
<module>rest-admin-jpa</module> <module>rest-admin-jpa</module>
<module>rest-admin-mybatis</module> <module>rest-admin-mybatis</module>
<module>rest-admin-mybatis-generator</module>
<module>rest-admin-datasource</module> <module>rest-admin-datasource</module>
<module>rest-admin-dubbo</module> <module>rest-admin-dubbo</module>
...@@ -115,7 +133,6 @@ ...@@ -115,7 +133,6 @@
<module>rest-admin-elasticsearch</module> <module>rest-admin-elasticsearch</module>
<module>rest-admin-swagger2</module>
<module>rest-admin-swagger3</module> <module>rest-admin-swagger3</module>
<module>rest-admin-office</module> <module>rest-admin-office</module>
...@@ -138,6 +155,10 @@ ...@@ -138,6 +155,10 @@
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId> <artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope> <scope>test</scope>
...@@ -146,6 +167,10 @@ ...@@ -146,6 +167,10 @@
<groupId>org.junit.vintage</groupId> <groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId> <artifactId>junit-vintage-engine</artifactId>
</exclusion> </exclusion>
<exclusion>
<groupId>org.ow2.asm</groupId>
<artifactId>asm</artifactId>
</exclusion>
</exclusions> </exclusions>
</dependency> </dependency>
<dependency> <dependency>
...@@ -171,6 +196,80 @@ ...@@ -171,6 +196,80 @@
</dependencies> </dependencies>
<build> <build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-archetype-plugin</artifactId>
<version>3.2.1</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<encoding>utf-8</encoding>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
<configuration>
<encoding>UTF-8</encoding>
</configuration>
</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.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.7</version>
<executions>
<execution>
<id>Generate MyBatis Artifacts</id>
<phase>deploy</phase>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
<configuration>
<!-- generator 工具配置文件的位置 此处必须配置 否则找不到该配置文件,maven build不成功-->
<configurationFile>src/test/resources/generatorConfig.xml</configurationFile>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
<dependencies>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<!--<scope>runtime</scope>-->
<version>8.0.28</version>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-mybatis-generator</artifactId>
<version>2.0.0-SNAPSHOT</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</pluginManagement>
<defaultGoal>compile</defaultGoal> <defaultGoal>compile</defaultGoal>
<resources> <resources>
<resource> <resource>
......
...@@ -31,17 +31,14 @@ ...@@ -31,17 +31,14 @@
<dependency> <dependency>
<groupId>com.glsx</groupId> <groupId>com.glsx</groupId>
<artifactId>rest-admin-core</artifactId> <artifactId>rest-admin-core</artifactId>
<scope>compile</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.glsx</groupId> <groupId>com.glsx</groupId>
<artifactId>rest-admin-common</artifactId> <artifactId>rest-admin-common</artifactId>
<scope>compile</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.glsx</groupId> <groupId>com.glsx</groupId>
<artifactId>rest-admin-redis</artifactId> <artifactId>rest-admin-redis</artifactId>
<scope>compile</scope>
</dependency> </dependency>
</dependencies> </dependencies>
......
...@@ -24,14 +24,14 @@ ...@@ -24,14 +24,14 @@
<groupId>com.glsx</groupId> <groupId>com.glsx</groupId>
<artifactId>rest-admin-sentinel</artifactId> <artifactId>rest-admin-sentinel</artifactId>
</dependency> </dependency>
<dependency> <!-- <dependency>-->
<groupId>com.glsx</groupId> <!-- <groupId>com.glsx</groupId>-->
<artifactId>rest-admin-sleuth</artifactId> <!-- <artifactId>rest-admin-sleuth</artifactId>-->
</dependency> <!-- </dependency>-->
<dependency> <!-- <dependency>-->
<groupId>com.glsx</groupId> <!-- <groupId>com.glsx</groupId>-->
<artifactId>rest-admin-monitor</artifactId> <!-- <artifactId>rest-admin-monitor</artifactId>-->
</dependency> <!-- </dependency>-->
<dependency> <dependency>
<groupId>com.glsx</groupId> <groupId>com.glsx</groupId>
<artifactId>rest-admin-gateway-client</artifactId> <artifactId>rest-admin-gateway-client</artifactId>
......
...@@ -21,7 +21,12 @@ ...@@ -21,7 +21,12 @@
<dependency> <dependency>
<groupId>com.github.ben-manes.caffeine</groupId> <groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId> <artifactId>caffeine</artifactId>
<version>3.1.1</version> <exclusions>
<exclusion>
<groupId>com.google.errorprone</groupId>
<artifactId>error_prone_annotations</artifactId>
</exclusion>
</exclusions>
</dependency> </dependency>
<dependency> <dependency>
......
package com.glsx.plat.cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.glsx.plat.constant.CacheNameTimeConstant;
import org.springframework.cache.CacheManager;
import org.springframework.cache.caffeine.CaffeineCache;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
@Configuration
public class CacheConfig {
@Bean
public CacheManager caffeineCacheManager() {
SimpleCacheManager cacheManager = new SimpleCacheManager();
List<CaffeineCache> caches = new ArrayList<>();
caches.add(new CaffeineCache(CacheNameTimeConstant.CACHE_5SECS, Caffeine.newBuilder().expireAfterWrite(5, TimeUnit.SECONDS).build()));
caches.add(new CaffeineCache(CacheNameTimeConstant.CACHE_10SECS, Caffeine.newBuilder().expireAfterWrite(10, TimeUnit.SECONDS).build()));
caches.add(new CaffeineCache(CacheNameTimeConstant.CACHE_30SECS, Caffeine.newBuilder().expireAfterWrite(30, TimeUnit.SECONDS).build()));
cacheManager.setCaches(caches);
return cacheManager;
}
}
package com.glsx.plat.constant;
public interface CacheNameTimeConstant {
String CACHE_DEFAULT = "CACHE_DEFAULT";
String CACHE_10SECS = "CACHE_10SECS";
String CACHE_5SECS = "CACHE_5SECS";
String CACHE_30SECS = "CACHE_30SECS";
String CACHE_60SECS = "CACHE_60SECS";
String CACHE_10MINS = "CACHE_10MINS";
String CACHE_5MINS = "CACHE_5MINS";
String CACHE_30MINS = "CACHE_30MINS";
String CACHE_60MINS = "CACHE_60MINS";
String CACHE_12HOURS = "CACHE_12HOURS";
String CACHE_24HOURS = "CACHE_24HOURS";
String CACHE_3DAYS = "CACHE_3DAYS";
String CACHE_7DAYS = "CACHE_7DAYS";
String CACHE_30DAYS = "CACHE_30DAYS";
}
...@@ -18,9 +18,6 @@ ...@@ -18,9 +18,6 @@
<commons.codec.version>1.10</commons.codec.version> <commons.codec.version>1.10</commons.codec.version>
<commons.lang3.version>3.12.0</commons.lang3.version> <commons.lang3.version>3.12.0</commons.lang3.version>
<commons.collections4.version>4.4</commons.collections4.version> <commons.collections4.version>4.4</commons.collections4.version>
<joda.time.version>2.10.14</joda.time.version>
<org.mapstruct.version>1.5.2.Final</org.mapstruct.version>
<fastjson.version>1.2.76</fastjson.version>
<fastjson2.version>2.0.3</fastjson2.version> <fastjson2.version>2.0.3</fastjson2.version>
</properties> </properties>
...@@ -98,7 +95,6 @@ ...@@ -98,7 +95,6 @@
<dependency> <dependency>
<groupId>com.alibaba</groupId> <groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId> <artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency> </dependency>
<!-- <dependency>--> <!-- <dependency>-->
<!-- <groupId>com.alibaba.fastjson2</groupId>--> <!-- <groupId>com.alibaba.fastjson2</groupId>-->
...@@ -107,14 +103,8 @@ ...@@ -107,14 +103,8 @@
<!-- </dependency>--> <!-- </dependency>-->
<dependency> <dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
<dependency>
<groupId>joda-time</groupId> <groupId>joda-time</groupId>
<artifactId>joda-time</artifactId> <artifactId>joda-time</artifactId>
<version>${joda.time.version}</version>
</dependency> </dependency>
<dependency> <dependency>
...@@ -126,12 +116,10 @@ ...@@ -126,12 +116,10 @@
<dependency> <dependency>
<groupId>org.mapstruct</groupId> <groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId> <artifactId>mapstruct</artifactId>
<version>${org.mapstruct.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.mapstruct</groupId> <groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId> <artifactId>mapstruct-processor</artifactId>
<version>${org.mapstruct.version}</version>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
</dependencies> </dependencies>
......
package com.glsx.plat.web.utils; package com.glsx.plat.common.utils;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
......
package com.glsx.plat.common.utils;
import org.bouncycastle.crypto.digests.SM3Digest;
import org.bouncycastle.crypto.macs.HMac;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.pqc.math.linearalgebra.ByteUtils;
import java.io.UnsupportedEncodingException;
import java.security.Security;
import java.util.Arrays;
public class SM3Utils {
private static final String ENCODING = "UTF-8";
static {
Security.addProvider(new BouncyCastleProvider());
}
/**
* sm3 算法加密 *
*
* @param paramStr 待加密的参数字符串
* @param appKey 加密的密钥 appKey(接口访问秘钥 Key)
* @return 返回 SM3 加密后固定长度为 32 的 16 进制密内容文字符串
* @explain
*/
public static String encrypt(String paramStr, String appKey) {
//将返回的 hash 值转换成 16 进制字符串
String resultHexStr = "";
try {
//将字符串转换成 byte 数组
byte[] srcData = paramStr.getBytes(ENCODING);
//调用 hash()
byte[] resultHash = hmac(srcData, appKey.getBytes(ENCODING));
//将返回的 hash 值转换成 16 进制字符串
resultHexStr = ByteUtils.toHexString(resultHash);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return resultHexStr;
}
/**
* 通过密钥进行哈希
*
* @param appKey 加密的密钥 appKey 的 byte 数组
* @param srcData 被加密参数字符串的 byte 数组
* @return
*/
public static byte[] hmac(byte[] appKey, byte[] srcData) {
KeyParameter keyParameter = new KeyParameter(appKey);
SM3Digest digest = new SM3Digest();
HMac mac = new HMac(digest);
mac.init(keyParameter);
mac.update(srcData, 0, srcData.length);
byte[] result = new byte[mac.getMacSize()];
mac.doFinal(result, 0);
return result;
}
/**
* 判断待加密的原始数据与加密后的数据是否一致 *
*
* @param paramStr 待加密的参数字符串
* @param resultHexStr SM3 加密后固定长度为 32 的 16 进制密内容文字符串
* appKey
* 加密的密钥 appKey 的 byte 数组
* 校验结果
*/
public static boolean verify(String paramStr, String resultHexStr, String appKey) {
boolean flag = false;
try {
byte[] srcData = paramStr.getBytes(ENCODING);
byte[] sm3Hash = ByteUtils.fromHexString(resultHexStr);
byte[] newHash = hmac(srcData, appKey.getBytes(ENCODING));
if (Arrays.equals(newHash, sm3Hash)) {
flag = true;
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return flag;
}
public static void main(String[] args) {
//待加密的待加密的参数字符串
String paramStr = "6bba9d97c252661067758b2b6f80e7c558e562b8";
//加密的密钥 appKey
String appKey = "RaOF35Kw";
//sm3 算法加密
String resultHexStr = SM3Utils.encrypt(paramStr, appKey);
System.out.println("待加密的待加密的参数字符串:" + paramStr);
System.out.println("SM3 加密后的密文字符串内容:" + resultHexStr);
System.out.println("校验结果:" + SM3Utils.verify(paramStr, resultHexStr, appKey));
}
}
\ No newline at end of file \ No newline at end of file
package com.glsx.plat.web.utils; package com.glsx.plat.common.utils;
import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.context.request.ServletRequestAttributes;
......
...@@ -3,6 +3,8 @@ ...@@ -3,6 +3,8 @@
*/ */
package com.glsx.plat.common.utils; package com.glsx.plat.common.utils;
import org.springframework.util.AntPathMatcher;
import java.io.*; import java.io.*;
import java.util.*; import java.util.*;
...@@ -145,6 +147,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils { ...@@ -145,6 +147,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
/** /**
* 将null转空字符串 * 将null转空字符串
*
* @param origin * @param origin
* @return * @return
*/ */
...@@ -255,15 +258,41 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils { ...@@ -255,15 +258,41 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
return false; return false;
} }
/**
* 判断当前访问的url是否开头URI是在配置的忽略url列表中
*
* @param url
* @return
*/
public static boolean isMatchedStr(String[] skipAuthUrls, String url) {
if (StringUtils.isEmpty(url)) {
return false;
}
if (Objects.isNull(skipAuthUrls)) {
return false;
}
AntPathMatcher matcher = new AntPathMatcher();
for (String skipAuthUrl : skipAuthUrls) {
if (matcher.match(skipAuthUrl, url)) {
return true;
}
}
return false;
}
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static <T> T cast(Object obj) { public static <T> T cast(Object obj) {
return (T) obj; return (T) obj;
} }
// public static void main(String[] args) throws UnsupportedEncodingException { // public static void main(String[] args) throws UnsupportedEncodingException {
// System.out.println("中文a".getBytes("UTF-8").length); //7 //// System.out.println("中文a".getBytes("UTF-8").length); //7
// System.out.println(getStrLength("中文a")); //7 //// System.out.println(getStrLength("中文a")); //7
// System.out.println("中文a".length()); //3 //// System.out.println("中文a".length()); //3
//
// String[] skipAuthUrls = new String[]{"/login/check", "/api/**", "/**/v3/api-docs", "/open/api/access/queryAccessToken"};
// boolean flag = isMatchedStr(skipAuthUrls, "/platform-shopmall/v3/api-docs");
// System.out.println(flag);
// } // }
} }
...@@ -43,7 +43,7 @@ public class NacosConfigLog { ...@@ -43,7 +43,7 @@ public class NacosConfigLog {
dataId = prefix + "." + extension; dataId = prefix + "." + extension;
content = configService.getConfig(dataId, group, 5000); content = configService.getConfig(dataId, group, 5000);
} }
log.info("- dataId {} config info\n{}", dataId, content); log.info("{} -group {} dataId {} config info\n{}", serverAddr, group, dataId, content);
} }
} }
...@@ -2,7 +2,7 @@ package com.glsx.plat.context.aop; ...@@ -2,7 +2,7 @@ package com.glsx.plat.context.aop;
import com.glsx.plat.common.annotation.NoResubmit; import com.glsx.plat.common.annotation.NoResubmit;
import com.glsx.plat.core.web.R; import com.glsx.plat.core.web.R;
import com.glsx.plat.web.utils.IpUtils; import com.glsx.plat.common.utils.IpUtils;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
......
...@@ -5,7 +5,6 @@ import org.apache.commons.lang.time.DateUtils; ...@@ -5,7 +5,6 @@ import org.apache.commons.lang.time.DateUtils;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler; import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
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.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
...@@ -18,7 +17,7 @@ import java.util.concurrent.ThreadPoolExecutor; ...@@ -18,7 +17,7 @@ import java.util.concurrent.ThreadPoolExecutor;
@Slf4j @Slf4j
@EnableAsync @EnableAsync
@Configuration @Configuration
public class ThreadPoolConfig implements AsyncConfigurer { public class ThreadPoolConfig {
DefaultRejectedExecutionHandler rejectedExecutionHandler = new DefaultRejectedExecutionHandler(); DefaultRejectedExecutionHandler rejectedExecutionHandler = new DefaultRejectedExecutionHandler();
// 线程池维护线程的最少数量 // 线程池维护线程的最少数量
...@@ -26,10 +25,9 @@ public class ThreadPoolConfig implements AsyncConfigurer { ...@@ -26,10 +25,9 @@ public class ThreadPoolConfig implements AsyncConfigurer {
//最大线程池大小 //最大线程池大小
private int maxPoolSize = 150; private int maxPoolSize = 150;
//队列容量,排队数 //队列容量,排队数
private int queueCapacity = 10000; private int queueCapacity = 1000;
@Bean(name = "threadPoolTaskExecutor") @Bean(name = "threadPoolTaskExecutor")
@Override
public ThreadPoolTaskExecutor getAsyncExecutor() { public ThreadPoolTaskExecutor getAsyncExecutor() {
ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor(); ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
//设置核心线程数 //设置核心线程数
...@@ -41,7 +39,7 @@ public class ThreadPoolConfig implements AsyncConfigurer { ...@@ -41,7 +39,7 @@ public class ThreadPoolConfig implements AsyncConfigurer {
//设置线程活跃时间(秒) 最大允许空闲时间,超过时间并且当前池中线程数大于 corePoolSize 的时候会销毁 //设置线程活跃时间(秒) 最大允许空闲时间,超过时间并且当前池中线程数大于 corePoolSize 的时候会销毁
threadPoolTaskExecutor.setKeepAliveSeconds(60); threadPoolTaskExecutor.setKeepAliveSeconds(60);
//设置默认线程名称 //设置默认线程名称
threadPoolTaskExecutor.setThreadNamePrefix("payu-"); threadPoolTaskExecutor.setThreadNamePrefix("plat-");
//设置拒绝策略 //设置拒绝策略
// threadPoolTaskExecutor.setRejectedExecutionHandler(rejectedExecutionHandler); // threadPoolTaskExecutor.setRejectedExecutionHandler(rejectedExecutionHandler);
threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
...@@ -56,7 +54,6 @@ public class ThreadPoolConfig implements AsyncConfigurer { ...@@ -56,7 +54,6 @@ public class ThreadPoolConfig implements AsyncConfigurer {
* *
* @return * @return
*/ */
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
AsyncUncaughtExceptionHandler asyncUncaughtExceptionHandler = (throwable, method, objects) -> { AsyncUncaughtExceptionHandler asyncUncaughtExceptionHandler = (throwable, method, objects) -> {
log.error(method.getName() + " 执行异常", throwable); log.error(method.getName() + " 执行异常", throwable);
......
...@@ -2,9 +2,14 @@ package com.glsx.plat.context.configuration; ...@@ -2,9 +2,14 @@ package com.glsx.plat.context.configuration;
import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableMBeanExport;
import org.springframework.jmx.support.RegistrationPolicy;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration @Configuration
@ComponentScan({"com.glsx.plat"}) @ComponentScan({"com.glsx.plat", "cn.com.glsx.*"})
@EnableTransactionManagement
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
public class RestAdminAutoConfiguration { public class RestAdminAutoConfiguration {
} }
\ No newline at end of file \ No newline at end of file
package com.glsx.plat.context.utils;
import com.glsx.plat.exception.ValidateException;
import org.apache.commons.lang.StringUtils;
/**
* 断言工具类
*/
public class AssertUtil {
public static void isBlank(String str, String message) {
if (StringUtils.isBlank(str)) {
throw new ValidateException(message);
}
}
public static void isNull(Object object, String message) {
if (object == null) {
throw new ValidateException(message);
}
}
}
/**
* Copyright (c) 2016-2019 人人开源 All rights reserved.
* <p>
* https://www.renren.io
* <p>
* 版权所有,侵权必究!
*/
package com.glsx.plat.context.utils.validator;
import com.glsx.plat.exception.ValidateException;
import org.apache.commons.lang.StringUtils;
/**
* 数据校验
*/
public abstract class AssertUtils {
public static void isBlank(String str, String message) {
if (StringUtils.isBlank(str)) {
throw new ValidateException(message);
}
}
public static void isNull(Object object, String message) {
if (object == null) {
throw new ValidateException(message);
}
}
}
...@@ -31,12 +31,22 @@ ...@@ -31,12 +31,22 @@
<dependency> <dependency>
<groupId>cn.hutool</groupId> <groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId> <artifactId>hutool-all</artifactId>
<version>5.7.20</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.github.pagehelper</groupId> <groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId> <artifactId>pagehelper</artifactId>
<version>5.3.0</version> </dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
</dependency>
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
</dependency>
<dependency>
<groupId>jakarta.persistence</groupId>
<artifactId>jakarta.persistence-api</artifactId>
</dependency> </dependency>
</dependencies> </dependencies>
</project> </project>
\ No newline at end of file \ No newline at end of file
package com.glsx.plat.mybatis.base; package com.glsx.plat.core.base;
import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonFormat;
import com.glsx.plat.core.enums.SysConstants; import com.glsx.plat.core.enums.SysConstants;
......
package com.glsx.plat.core.enums;
public interface BaseEnum<E extends Enum<?>, T> {
public T getValue();
public String getDisplayName();
}
package com.glsx.plat.core.web;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import java.io.Serializable;
@Data
@Builder
@Accessors(chain = true)
@NoArgsConstructor
@AllArgsConstructor
public class OpenApiResult<T> implements Serializable {
private static final String SUCCESS_DEFAULT_CODE = "00000";
private static final String FAILURE_DEFAULT_CODE = "44444";
private Boolean success;
private String code;
private String desc;
private T result;
private Long time;
public static <T> OpenApiResult<T> success(T result) {
return OpenApiResult.<T>builder()
.code(SUCCESS_DEFAULT_CODE)
.success(true)
.desc("成功")
.result(result)
.time(System.currentTimeMillis())
.build();
}
public static <T> OpenApiResult<T> failure(String code, String desc) {
return OpenApiResult.<T>builder()
.success(true)
.code(code)
.desc(desc)
.result(null)
.time(System.currentTimeMillis())
.build();
}
}
//package com.glsx.plat.datasource.config; package com.glsx.plat.datasource.config;
//
//import com.alibaba.druid.pool.DruidDataSource; import org.springframework.context.annotation.Configuration;
//import com.alibaba.druid.support.http.StatViewServlet;
//import com.alibaba.druid.support.http.WebStatFilter; @Configuration
//import org.springframework.boot.context.properties.ConfigurationProperties; public class DruidConfig {
//import org.springframework.boot.web.servlet.FilterRegistrationBean;
//import org.springframework.boot.web.servlet.ServletRegistrationBean; //加载application.yaml中的Druid配置
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//
//import javax.sql.DataSource;
//import java.util.Arrays;
//import java.util.HashMap;
//import java.util.Map;
//
//@Configuration
//public class DruidConfig {
//
// //加载application.yaml中的Druid配置
// @ConfigurationProperties(prefix = "spring.datasource") // @ConfigurationProperties(prefix = "spring.datasource")
// @Bean // @Bean
// public DataSource druid() { // public DataSource druid() {
// return new DruidDataSource(); // return new DruidDataSource();
// } // }
//
// //配置Druid的监控 // //配置Druid的监控
// //1、配置一个管理后台的Servlet // //1、配置一个管理后台的Servlet
// @Bean // @Bean
...@@ -56,5 +44,31 @@ ...@@ -56,5 +44,31 @@
// //
// return bean; // return bean;
// } // }
// @Bean
// @ConfigurationProperties(prefix = "spring.datasource")
// public DataSource druidPrimary() {
// DruidDataSource druidDataSource = new DruidDataSource();
// List<Filter> filterList = new ArrayList<>();
// filterList.add(wallFilter());
// druidDataSource.setProxyFilters(filterList);
// return new DruidDataSource();
// }
// //
//}
\ No newline at end of file \ No newline at end of file
// @Bean
// public WallFilter wallFilter() {
// WallFilter wallFilter = new WallFilter();
// wallFilter.setConfig(wallConfig());
// return wallFilter;
// }
//
// @Bean
// public WallConfig wallConfig() {
// WallConfig config = new WallConfig();
// //允许一次执行多条语句
// config.setMultiStatementAllow(true);
// config.setNoneBaseStatementAllow(true);
// return config;
// }
}
\ No newline at end of file \ No newline at end of file
...@@ -12,31 +12,49 @@ ...@@ -12,31 +12,49 @@
<artifactId>rest-admin-dubbo</artifactId> <artifactId>rest-admin-dubbo</artifactId>
<properties> <properties>
<curator.version>4.2.0</curator.version> <curator.version>2.12.0</curator.version>
<dubbo.version>2.7.7</dubbo.version>
<zookeeper.version>3.4.6</zookeeper.version>
</properties> </properties>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.apache.curator</groupId> <groupId>org.apache.dubbo</groupId>
<artifactId>curator-framework</artifactId> <artifactId>dubbo-spring-boot-starter</artifactId>
<version>${curator.version}</version> <version>${dubbo.version}</version>
</dependency>
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-dependencies-zookeeper</artifactId>
<version>${dubbo.version}</version>
<type>pom</type>
<!-- 4.0.0原生不兼容zk 3.4, 必须进行兼容性处理 -->
<exclusions> <exclusions>
<exclusion> <exclusion>
<groupId>org.apache.zookeeper</groupId> <groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId> <artifactId>zookeeper</artifactId>
</exclusion> </exclusion>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
</exclusions> </exclusions>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>${curator.version}</version>
</dependency>
<dependency>
<groupId>com.101tec</groupId> <groupId>com.101tec</groupId>
<artifactId>zkclient</artifactId> <artifactId>zkclient</artifactId>
<version>0.11</version> <version>0.11</version>
<exclusions>
<exclusion>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>${zookeeper.version}</version>
<!--排除这个slf4j-log4j12--> <!--排除这个slf4j-log4j12-->
<exclusions> <exclusions>
<exclusion> <exclusion>
...@@ -45,15 +63,5 @@ ...@@ -45,15 +63,5 @@
</exclusion> </exclusion>
</exclusions> </exclusions>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-dubbo</artifactId>
<version>2.2.1.RELEASE</version>
</dependency>
</dependencies> </dependencies>
</project> </project>
\ No newline at end of file \ No newline at end of file
package com.glsx.plat.dubbo.config;
import com.alibaba.spring.context.config.ConfigurationBeanBinder;
import org.apache.dubbo.config.spring.context.properties.DubboConfigBinder;
import org.springframework.boot.context.properties.bind.BindHandler;
import org.springframework.boot.context.properties.bind.Bindable;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.boot.context.properties.bind.PropertySourcesPlaceholdersResolver;
import org.springframework.boot.context.properties.bind.handler.IgnoreErrorsBindHandler;
import org.springframework.boot.context.properties.bind.handler.NoUnboundElementsBindHandler;
import org.springframework.boot.context.properties.source.ConfigurationPropertySource;
import org.springframework.boot.context.properties.source.UnboundElementsSourceFilter;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.PropertySource;
import java.util.Map;
import static java.util.Arrays.asList;
import static org.springframework.boot.context.properties.source.ConfigurationPropertySources.from;
/**
* Spring Boot Relaxed {@link DubboConfigBinder} implementation
* see org.springframework.boot.context.properties.ConfigurationPropertiesBinder
*
* @since 2.7.0
*/
class BinderDubboConfigBinder implements ConfigurationBeanBinder {
@Override
public void bind(Map<String, Object> configurationProperties, boolean ignoreUnknownFields,
boolean ignoreInvalidFields, Object configurationBean) {
Iterable<PropertySource<?>> propertySources = asList(new MapPropertySource("internal", configurationProperties));
// Converts ConfigurationPropertySources
Iterable<ConfigurationPropertySource> configurationPropertySources = from(propertySources);
// Wrap Bindable from DubboConfig instance
Bindable bindable = Bindable.ofInstance(configurationBean);
Binder binder = new Binder(configurationPropertySources, new PropertySourcesPlaceholdersResolver(propertySources));
// Get BindHandler
BindHandler bindHandler = getBindHandler(ignoreUnknownFields, ignoreInvalidFields);
// Bind
binder.bind("", bindable, bindHandler);
}
private BindHandler getBindHandler(boolean ignoreUnknownFields,
boolean ignoreInvalidFields) {
BindHandler handler = BindHandler.DEFAULT;
if (ignoreInvalidFields) {
handler = new IgnoreErrorsBindHandler(handler);
}
if (!ignoreUnknownFields) {
UnboundElementsSourceFilter filter = new UnboundElementsSourceFilter();
handler = new NoUnboundElementsBindHandler(handler, filter);
}
return handler;
}
}
package com.glsx.plat.dubbo.config;
import org.apache.dubbo.common.utils.Assert;
import org.springframework.core.env.PropertyResolver;
import org.springframework.lang.Nullable;
/**
* Delegating {@link PropertyResolver}
*
* @since 2.7.1
*/
class DelegatingPropertyResolver implements PropertyResolver {
private final PropertyResolver delegate;
DelegatingPropertyResolver(PropertyResolver delegate) {
Assert.notNull(delegate, "The delegate of PropertyResolver must not be null");
this.delegate = delegate;
}
@Override
public boolean containsProperty(String key) {
return delegate.containsProperty(key);
}
@Override
@Nullable
public String getProperty(String key) {
return delegate.getProperty(key);
}
@Override
public String getProperty(String key, String defaultValue) {
return delegate.getProperty(key, defaultValue);
}
@Override
@Nullable
public <T> T getProperty(String key, Class<T> targetType) {
return delegate.getProperty(key, targetType);
}
@Override
public <T> T getProperty(String key, Class<T> targetType, T defaultValue) {
return delegate.getProperty(key, targetType, defaultValue);
}
@Override
public String getRequiredProperty(String key) throws IllegalStateException {
return delegate.getRequiredProperty(key);
}
@Override
public <T> T getRequiredProperty(String key, Class<T> targetType) throws IllegalStateException {
return delegate.getRequiredProperty(key, targetType);
}
@Override
public String resolvePlaceholders(String text) {
return delegate.resolvePlaceholders(text);
}
@Override
public String resolveRequiredPlaceholders(String text) throws IllegalArgumentException {
return delegate.resolveRequiredPlaceholders(text);
}
}
\ No newline at end of file \ No newline at end of file
package com.glsx.plat.dubbo.config;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import com.glsx.plat.dubbo.factory.ReferenceBuilderFactory;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ProviderConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.dubbo.config.spring.beans.factory.annotation.ReferenceAnnotationBeanPostProcessor;
import org.apache.dubbo.config.spring.beans.factory.annotation.ServiceClassPostProcessor;
import org.apache.dubbo.spring.boot.autoconfigure.DubboRelaxedBinding2AutoConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.core.env.PropertyResolver;
import java.util.HashSet;
import java.util.Set;
import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_PREFIX;
import static org.apache.dubbo.spring.boot.util.DubboUtils.PROPERTY_NAME_SEPARATOR;
/**
* Dubbo Auto {@link Configuration}
*
* @see DubboReference
* @see DubboService
* @see ServiceClassPostProcessor
* @see ReferenceAnnotationBeanPostProcessor
* @since 2.7.0
*/
//@Configuration
//@AutoConfigureAfter(DubboRelaxedBinding2AutoConfiguration.class)
//@EnableConfigurationProperties(DubboConfigurationProperties.class)
//@Import({DubboRelaxedBinding2AutoConfiguration.class})
public class DubboAutoConfiguration {
/**
* service类,服务提供者的BeanDefinitionRegistryPostProcessor类,用来解析 * @Service, @DubboService注解,生成Service的BeanDefinition类,放入spring容器,供spring容器生成Bean
* modify by alvin.zengqi
*
* @param propertyResolver
* @param properties
* @return
* @since 2.6.0
*/
@Bean
public ServiceClassPostProcessor serviceClassPostProcessor(PropertyResolver propertyResolver, DubboConfigurationProperties properties) {
Set<String> packagesToScan = new HashSet<>();
if (properties.getScan() != null && properties.getScan().getBasePackages() != null) {
packagesToScan = properties.getScan().getBasePackages();
}
// 兼容alibaba dubbo低版本scan
String scanPackage = propertyResolver.getProperty("dubbo.scan", String.class);
packagesToScan.add(scanPackage);
return new ServiceClassPostProcessor(packagesToScan);
}
/**
* 用来解析@Reference,@DubboReference 注解,消费者引用哪些服务,通过这个注解来进行引用 * 给标注这个@Reference,@DubboReference注解的属性赋值, 和@autowired的做法类似
* Creates {@link ReferenceAnnotationBeanPostProcessor} Bean if Absent
*
* @return {@link ReferenceAnnotationBeanPostProcessor}
*/
@ConditionalOnMissingBean
@Bean(name = ReferenceAnnotationBeanPostProcessor.BEAN_NAME)
public ReferenceAnnotationBeanPostProcessor referenceAnnotationBeanPostProcessor() {
return new ReferenceAnnotationBeanPostProcessor();
}
/**
* Build a primary {@link PropertyResolver} bean to {@link Autowired @Autowired}
*
* @param environment {@link Environment}
* @return alias bean for {@link Environment}
* @since 2.7.3
*/
@Bean
@Primary
public PropertyResolver primaryPropertyResolver(Environment environment) {
return environment;
}
public static final String DUBBO_LOG_TRACING_SUFFIX = "log.trace";
public static final String DUBBO_LOG_TRACING_PROPERTY = DUBBO_PREFIX + PROPERTY_NAME_SEPARATOR + DUBBO_LOG_TRACING_SUFFIX;
/**
* 注册Reference构建工厂类
*
* @param env
* @return
*/
@Bean
public ReferenceBuilderFactory referenceBuilderFactory(ApplicationConfig config, PropertyResolver env) {
ReferenceBuilderFactory reference = new ReferenceBuilderFactory();
Boolean traceEnable = env.getProperty(DUBBO_LOG_TRACING_PROPERTY, Boolean.class);
if (null != traceEnable && !traceEnable) {
reference.setDefaultFilter("-logTrace");
}
return reference;
}
@Bean
@ConditionalOnProperty(prefix = DUBBO_PREFIX, name = DUBBO_LOG_TRACING_SUFFIX, havingValue = "false")
public ProviderConfig providerConfig(ApplicationConfig application, RegistryConfig registryConfig) {
ProviderConfig providerConfig = new ProviderConfig();
providerConfig.setFilter("-logTrace");
providerConfig.setRegistry(registryConfig);
return providerConfig;
}
}
package com.glsx.plat.dubbo.config;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import org.apache.dubbo.config.*;
import org.apache.dubbo.config.spring.ConfigCenterBean;
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import static org.apache.dubbo.spring.boot.util.DubboUtils.*;
/**
* Dubbo {@link ConfigurationProperties Config Properties} only used to generate JSON metadata(non-public class)
*
* @since 2.7.1
*/
//@ConfigurationProperties(DUBBO_PREFIX)
class DubboConfigurationProperties {
@NestedConfigurationProperty
private Config config = new Config();
@NestedConfigurationProperty
private Scan scan = new Scan();
// Single Config Bindings
@NestedConfigurationProperty
private ApplicationConfig application = new ApplicationConfig();
@NestedConfigurationProperty
private ModuleConfig module = new ModuleConfig();
@NestedConfigurationProperty
private RegistryConfig registry = new RegistryConfig();
@NestedConfigurationProperty
private ProtocolConfig protocol = new ProtocolConfig();
@NestedConfigurationProperty
private MonitorConfig monitor = new MonitorConfig();
@NestedConfigurationProperty
private ProviderConfig provider = new ProviderConfig();
@NestedConfigurationProperty
private ConsumerConfig consumer = new ConsumerConfig();
@NestedConfigurationProperty
private ConfigCenterBean configCenter = new ConfigCenterBean();
@NestedConfigurationProperty
private MetadataReportConfig metadataReport = new MetadataReportConfig();
// Multiple Config Bindings
private Map<String, ModuleConfig> modules = new LinkedHashMap<>();
private Map<String, RegistryConfig> registries = new LinkedHashMap<>();
private Map<String, ProtocolConfig> protocols = new LinkedHashMap<>();
private Map<String, MonitorConfig> monitors = new LinkedHashMap<>();
private Map<String, ProviderConfig> providers = new LinkedHashMap<>();
private Map<String, ConsumerConfig> consumers = new LinkedHashMap<>();
private Map<String, ConfigCenterBean> configCenters = new LinkedHashMap<>();
private Map<String, MetadataReportConfig> metadataReports = new LinkedHashMap<>();
public Config getConfig() {
return config;
}
public void setConfig(Config config) {
this.config = config;
}
public Scan getScan() {
return scan;
}
public void setScan(Scan scan) {
this.scan = scan;
}
public ApplicationConfig getApplication() {
return application;
}
public void setApplication(ApplicationConfig application) {
this.application = application;
}
public ModuleConfig getModule() {
return module;
}
public void setModule(ModuleConfig module) {
this.module = module;
}
public RegistryConfig getRegistry() {
return registry;
}
public void setRegistry(RegistryConfig registry) {
this.registry = registry;
}
public ProtocolConfig getProtocol() {
return protocol;
}
public void setProtocol(ProtocolConfig protocol) {
this.protocol = protocol;
}
public MonitorConfig getMonitor() {
return monitor;
}
public void setMonitor(MonitorConfig monitor) {
this.monitor = monitor;
}
public ProviderConfig getProvider() {
return provider;
}
public void setProvider(ProviderConfig provider) {
this.provider = provider;
}
public ConsumerConfig getConsumer() {
return consumer;
}
public void setConsumer(ConsumerConfig consumer) {
this.consumer = consumer;
}
public ConfigCenterBean getConfigCenter() {
return configCenter;
}
public void setConfigCenter(ConfigCenterBean configCenter) {
this.configCenter = configCenter;
}
public MetadataReportConfig getMetadataReport() {
return metadataReport;
}
public void setMetadataReport(MetadataReportConfig metadataReport) {
this.metadataReport = metadataReport;
}
public Map<String, ModuleConfig> getModules() {
return modules;
}
public void setModules(Map<String, ModuleConfig> modules) {
this.modules = modules;
}
public Map<String, RegistryConfig> getRegistries() {
return registries;
}
public void setRegistries(Map<String, RegistryConfig> registries) {
this.registries = registries;
}
public Map<String, ProtocolConfig> getProtocols() {
return protocols;
}
public void setProtocols(Map<String, ProtocolConfig> protocols) {
this.protocols = protocols;
}
public Map<String, MonitorConfig> getMonitors() {
return monitors;
}
public void setMonitors(Map<String, MonitorConfig> monitors) {
this.monitors = monitors;
}
public Map<String, ProviderConfig> getProviders() {
return providers;
}
public void setProviders(Map<String, ProviderConfig> providers) {
this.providers = providers;
}
public Map<String, ConsumerConfig> getConsumers() {
return consumers;
}
public void setConsumers(Map<String, ConsumerConfig> consumers) {
this.consumers = consumers;
}
public Map<String, ConfigCenterBean> getConfigCenters() {
return configCenters;
}
public void setConfigCenters(Map<String, ConfigCenterBean> configCenters) {
this.configCenters = configCenters;
}
public Map<String, MetadataReportConfig> getMetadataReports() {
return metadataReports;
}
public void setMetadataReports(Map<String, MetadataReportConfig> metadataReports) {
this.metadataReports = metadataReports;
}
static class Config {
/**
* Indicates multiple properties binding from externalized configuration or not.
*/
private boolean multiple = DEFAULT_MULTIPLE_CONFIG_PROPERTY_VALUE;
/**
* The property name of override Dubbo config
*/
private boolean override = DEFAULT_OVERRIDE_CONFIG_PROPERTY_VALUE;
public boolean isOverride() {
return override;
}
public void setOverride(boolean override) {
this.override = override;
}
public boolean isMultiple() {
return multiple;
}
public void setMultiple(boolean multiple) {
this.multiple = multiple;
}
}
static class Scan {
/**
* The basePackages to scan , the multiple-value is delimited by comma
*
* @see EnableDubbo#scanBasePackages()
*/
private Set<String> basePackages = new LinkedHashSet<>();
public Set<String> getBasePackages() {
return basePackages;
}
public void setBasePackages(Set<String> basePackages) {
this.basePackages = basePackages;
}
}
}
package com.glsx.plat.dubbo.config;
import com.alibaba.spring.context.config.ConfigurationBeanBinder;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.core.env.*;
import java.util.Map;
import static com.alibaba.spring.util.PropertySourcesUtils.getSubProperties;
import static org.apache.dubbo.spring.boot.util.DubboUtils.*;
import static org.springframework.beans.factory.config.ConfigurableBeanFactory.SCOPE_PROTOTYPE;
/**
* Dubbo Relaxed Binding Auto-{@link Configuration} for Spring Boot 2.0
*
* @see DubboRelaxedBindingAutoConfiguration
* @since 2.7.0
*/
//@Configuration
//@ConditionalOnClass(name = "org.springframework.boot.context.properties.bind.Binder")
public class DubboRelaxedBinding2AutoConfiguration {
@Bean(name = BASE_PACKAGES_PROPERTY_RESOLVER_BEAN_NAME)
public PropertyResolver dubboScanBasePackagesPropertyResolver(ConfigurableEnvironment environment) {
ConfigurableEnvironment propertyResolver = new AbstractEnvironment() {
@Override
protected void customizePropertySources(MutablePropertySources propertySources) {
Map<String, Object> dubboScanProperties = getSubProperties(environment.getPropertySources(), DUBBO_SCAN_PREFIX);
propertySources.addLast(new MapPropertySource("dubboScanProperties", dubboScanProperties));
}
};
return new DelegatingPropertyResolver(propertyResolver);
}
@ConditionalOnMissingBean(name = RELAXED_DUBBO_CONFIG_BINDER_BEAN_NAME, value = ConfigurationBeanBinder.class)
@Bean(RELAXED_DUBBO_CONFIG_BINDER_BEAN_NAME)
@Scope(scopeName = SCOPE_PROTOTYPE)
public ConfigurationBeanBinder relaxedDubboConfigBinder() {
return new BinderDubboConfigBinder();
}
}
package com.glsx.plat.dubbo.env;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.Ordered;
import org.springframework.core.env.*;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import static org.apache.dubbo.spring.boot.util.DubboUtils.*;
/**
* The lowest precedence {@link EnvironmentPostProcessor} processes
* {@link SpringApplication#setDefaultProperties(Properties) Spring Boot default properties} for Dubbo
* as late as possible before {@link ConfigurableApplicationContext#refresh() application context refresh}.
*/
public class DubboDefaultPropertiesEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered {
/**
* The name of default {@link PropertySource} defined in SpringApplication#configurePropertySources method.
*/
public static final String PROPERTY_SOURCE_NAME = "defaultProperties";
/**
* The property name of "spring.main.allow-bean-definition-overriding".
* Please refer to: https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.1-Release-Notes#bean-overriding
*/
public static final String ALLOW_BEAN_DEFINITION_OVERRIDING_PROPERTY = "spring.main.allow-bean-definition-overriding";
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
MutablePropertySources propertySources = environment.getPropertySources();
Map<String, Object> defaultProperties = createDefaultProperties(environment);
if (!CollectionUtils.isEmpty(defaultProperties)) {
addOrReplace(propertySources, defaultProperties);
}
}
@Override
public int getOrder() {
return LOWEST_PRECEDENCE;
}
private Map<String, Object> createDefaultProperties(ConfigurableEnvironment environment) {
Map<String, Object> defaultProperties = new HashMap<>();
setDubboApplicationNameProperty(environment, defaultProperties);
setDubboConfigMultipleProperty(defaultProperties);
setDubboApplicationQosEnableProperty(defaultProperties);
setAllowBeanDefinitionOverriding(defaultProperties);
return defaultProperties;
}
private void setDubboApplicationNameProperty(Environment environment, Map<String, Object> defaultProperties) {
String springApplicationName = environment.getProperty(SPRING_APPLICATION_NAME_PROPERTY);
if (StringUtils.hasLength(springApplicationName)
&& !environment.containsProperty(DUBBO_APPLICATION_NAME_PROPERTY)) {
defaultProperties.put(DUBBO_APPLICATION_NAME_PROPERTY, springApplicationName);
}
}
private void setDubboConfigMultipleProperty(Map<String, Object> defaultProperties) {
defaultProperties.put(DUBBO_CONFIG_MULTIPLE_PROPERTY, Boolean.TRUE.toString());
}
private void setDubboApplicationQosEnableProperty(Map<String, Object> defaultProperties) {
defaultProperties.put(DUBBO_APPLICATION_QOS_ENABLE_PROPERTY, Boolean.FALSE.toString());
}
/**
* Set {@link #ALLOW_BEAN_DEFINITION_OVERRIDING_PROPERTY "spring.main.allow-bean-definition-overriding"} to be
* <code>true</code> as default.
*
* @param defaultProperties the default {@link Properties properties}
* @see #ALLOW_BEAN_DEFINITION_OVERRIDING_PROPERTY
* @since 2.7.1
*/
private void setAllowBeanDefinitionOverriding(Map<String, Object> defaultProperties) {
defaultProperties.put(ALLOW_BEAN_DEFINITION_OVERRIDING_PROPERTY, Boolean.TRUE.toString());
}
/**
* Copy from BusEnvironmentPostProcessor#addOrReplace(MutablePropertySources, Map)
*
* @param propertySources {@link MutablePropertySources}
* @param map Default Dubbo Properties
*/
private void addOrReplace(MutablePropertySources propertySources,
Map<String, Object> map) {
MapPropertySource target = null;
if (propertySources.contains(PROPERTY_SOURCE_NAME)) {
PropertySource<?> source = propertySources.get(PROPERTY_SOURCE_NAME);
if (source instanceof MapPropertySource) {
target = (MapPropertySource) source;
for (String key : map.keySet()) {
if (!target.containsProperty(key)) {
target.getSource().put(key, map.get(key));
}
}
}
}
if (target == null) {
target = new MapPropertySource(PROPERTY_SOURCE_NAME, map);
}
if (!propertySources.contains(PROPERTY_SOURCE_NAME)) {
propertySources.addLast(target);
}
}
}
package com.glsx.plat.dubbo.env;
import org.apache.dubbo.spring.boot.util.DubboUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.Ordered;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;
import org.springframework.util.CollectionUtils;
import java.util.Map;
import java.util.SortedMap;
/**
* @author Alvin
* @version V1.0
* @Title: OreDubboPropertiesEnvironmentPostProcessor.java
* @Description: ore dubbo 配置处理
* @date 2020年8月28日 上午10:42:57
* @Company: didihu.com.cn
* @Copyright Copyright (c) 2020
*/
public class DubboPropertiesEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered {
/**
* Gets Logger After LoggingSystem configuration ready
*
* @see LoggingApplicationListener
*/
Logger logger = LoggerFactory.getLogger(getClass());
public static final String PROPERTY_SOURCE_NAME = "oreDubboProperties";
@Override
public int getOrder() {
return LOWEST_PRECEDENCE;
}
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment,
SpringApplication application) {
MutablePropertySources propertySources = environment.getPropertySources();
SortedMap<String, Object> dubboProperties = DubboUtils.filterDubboProperties(environment);
if (!CollectionUtils.isEmpty(dubboProperties)) {
addOrReplace(propertySources, dubboProperties);
}
if (logger.isInfoEnabled()) {
logger.info("Dubbo Config was overridden by ore externalized configuration {}", dubboProperties);
}
}
/**
* Copy from BusEnvironmentPostProcessor#addOrReplace(MutablePropertySources, Map)
*
* @param propertySources {@link MutablePropertySources}
* @param map ore Dubbo Properties
*/
private void addOrReplace(MutablePropertySources propertySources, Map<String, Object> map) {
MapPropertySource target = null;
if (propertySources.contains(PROPERTY_SOURCE_NAME)) {
PropertySource<?> source = propertySources.get(PROPERTY_SOURCE_NAME);
if (source instanceof MapPropertySource) {
target = (MapPropertySource) source;
for (String key : map.keySet()) {
if (!target.containsProperty(key)) {
target.getSource().put(key, map.get(key));
}
}
}
}
if (target == null) {
target = new MapPropertySource(PROPERTY_SOURCE_NAME, map);
}
if (!propertySources.contains(PROPERTY_SOURCE_NAME)) {
propertySources.addLast(target);
}
}
}
package com.glsx.plat.dubbo.factory;
import org.apache.dubbo.config.MethodConfig;
import org.apache.dubbo.config.RegistryConfig;
import java.util.List;
public interface ReferenceBuilder<T> {
/**
* 可选参数,服务方法调用超时时间(毫秒)
* 缺省使用dubbo:consumer的timeout
*
* @param timeout
* @return this
*/
ReferenceBuilder<T> timeout(Integer timeout);
/**
* 可选参数,服务版本,与服务提供者的版本一致
*
* @param version
* @return this
*/
ReferenceBuilder<T> version(String version);
/**
* 可选参数,启动时检查提供者是否存在,true报错,false忽略
* 缺省使用dubbo:consumer的check
*
* @param check
* @return
*/
ReferenceBuilder<T> check(Boolean check);
/**
* 可选参数,点对点直连服务提供者地址,将绕过注册中心
*
* @param url
* @return
*/
ReferenceBuilder<T> url(String url);
/**
* 可选参数,服务分组,当一个接口有多个实现,可以用分组区分,必需和服务提供方一致
*
* @param group
* @return
*/
ReferenceBuilder<T> group(String group);
/**
* 可选参数,远程服务调用重试次数,不包括第一次调用,不需要重试请设为0
* 缺省使用dubbo:consumer的retries
*
* @param retries
* @return
*/
ReferenceBuilder<T> retries(Integer retries);
/**
* 可选参数,只调用指定协议的服务提供方,其它协议忽略。
*
* @param protocol
* @return
*/
ReferenceBuilder<T> protocol(String protocol);
/**
* 可选参数,对每个提供者的最大连接数,rmi、http、hessian等短连接协议表示限制连接数,dubbo等长连接协表示建立的长连接个数
* 缺省使用dubbo:consumer的connections
*
* @param connections
* @return
*/
ReferenceBuilder<T> connections(Integer connections);
/**
* 可选参数,负载均衡策略,可选值:random,roundrobin,leastactive,分别表示:随机,轮循,最少活跃调用
* 缺省使用dubbo:consumer的loadbalance
*
* @param loadbalance
* @return
*/
ReferenceBuilder<T> loadbalance(String loadbalance);
/**
* 可选参数,是否异步执行,不可靠异步,只是忽略返回值,不阻塞执行线程
* 缺省使用dubbo:consumer的async
*
* @param async
* @return
*/
ReferenceBuilder<T> async(Boolean async);
/**
* 可选参数,选择动态代理实现策略,可选:javassist, jdk。
* 缺省为:javassist
*
* @param proxy
* @return
*/
ReferenceBuilder<T> proxy(String proxy);
/**
* 可选参数,每服务消费者每服务每方法最大并发调用数。
* 缺省为:0
*
* @param actives
* @return
*/
ReferenceBuilder<T> actives(Integer actives);
/**
* 可选参数,客户端传输类型设置,如Dubbo协议的netty或mina。
*
* @param client
* @return
*/
ReferenceBuilder<T> client(String client);
/**
* 可选参数,方法级参数配置,如设置单个方法的超时时间、重试次数等
*
* @param method
* @return
* @Description:
* @author Alvin.zengqi
* @date 2018年1月27日 下午3:21:35
*/
ReferenceBuilder<T> method(MethodConfig method);
/**
* 可选参数,方法级参数配置,如设置多个方法的超时时间、重试次数等
*
* @param methods
* @return
* @Description:
* @author Alvin.zengqi
* @date 2018年1月27日 下午3:21:35
*/
ReferenceBuilder<T> methods(List<MethodConfig> methods);
/**
* 增加过滤器配置
*
* @param filterName
* @return
*/
ReferenceBuilder<T> filter(String filterName);
/**
* 增加注册中心配置
*
* @param registry
* @return
*/
ReferenceBuilder<T> registry(RegistryConfig registry);
/**
* 增加路由标签配置
*
* @param tagName
* @return
*/
ReferenceBuilder<T> tag(String tagName);
// 构造
T build();
}
package com.glsx.plat.dubbo.factory;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.MethodConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import java.util.ArrayList;
import java.util.List;
public class ReferenceBuilderFactory {
@Autowired
private ApplicationConfig config;
@Autowired
private RegistryConfig registry;
@Autowired
private Environment env;
private String defaultFilter;
public <T> ReferenceBuilder<T> builder(Class<T> clazz) {
return new DefaultBuilder<T>(clazz);
}
private class DefaultBuilder<T> implements ReferenceBuilder<T> {
private ReferenceConfig<T> reference = new ReferenceConfig<T>();
DefaultBuilder(Class<T> clazz) {
config.setRegistry(registry);
reference.setInterface(clazz);
if (StringUtils.isNotEmpty(defaultFilter)) {
reference.setFilter(defaultFilter);
}
// 优先获取单个RPC服务直连地址,如:cn.com.glsx.***Remote.url=dubbo://127.0.0.1:20880
String url = env.getProperty(clazz.getName().concat(".url"));
if (StringUtils.isEmpty(url)) {
// 获取全局RPC服务直连地址,如:ore.dubbo.provider.url=dubbo://127.0.0.1:20880
url = env.getProperty("dubbo.provider.url");
}
reference.setUrl(url);
}
@Override
public ReferenceBuilder<T> timeout(Integer timeout) {
reference.setTimeout(timeout);
return this;
}
@Override
public ReferenceBuilder<T> version(String version) {
reference.setVersion(version);
return this;
}
@Override
public ReferenceBuilder<T> check(Boolean check) {
reference.setCheck(check);
return this;
}
@Override
public ReferenceBuilder<T> url(String url) {
reference.setUrl(url);
return this;
}
@Override
public T build() {
return reference.get();
}
@Override
public ReferenceBuilder<T> group(String group) {
reference.setGroup(group);
return this;
}
@Override
public ReferenceBuilder<T> retries(Integer retries) {
reference.setRetries(retries);
return this;
}
@Override
public ReferenceBuilder<T> protocol(String protocol) {
reference.setProtocol(protocol);
return this;
}
@Override
public ReferenceBuilder<T> connections(Integer connections) {
reference.setConnections(connections);
return this;
}
@Override
public ReferenceBuilder<T> loadbalance(String loadbalance) {
reference.setLoadbalance(loadbalance);
return this;
}
@Override
public ReferenceBuilder<T> async(Boolean async) {
reference.setAsync(async);
return this;
}
@Override
public ReferenceBuilder<T> proxy(String proxy) {
reference.setProxy(proxy);
return this;
}
@Override
public ReferenceBuilder<T> actives(Integer actives) {
reference.setActives(actives);
return this;
}
@Override
public ReferenceBuilder<T> method(MethodConfig method) {
List<MethodConfig> methods = reference.getMethods();
if (methods == null) {
methods = new ArrayList<MethodConfig>();
}
methods.add(method);
return methods(methods);
}
@Override
public ReferenceBuilder<T> methods(List<MethodConfig> methods) {
reference.setMethods(methods);
return this;
}
@Override
public ReferenceBuilder<T> filter(String filterName) {
reference.setFilter(filterName);
return this;
}
@Override
public ReferenceBuilder<T> client(String client) {
reference.setClient(client);
return this;
}
@Override
public ReferenceBuilder<T> registry(RegistryConfig registry) {
reference.setRegistry(registry);
return this;
}
@Override
public ReferenceBuilder<T> tag(String tagName) {
reference.setTag(tagName);
return this;
}
}
public String getDefaultFilter() {
return defaultFilter;
}
public void setDefaultFilter(String defaultFilter) {
this.defaultFilter = defaultFilter;
}
}
...@@ -11,46 +11,59 @@ ...@@ -11,46 +11,59 @@
<artifactId>rest-admin-elasticjob</artifactId> <artifactId>rest-admin-elasticjob</artifactId>
<properties>
<curator.version>2.12.0</curator.version>
<zookeeper.version>3.4.6</zookeeper.version>
</properties>
<dependencies> <dependencies>
<!-- 运行环境上下文 -->
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-context</artifactId>
</dependency>
<dependency> <dependency>
<groupId>com.github.kuhn-he</groupId> <groupId>com.github.kuhn-he</groupId>
<artifactId>elastic-job-lite-spring-boot-starter</artifactId> <artifactId>elastic-job-lite-spring-boot-starter</artifactId>
<version>2.1.53</version> <version>2.1.53</version>
</dependency>
<!-- <dependency>-->
<!-- <groupId>org.apache.shardingsphere.elasticjob</groupId>-->
<!-- <artifactId>elasticjob-lite-spring-boot-starter</artifactId>-->
<!-- <version>3.0.0</version>-->
<!-- </dependency>-->
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-framework</artifactId>
<exclusions> <exclusions>
<exclusion> <exclusion>
<groupId>org.apache.curator</groupId> <groupId>org.apache.zookeeper</groupId>
<artifactId>curator-recipes</artifactId> <artifactId>zookeeper</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.curator</groupId>
<artifactId>curator-framework</artifactId>
</exclusion>
<exclusion>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</exclusion> </exclusion>
</exclusions> </exclusions>
</dependency> </dependency>
<!-- zookeeper 分布式锁、注意zookeeper版本 版本限制-->
<dependency> <dependency>
<groupId>org.apache.curator</groupId> <groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId> <artifactId>curator-recipes</artifactId>
<version>2.10.0</version> <exclusions>
</dependency> <exclusion>
<groupId>org.apache.zookeeper</groupId>
<dependency> <artifactId>zookeeper</artifactId>
<groupId>org.apache.curator</groupId> </exclusion>
<artifactId>curator-framework</artifactId> </exclusions>
<version>2.10.0</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.google.guava</groupId> <groupId>org.apache.zookeeper</groupId>
<artifactId>guava</artifactId> <artifactId>zookeeper</artifactId>
<version>18.0</version> <version>${zookeeper.version}</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
</exclusions>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework</groupId> <groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId> <artifactId>spring-beans</artifactId>
......
package com.glsx.plat.job.config; package com.glsx.plat.job.config;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.dangdang.ddframe.job.config.JobCoreConfiguration;
import com.dangdang.ddframe.job.config.simple.SimpleJobConfiguration;
import com.dangdang.ddframe.job.lite.api.JobScheduler;
import com.dangdang.ddframe.job.lite.config.LiteJobConfiguration;
import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperConfiguration; import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperConfiguration;
import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperRegistryCenter; import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperRegistryCenter;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
...@@ -31,14 +26,14 @@ public class ElasticJobConfig { ...@@ -31,14 +26,14 @@ public class ElasticJobConfig {
* @param shardingTotalCount * @param shardingTotalCount
* @param shardingItemParameters * @param shardingItemParameters
*/ */
public void addSimpleJobScheduler(final Class<? extends SimpleJob> jobClass, // public void addSimpleJobScheduler(final Class<? extends SimpleJob> jobClass,
final String cron, // final String cron,
final int shardingTotalCount, // final int shardingTotalCount,
final String shardingItemParameters) { // final String shardingItemParameters) {
JobCoreConfiguration coreConfig = JobCoreConfiguration.newBuilder(jobClass.getName(), cron, shardingTotalCount).shardingItemParameters(shardingItemParameters).jobParameter("job参数").build(); // JobCoreConfiguration coreConfig = JobCoreConfiguration.newBuilder(jobClass.getName(), cron, shardingTotalCount).shardingItemParameters(shardingItemParameters).jobParameter("job参数").build();
SimpleJobConfiguration simpleJobConfig = new SimpleJobConfiguration(coreConfig, jobClass.getCanonicalName()); // SimpleJobConfiguration simpleJobConfig = new SimpleJobConfiguration(coreConfig, jobClass.getCanonicalName());
JobScheduler jobScheduler = new JobScheduler(regCenter, LiteJobConfiguration.newBuilder(simpleJobConfig).build()); // JobScheduler jobScheduler = new JobScheduler(regCenter, LiteJobConfiguration.newBuilder(simpleJobConfig).build());
jobScheduler.init(); // jobScheduler.init();
} // }
} }
\ No newline at end of file \ No newline at end of file
//package com.glsx.plat.job.config;
//
//import org.apache.shardingsphere.elasticjob.reg.base.CoordinatorRegistryCenter;
//import org.apache.shardingsphere.elasticjob.reg.zookeeper.ZookeeperConfiguration;
//import org.apache.shardingsphere.elasticjob.reg.zookeeper.ZookeeperRegistryCenter;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//
////@Configuration
//public class ZookepeerConfig {
//
// //zookeeper链接字符串 localhost:2181
// private String ZOOKEEPER_CONNECTION_STRING = "localhost:2181";
// //定时任务命名空间
// private String JOB_NAMESPACE = "elastic-job-boot-java";
//
// //zk的配置及创建注册中心
// @Bean(initMethod = "init")
// public CoordinatorRegistryCenter setUpRegistryCenter(@Value("${elaticjob.zookeeper.server-lists}") final String serverList, @Value("${elaticjob.zookeeper.namespace}") final String namespace) {
// //zk的配置
// ZookeeperConfiguration zookeeperConfiguration = new ZookeeperConfiguration(serverList, namespace);
// //设置zk超时时间
// zookeeperConfiguration.setSessionTimeoutMilliseconds(1000);
// //创建注册中心
// CoordinatorRegistryCenter zookeeperRegistryCenter = new ZookeeperRegistryCenter(zookeeperConfiguration);
// return zookeeperRegistryCenter;
// }
//
//}
//
//package org.apache.curator.framework.api;
//
///**
// * Licensed to the Apache Software Foundation (ASF) under one
// * or more contributor license agreements. See the NOTICE file
// * distributed with this work for additional information
// * regarding copyright ownership. The ASF licenses this file
// * to you under the Apache License, Version 2.0 (the
// * "License"); you may not use this file except in compliance
// * with the License. You may obtain a copy of the License at
// * <p>
// * http://www.apache.org/licenses/LICENSE-2.0
// * <p>
// * Unless required by applicable law or agreed to in writing,
// * software distributed under the License is distributed on an
// * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// * KIND, either express or implied. See the License for the
// * specific language governing permissions and limitations
// * under the License.
// */
//
//import org.apache.zookeeper.CreateMode;
//
//public interface CreateBuilderMain extends
// BackgroundPathAndBytesable<String>,
// CreateModable<ACLBackgroundPathAndBytesable<String>>,
// ACLCreateModeBackgroundPathAndBytesable<String>,
// Compressible<CreateBackgroundModeStatACLable>,
// Statable<CreateProtectACLCreateModePathAndBytesable<String>> {
// /**
// * Causes any parent nodes to get created if they haven't already been
// *
// * @return this
// */
// public ProtectACLCreateModePathAndBytesable<String> creatingParentsIfNeeded();
//
//// public ProtectACLCreateModePathAndBytesable<String> creatingParentsIfNeeded();
//
// /**
// * Causes any parent nodes to get created using {@link CreateMode#CONTAINER} if they haven't already been.
// * IMPORTANT NOTE: container creation is a new feature in recent versions of ZooKeeper.
// * If the ZooKeeper version you're using does not support containers, the parent nodes
// * are created as ordinary PERSISTENT nodes.
// *
// * @return this
// */
// public ProtectACLCreateModeStatPathAndBytesable<String> creatingParentContainersIfNeeded();
//
// /**
// * @return this
// * @deprecated this has been generalized to support all create modes. Instead, use:
// * <pre>
// * client.create().withProtection().withMode(CreateMode.EPHEMERAL_SEQUENTIAL)...
// * </pre>
// */
// @Deprecated
// public ACLPathAndBytesable<String> withProtectedEphemeralSequential();
//
// /**
// * <p>
// * Hat-tip to https://github.com/sbridges for pointing this out
// * </p>
// *
// * <p>
// * It turns out there is an edge case that exists when creating sequential-ephemeral
// * nodes. The creation can succeed on the server, but the server can crash before
// * the created node name is returned to the client. However, the ZK session is still
// * valid so the ephemeral node is not deleted. Thus, there is no way for the client to
// * determine what node was created for them.
// * </p>
// *
// * <p>
// * Even without sequential-ephemeral, however, the create can succeed on the sever
// * but the client (for various reasons) will not know it.
// * </p>
// *
// * <p>
// * Putting the create builder into protection mode works around this.
// * The name of the node that is created is prefixed with a GUID. If node creation fails
// * the normal retry mechanism will occur. On the retry, the parent path is first searched
// * for a node that has the GUID in it. If that node is found, it is assumed to be the lost
// * node that was successfully created on the first try and is returned to the caller.
// * </p>
// *
// * @return this
// */
// public ACLCreateModeStatBackgroundPathAndBytesable<String> withProtection();
//}
//
///**
// * Licensed to the Apache Software Foundation (ASF) under one
// * or more contributor license agreements. See the NOTICE file
// * distributed with this work for additional information
// * regarding copyright ownership. The ASF licenses this file
// * to you under the Apache License, Version 2.0 (the
// * "License"); you may not use this file except in compliance
// * with the License. You may obtain a copy of the License at
// * <p>
// * http://www.apache.org/licenses/LICENSE-2.0
// * <p>
// * Unless required by applicable law or agreed to in writing,
// * software distributed under the License is distributed on an
// * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// * KIND, either express or implied. See the License for the
// * specific language governing permissions and limitations
// * under the License.
// */
//
//package org.apache.curator.framework.imps;
//
//import com.google.common.annotations.VisibleForTesting;
//import com.google.common.base.Preconditions;
//import com.google.common.base.Predicate;
//import com.google.common.collect.Iterables;
//import org.apache.curator.RetryLoop;
//import org.apache.curator.drivers.OperationTrace;
//import org.apache.curator.framework.api.*;
//import org.apache.curator.framework.api.transaction.OperationType;
//import org.apache.curator.framework.api.transaction.TransactionCreateBuilder;
//import org.apache.curator.framework.api.transaction.TransactionCreateBuilder2;
//import org.apache.curator.utils.InternalACLProvider;
//import org.apache.curator.utils.ThreadUtils;
//import org.apache.curator.utils.ZKPaths;
//import org.apache.zookeeper.AsyncCallback;
//import org.apache.zookeeper.CreateMode;
//import org.apache.zookeeper.KeeperException;
//import org.apache.zookeeper.Op;
//import org.apache.zookeeper.data.ACL;
//import org.apache.zookeeper.data.Stat;
//import org.apache.zookeeper.server.DataTree;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//
//import java.util.List;
//import java.util.concurrent.Callable;
//import java.util.concurrent.Executor;
//import java.util.concurrent.atomic.AtomicBoolean;
//
//public class CreateBuilderImpl implements CreateBuilder, CreateBuilder2, BackgroundOperation<PathAndBytes>, ErrorListenerPathAndBytesable<String> {
// private final Logger log = LoggerFactory.getLogger(getClass());
// private final CuratorFrameworkImpl client;
// private final ProtectedMode protectedMode = new ProtectedMode();
// private CreateMode createMode;
// private Backgrounding backgrounding;
// private boolean createParentsIfNeeded;
// private boolean createParentsAsContainers;
// private boolean compress;
// private boolean setDataIfExists;
// private int setDataIfExistsVersion = -1;
// private ACLing acling;
// private Stat storingStat;
// private long ttl;
//
// @VisibleForTesting
// boolean failNextCreateForTesting = false;
//
// @VisibleForTesting
// static final String PROTECTED_PREFIX = "_c_";
//
// CreateBuilderImpl(CuratorFrameworkImpl client) {
// this.client = client;
// createMode = CreateMode.PERSISTENT;
// backgrounding = new Backgrounding();
// acling = new ACLing(client.getAclProvider());
// createParentsIfNeeded = false;
// createParentsAsContainers = false;
// compress = false;
// setDataIfExists = false;
// storingStat = null;
// ttl = -1;
// }
//
// public CreateBuilderImpl(CuratorFrameworkImpl client, CreateMode createMode, Backgrounding backgrounding, boolean createParentsIfNeeded, boolean createParentsAsContainers, boolean doProtected, boolean compress, boolean setDataIfExists, List<ACL> aclList, Stat storingStat, long ttl) {
// this.client = client;
// this.createMode = createMode;
// this.backgrounding = backgrounding;
// this.createParentsIfNeeded = createParentsIfNeeded;
// this.createParentsAsContainers = createParentsAsContainers;
// this.compress = compress;
// this.setDataIfExists = setDataIfExists;
// this.acling = new ACLing(client.getAclProvider(), aclList);
// this.storingStat = storingStat;
// this.ttl = ttl;
// if (doProtected) {
// protectedMode.setProtectedMode();
// }
// }
//
// public void setSetDataIfExistsVersion(int version) {
// this.setDataIfExistsVersion = version;
// }
//
// @Override
// public CreateBuilder2 orSetData() {
// return orSetData(-1);
// }
//
// @Override
// public CreateBuilder2 orSetData(int version) {
// setDataIfExists = true;
// setDataIfExistsVersion = version;
// return this;
// }
//
// @Override
// public CreateBuilderMain withTtl(long ttl) {
// Preconditions.checkState(!client.isZk34CompatibilityMode(), "TTLs are not support when running in ZooKeeper 3.4 compatibility mode");
// this.ttl = ttl;
// return this;
// }
//
// <T> TransactionCreateBuilder<T> asTransactionCreateBuilder(final T context, final CuratorMultiTransactionRecord transaction) {
// return new TransactionCreateBuilder<T>() {
// @Override
// public PathAndBytesable<T> withACL(List<ACL> aclList) {
// return withACL(aclList, false);
// }
//
// @Override
// public PathAndBytesable<T> withACL(List<ACL> aclList, boolean applyToParents) {
// CreateBuilderImpl.this.withACL(aclList, applyToParents);
// return this;
// }
//
// @Override
// public TransactionCreateBuilder2<T> withTtl(long ttl) {
// CreateBuilderImpl.this.withTtl(ttl);
// return this;
// }
//
// @Override
// public ACLPathAndBytesable<T> withMode(CreateMode mode) {
// CreateBuilderImpl.this.withMode(mode);
// return this;
// }
//
// @Override
// public ACLCreateModePathAndBytesable<T> compressed() {
// CreateBuilderImpl.this.compressed();
// return this;
// }
//
// @Override
// public T forPath(String path) throws Exception {
// return forPath(path, client.getDefaultData());
// }
//
// @Override
// public T forPath(String path, byte[] data) throws Exception {
// if (compress) {
// data = client.getCompressionProvider().compress(path, data);
// }
//
// String fixedPath = client.fixForNamespace(path);
// if (client.isZk34CompatibilityMode()) {
// transaction.add(Op.create(fixedPath, data, acling.getAclList(path), createMode), OperationType.CREATE, path);
// } else {
// transaction.add(Op.create(fixedPath, data, acling.getAclList(path), createMode), OperationType.CREATE, path);
// }
// return context;
// }
// };
// }
//
// @Override
// public CreateBackgroundModeStatACLable compressed() {
// compress = true;
// return new CreateBackgroundModeStatACLable() {
// @Override
// public CreateBackgroundModeACLable storingStatIn(Stat stat) {
// storingStat = stat;
// return asCreateBackgroundModeACLable();
// }
//
// @Override
// public ACLCreateModePathAndBytesable<String> creatingParentsIfNeeded() {
// createParentsIfNeeded = true;
// return asACLCreateModePathAndBytesable();
// }
//
// @Override
// public ACLCreateModePathAndBytesable<String> creatingParentContainersIfNeeded() {
// setCreateParentsAsContainers();
// return creatingParentsIfNeeded();
// }
//
// @Override
// public ACLPathAndBytesable<String> withProtectedEphemeralSequential() {
// return CreateBuilderImpl.this.withProtectedEphemeralSequential();
// }
//
// @Override
// public BackgroundPathAndBytesable<String> withACL(List<ACL> aclList) {
// return CreateBuilderImpl.this.withACL(aclList);
// }
//
// @Override
// public BackgroundPathAndBytesable<String> withACL(List<ACL> aclList, boolean applyToParents) {
// return CreateBuilderImpl.this.withACL(aclList, applyToParents);
// }
//
// @Override
// public ErrorListenerPathAndBytesable<String> inBackground(BackgroundCallback callback, Object context) {
// return CreateBuilderImpl.this.inBackground(callback, context);
// }
//
// @Override
// public ErrorListenerPathAndBytesable<String> inBackground(BackgroundCallback callback, Object context, Executor executor) {
// return CreateBuilderImpl.this.inBackground(callback, context, executor);
// }
//
// @Override
// public ErrorListenerPathAndBytesable<String> inBackground() {
// return CreateBuilderImpl.this.inBackground();
// }
//
// @Override
// public ErrorListenerPathAndBytesable<String> inBackground(Object context) {
// return CreateBuilderImpl.this.inBackground(context);
// }
//
// @Override
// public ErrorListenerPathAndBytesable<String> inBackground(BackgroundCallback callback) {
// return CreateBuilderImpl.this.inBackground(callback);
// }
//
// @Override
// public ErrorListenerPathAndBytesable<String> inBackground(BackgroundCallback callback, Executor executor) {
// return CreateBuilderImpl.this.inBackground(callback, executor);
// }
//
// @Override
// public ACLBackgroundPathAndBytesable<String> withMode(CreateMode mode) {
// return CreateBuilderImpl.this.withMode(mode);
// }
//
// @Override
// public String forPath(String path, byte[] data) throws Exception {
// return CreateBuilderImpl.this.forPath(path, data);
// }
//
// @Override
// public String forPath(String path) throws Exception {
// return CreateBuilderImpl.this.forPath(path);
// }
// };
// }
//
// @Override
// public ACLBackgroundPathAndBytesable<String> withACL(List<ACL> aclList) {
// return withACL(aclList, false);
// }
//
// @Override
// public ACLBackgroundPathAndBytesable<String> withACL(List<ACL> aclList, boolean applyToParents) {
// acling = new ACLing(client.getAclProvider(), aclList, applyToParents);
// return new ACLBackgroundPathAndBytesable<String>() {
// @Override
// public BackgroundPathAndBytesable<String> withACL(List<ACL> aclList) {
// return CreateBuilderImpl.this.withACL(aclList);
// }
//
// @Override
// public BackgroundPathAndBytesable<String> withACL(List<ACL> aclList, boolean applyToParents) {
// return CreateBuilderImpl.this.withACL(aclList, applyToParents);
// }
//
// @Override
// public ErrorListenerPathAndBytesable<String> inBackground() {
// return CreateBuilderImpl.this.inBackground();
// }
//
// @Override
// public ErrorListenerPathAndBytesable<String> inBackground(BackgroundCallback callback, Object context) {
// return CreateBuilderImpl.this.inBackground(callback, context);
// }
//
// @Override
// public ErrorListenerPathAndBytesable<String> inBackground(BackgroundCallback callback, Object context, Executor executor) {
// return CreateBuilderImpl.this.inBackground(callback, context, executor);
// }
//
// @Override
// public ErrorListenerPathAndBytesable<String> inBackground(Object context) {
// return CreateBuilderImpl.this.inBackground(context);
// }
//
// @Override
// public ErrorListenerPathAndBytesable<String> inBackground(BackgroundCallback callback) {
// return CreateBuilderImpl.this.inBackground(callback);
// }
//
// @Override
// public ErrorListenerPathAndBytesable<String> inBackground(BackgroundCallback callback, Executor executor) {
// return CreateBuilderImpl.this.inBackground(callback, executor);
// }
//
// @Override
// public String forPath(String path, byte[] data) throws Exception {
// return CreateBuilderImpl.this.forPath(path, data);
// }
//
// @Override
// public String forPath(String path) throws Exception {
// return CreateBuilderImpl.this.forPath(path);
// }
// };
// }
//
// @Override
// public ProtectACLCreateModeStatPathAndBytesable<String> creatingParentContainersIfNeeded() {
// setCreateParentsAsContainers();
// return creatingParentsIfNeeded();
// }
//
// private void setCreateParentsAsContainers() {
// if (client.useContainerParentsIfAvailable()) {
// createParentsAsContainers = true;
// }
// }
//
// @Override
// public ProtectACLCreateModeStatPathAndBytesable<String> creatingParentsIfNeeded() {
// createParentsIfNeeded = true;
// return new ProtectACLCreateModeStatPathAndBytesable<String>() {
// @Override
// public ACLCreateModeBackgroundPathAndBytesable<String> withProtection() {
// return CreateBuilderImpl.this.withProtection();
// }
//
// @Override
// public BackgroundPathAndBytesable<String> withACL(List<ACL> aclList) {
// return withACL(aclList, false);
// }
//
// @Override
// public BackgroundPathAndBytesable<String> withACL(List<ACL> aclList, boolean applyToParents) {
// return CreateBuilderImpl.this.withACL(aclList, applyToParents);
// }
//
// @Override
// public ErrorListenerPathAndBytesable<String> inBackground() {
// return CreateBuilderImpl.this.inBackground();
// }
//
// @Override
// public ErrorListenerPathAndBytesable<String> inBackground(Object context) {
// return CreateBuilderImpl.this.inBackground(context);
// }
//
// @Override
// public ErrorListenerPathAndBytesable<String> inBackground(BackgroundCallback callback) {
// return CreateBuilderImpl.this.inBackground(callback);
// }
//
// @Override
// public ErrorListenerPathAndBytesable<String> inBackground(BackgroundCallback callback, Object context) {
// return CreateBuilderImpl.this.inBackground(callback, context);
// }
//
// @Override
// public ErrorListenerPathAndBytesable<String> inBackground(BackgroundCallback callback, Executor executor) {
// return CreateBuilderImpl.this.inBackground(callback, executor);
// }
//
// @Override
// public ErrorListenerPathAndBytesable<String> inBackground(BackgroundCallback callback, Object context, Executor executor) {
// return CreateBuilderImpl.this.inBackground(callback, context, executor);
// }
//
// @Override
// public ACLBackgroundPathAndBytesable<String> withMode(CreateMode mode) {
// return CreateBuilderImpl.this.withMode(mode);
// }
//
// @Override
// public String forPath(String path, byte[] data) throws Exception {
// return CreateBuilderImpl.this.forPath(path, data);
// }
//
// @Override
// public String forPath(String path) throws Exception {
// return CreateBuilderImpl.this.forPath(path);
// }
//
// @Override
// public ACLBackgroundPathAndBytesable<String> storingStatIn(Stat stat) {
// storingStat = stat;
// return CreateBuilderImpl.this;
// }
// };
// }
//
// @Override
// public ACLCreateModeStatBackgroundPathAndBytesable<String> withProtection() {
// protectedMode.setProtectedMode();
// return asACLCreateModeStatBackgroundPathAndBytesable();
// }
//
// @Override
// public ACLPathAndBytesable<String> withProtectedEphemeralSequential() {
// protectedMode.setProtectedMode();
// createMode = CreateMode.EPHEMERAL_SEQUENTIAL;
//
// return new ACLPathAndBytesable<String>() {
// @Override
// public PathAndBytesable<String> withACL(List<ACL> aclList) {
// return CreateBuilderImpl.this.withACL(aclList);
// }
//
// @Override
// public PathAndBytesable<String> withACL(List<ACL> aclList, boolean applyToParents) {
// return CreateBuilderImpl.this.withACL(aclList, applyToParents);
// }
//
// @Override
// public String forPath(String path, byte[] data) throws Exception {
// return CreateBuilderImpl.this.forPath(path, data);
// }
//
// @Override
// public String forPath(String path) throws Exception {
// return CreateBuilderImpl.this.forPath(path);
// }
// };
// }
//
// @Override
// public ACLBackgroundPathAndBytesable<String> withMode(CreateMode mode) {
// createMode = mode;
// return this;
// }
//
// @Override
// public ErrorListenerPathAndBytesable<String> inBackground(BackgroundCallback callback, Object context) {
// backgrounding = new Backgrounding(callback, context);
// return this;
// }
//
// @Override
// public ErrorListenerPathAndBytesable<String> inBackground(BackgroundCallback callback, Object context, Executor executor) {
// backgrounding = new Backgrounding(client, callback, context, executor);
// return this;
// }
//
// @Override
// public ErrorListenerPathAndBytesable<String> inBackground(BackgroundCallback callback) {
// backgrounding = new Backgrounding(callback);
// return this;
// }
//
// @Override
// public ErrorListenerPathAndBytesable<String> inBackground(BackgroundCallback callback, Executor executor) {
// backgrounding = new Backgrounding(client, callback, executor);
// return this;
// }
//
// @Override
// public ErrorListenerPathAndBytesable<String> inBackground() {
// backgrounding = new Backgrounding(true);
// return this;
// }
//
// @Override
// public ErrorListenerPathAndBytesable<String> inBackground(Object context) {
// backgrounding = new Backgrounding(context);
// return this;
// }
//
// @Override
// public PathAndBytesable<String> withUnhandledErrorListener(UnhandledErrorListener listener) {
// backgrounding = new Backgrounding(backgrounding, listener);
// return this;
// }
//
// @Override
// public String forPath(String path) throws Exception {
// return forPath(path, client.getDefaultData());
// }
//
// @Override
// public String forPath(final String givenPath, byte[] data) throws Exception {
// if (compress) {
// data = client.getCompressionProvider().compress(givenPath, data);
// }
//
// final String adjustedPath = adjustPath(client.fixForNamespace(givenPath, createMode.isSequential()));
// List<ACL> aclList = acling.getAclList(adjustedPath);
// client.getSchemaSet().getSchema(givenPath).validateCreate(createMode, givenPath, data, aclList);
//
// String returnPath = null;
// if (backgrounding.inBackground()) {
// pathInBackground(adjustedPath, data, givenPath);
// } else {
// String path = protectedPathInForeground(adjustedPath, data, aclList);
// returnPath = client.unfixForNamespace(path);
// }
// return returnPath;
// }
//
// private String protectedPathInForeground(String adjustedPath, byte[] data, List<ACL> aclList) throws Exception {
// try {
// return pathInForeground(adjustedPath, data, aclList);
// } catch (Exception e) {
// ThreadUtils.checkInterrupted(e);
// if ((e instanceof KeeperException.ConnectionLossException ||
// !(e instanceof KeeperException)) && protectedMode.doProtected()) {
// /*
// * CURATOR-45 + CURATOR-79: we don't know if the create operation was successful or not,
// * register the znode to be sure it is deleted later.
// */
// new FindAndDeleteProtectedNodeInBackground(client, ZKPaths.getPathAndNode(adjustedPath).getPath(), protectedMode.protectedId()).execute();
// /*
// * The current UUID is scheduled to be deleted, it is not safe to use it again.
// * If this builder is used again later create a new UUID
// */
// protectedMode.resetProtectedId();
// }
//
// throw e;
// }
// }
//
// @Override
// public void performBackgroundOperation(final OperationAndData<PathAndBytes> operationAndData) throws Exception {
// try {
// final OperationTrace trace = client.getZookeeperClient().startAdvancedTracer("CreateBuilderImpl-Background");
// final byte[] data = operationAndData.getData().getData();
//
// final CompatibleCreateCallback mainCallback = new CompatibleCreateCallback() {
// @Override
// public void processResult(int rc, String path, Object ctx, String name, Stat stat) {
// trace.setReturnCode(rc).setRequestBytesLength(data).setPath(path).commit();
//
// if ((stat != null) && (storingStat != null)) {
// DataTree.copyStat(stat, storingStat);
// }
//
// if ((rc == KeeperException.Code.NONODE.intValue()) && createParentsIfNeeded) {
// backgroundCreateParentsThenNode(client, operationAndData, operationAndData.getData().getPath(), backgrounding, acling.getACLProviderForParents(), createParentsAsContainers);
// } else if ((rc == KeeperException.Code.NODEEXISTS.intValue()) && setDataIfExists) {
// backgroundSetData(client, operationAndData, operationAndData.getData().getPath(), backgrounding);
// } else {
// sendBackgroundResponse(rc, path, ctx, name, stat, operationAndData);
// }
// }
// };
//
// if (client.isZk34CompatibilityMode()) {
// AsyncCallback.StringCallback stringCallback = new AsyncCallback.StringCallback() {
// @Override
// public void processResult(int rc, String path, Object ctx, String name) {
// mainCallback.processResult(rc, path, ctx, name, null);
// }
// };
// client.getZooKeeper().create
// (
// operationAndData.getData().getPath(),
// data,
// acling.getAclList(operationAndData.getData().getPath()),
// createMode,
// stringCallback,
// backgrounding.getContext()
// );
// } else {
// CreateZK35.create
// (
// client.getZooKeeper(),
// operationAndData.getData().getPath(),
// data,
// acling.getAclList(operationAndData.getData().getPath()),
// createMode,
// mainCallback,
// backgrounding.getContext(),
// ttl
// );
// }
// } catch (Throwable e) {
// backgrounding.checkError(e, null);
// }
// }
//
// @Override
// public CreateProtectACLCreateModePathAndBytesable<String> storingStatIn(Stat stat) {
// storingStat = stat;
//
// return new CreateProtectACLCreateModePathAndBytesable<String>() {
//
// @Override
// public BackgroundPathAndBytesable<String> withACL(List<ACL> aclList) {
// return CreateBuilderImpl.this.withACL(aclList);
// }
//
// @Override
// public BackgroundPathAndBytesable<String> withACL(List<ACL> aclList, boolean applyToParents) {
// return CreateBuilderImpl.this.withACL(aclList, applyToParents);
// }
//
// @Override
// public ErrorListenerPathAndBytesable<String> inBackground() {
// return CreateBuilderImpl.this.inBackground();
// }
//
// @Override
// public ErrorListenerPathAndBytesable<String> inBackground(Object context) {
// return CreateBuilderImpl.this.inBackground(context);
// }
//
// @Override
// public ErrorListenerPathAndBytesable<String> inBackground(BackgroundCallback callback) {
// return CreateBuilderImpl.this.inBackground(callback);
// }
//
// @Override
// public ErrorListenerPathAndBytesable<String> inBackground(BackgroundCallback callback, Object context) {
// return CreateBuilderImpl.this.inBackground(callback, context);
// }
//
// @Override
// public ErrorListenerPathAndBytesable<String> inBackground(BackgroundCallback callback, Executor executor) {
// return CreateBuilderImpl.this.inBackground(callback, executor);
// }
//
// @Override
// public ErrorListenerPathAndBytesable<String> inBackground(BackgroundCallback callback, Object context,
// Executor executor) {
// return CreateBuilderImpl.this.inBackground(callback, context, executor);
// }
//
// @Override
// public String forPath(String path, byte[] data) throws Exception {
// return CreateBuilderImpl.this.forPath(path, data);
// }
//
// @Override
// public String forPath(String path) throws Exception {
// return CreateBuilderImpl.this.forPath(path);
// }
//
// @Override
// public ACLBackgroundPathAndBytesable<String> withMode(CreateMode mode) {
// return CreateBuilderImpl.this.withMode(mode);
// }
//
// @Override
// public ACLCreateModeBackgroundPathAndBytesable<String> withProtection() {
// return CreateBuilderImpl.this.withProtection();
// }
//
// @Override
// public ProtectACLCreateModePathAndBytesable<String> creatingParentsIfNeeded() {
// return CreateBuilderImpl.this.creatingParentsIfNeeded();
// }
//
// @Override
// public ProtectACLCreateModePathAndBytesable<String> creatingParentContainersIfNeeded() {
// return CreateBuilderImpl.this.creatingParentContainersIfNeeded();
// }
// };
// }
//
// private static String getProtectedPrefix(String protectedId) {
// return PROTECTED_PREFIX + protectedId + "-";
// }
//
// static <T> void backgroundCreateParentsThenNode(final CuratorFrameworkImpl client, final OperationAndData<T> mainOperationAndData, final String path, Backgrounding backgrounding, final InternalACLProvider aclProvider, final boolean createParentsAsContainers) {
// BackgroundOperation<T> operation = new BackgroundOperation<T>() {
// @Override
// public void performBackgroundOperation(OperationAndData<T> dummy) throws Exception {
// try {
// ZKPaths.mkdirs(client.getZooKeeper(), path, false, aclProvider, createParentsAsContainers);
// } catch (KeeperException e) {
// if (!RetryLoop.isRetryException(e)) {
// throw e;
// }
// // otherwise safe to ignore as it will get retried
// }
// client.queueOperation(mainOperationAndData);
// }
// };
// OperationAndData<T> parentOperation = new OperationAndData<>(operation, mainOperationAndData.getData(), null, null, backgrounding.getContext(), null);
// client.queueOperation(parentOperation);
// }
//
// private void backgroundSetData(final CuratorFrameworkImpl client, final OperationAndData<PathAndBytes> mainOperationAndData, final String path, final Backgrounding backgrounding) {
// final AsyncCallback.StatCallback statCallback = new AsyncCallback.StatCallback() {
// @Override
// public void processResult(int rc, String path, Object ctx, Stat stat) {
// if (rc == KeeperException.Code.NONODE.intValue()) {
// client.queueOperation(mainOperationAndData); // try to create it again
// } else {
// sendBackgroundResponse(rc, path, ctx, path, stat, mainOperationAndData);
// }
// }
// };
// BackgroundOperation<PathAndBytes> operation = new BackgroundOperation<PathAndBytes>() {
// @Override
// public void performBackgroundOperation(OperationAndData<PathAndBytes> op) throws Exception {
// try {
// client.getZooKeeper().setData(path, mainOperationAndData.getData().getData(), setDataIfExistsVersion, statCallback, backgrounding.getContext());
// } catch (KeeperException e) {
// // ignore
// }
// }
// };
// client.queueOperation(new OperationAndData<>(operation, null, null, null, null, null));
// }
//
// private void sendBackgroundResponse(int rc, String path, Object ctx, String name, Stat stat, OperationAndData<PathAndBytes> operationAndData) {
// path = client.unfixForNamespace(path);
// name = client.unfixForNamespace(name);
//
// CuratorEvent event = new CuratorEventImpl(client, CuratorEventType.CREATE, rc, path, name, ctx, stat, null, null, null, null, null);
// client.processBackgroundOperation(operationAndData, event);
// }
//
// private ACLCreateModePathAndBytesable<String> asACLCreateModePathAndBytesable() {
// return new ACLCreateModePathAndBytesable<String>() {
// @Override
// public PathAndBytesable<String> withACL(List<ACL> aclList) {
// return CreateBuilderImpl.this.withACL(aclList);
// }
//
// @Override
// public PathAndBytesable<String> withACL(List<ACL> aclList, boolean applyToParents) {
// CreateBuilderImpl.this.withACL(aclList, applyToParents);
// return this;
// }
//
// @Override
// public ACLPathAndBytesable<String> withMode(CreateMode mode) {
// createMode = mode;
// return new ACLPathAndBytesable<String>() {
// @Override
// public PathAndBytesable<String> withACL(List<ACL> aclList) {
// return CreateBuilderImpl.this.withACL(aclList);
// }
//
// @Override
// public PathAndBytesable<String> withACL(List<ACL> aclList, boolean applyToParents) {
// return CreateBuilderImpl.this.withACL(aclList, applyToParents);
// }
//
// @Override
// public String forPath(String path, byte[] data) throws Exception {
// return CreateBuilderImpl.this.forPath(path, data);
// }
//
// @Override
// public String forPath(String path) throws Exception {
// return CreateBuilderImpl.this.forPath(path);
// }
// };
// }
//
// @Override
// public String forPath(String path, byte[] data) throws Exception {
// return CreateBuilderImpl.this.forPath(path, data);
// }
//
// @Override
// public String forPath(String path) throws Exception {
// return CreateBuilderImpl.this.forPath(path);
// }
// };
// }
//
// private CreateBackgroundModeACLable asCreateBackgroundModeACLable() {
// return new CreateBackgroundModeACLable() {
//
// @Override
// public BackgroundPathAndBytesable<String> withACL(List<ACL> aclList) {
// return CreateBuilderImpl.this.withACL(aclList);
// }
//
// @Override
// public BackgroundPathAndBytesable<String> withACL(List<ACL> aclList, boolean applyToParents) {
// return CreateBuilderImpl.this.withACL(aclList, applyToParents);
// }
//
// @Override
// public ACLBackgroundPathAndBytesable<String> withMode(CreateMode mode) {
// return CreateBuilderImpl.this.withMode(mode);
// }
//
// @Override
// public String forPath(String path) throws Exception {
// return CreateBuilderImpl.this.forPath(path);
// }
//
// @Override
// public String forPath(String path, byte[] data) throws Exception {
// return CreateBuilderImpl.this.forPath(path, data);
// }
//
// @Override
// public ErrorListenerPathAndBytesable<String> inBackground(BackgroundCallback callback, Object context, Executor executor) {
// return CreateBuilderImpl.this.inBackground(callback, context, executor);
// }
//
// @Override
// public ErrorListenerPathAndBytesable<String> inBackground(BackgroundCallback callback, Executor executor) {
// return CreateBuilderImpl.this.inBackground(callback, executor);
// }
//
// @Override
// public ErrorListenerPathAndBytesable<String> inBackground(BackgroundCallback callback, Object context) {
// return CreateBuilderImpl.this.inBackground(callback, context);
// }
//
// @Override
// public ErrorListenerPathAndBytesable<String> inBackground(BackgroundCallback callback) {
// return CreateBuilderImpl.this.inBackground(callback);
// }
//
// @Override
// public ErrorListenerPathAndBytesable<String> inBackground(Object context) {
// return CreateBuilderImpl.this.inBackground(context);
// }
//
// @Override
// public ErrorListenerPathAndBytesable<String> inBackground() {
// return CreateBuilderImpl.this.inBackground();
// }
//
// @Override
// public ACLPathAndBytesable<String> withProtectedEphemeralSequential() {
// return CreateBuilderImpl.this.withProtectedEphemeralSequential();
// }
//
// @Override
// public ACLCreateModePathAndBytesable<String> creatingParentsIfNeeded() {
// createParentsIfNeeded = true;
// return asACLCreateModePathAndBytesable();
// }
//
// @Override
// public ACLCreateModePathAndBytesable<String> creatingParentContainersIfNeeded() {
// setCreateParentsAsContainers();
// return asACLCreateModePathAndBytesable();
// }
// };
// }
//
// private ACLCreateModeStatBackgroundPathAndBytesable<String> asACLCreateModeStatBackgroundPathAndBytesable() {
// return new ACLCreateModeStatBackgroundPathAndBytesable<String>() {
// @Override
// public BackgroundPathAndBytesable<String> withACL(List<ACL> aclList) {
// return CreateBuilderImpl.this.withACL(aclList);
// }
//
// @Override
// public BackgroundPathAndBytesable<String> withACL(List<ACL> aclList, boolean applyToParents) {
// CreateBuilderImpl.this.withACL(aclList, applyToParents);
// return this;
// }
//
// @Override
// public ErrorListenerPathAndBytesable<String> inBackground() {
// return CreateBuilderImpl.this.inBackground();
// }
//
// @Override
// public ErrorListenerPathAndBytesable<String> inBackground(BackgroundCallback callback, Object context, Executor executor) {
// return CreateBuilderImpl.this.inBackground(callback, context, executor);
// }
//
// @Override
// public ErrorListenerPathAndBytesable<String> inBackground(BackgroundCallback callback, Executor executor) {
// return CreateBuilderImpl.this.inBackground(callback, executor);
// }
//
// @Override
// public ErrorListenerPathAndBytesable<String> inBackground(BackgroundCallback callback, Object context) {
// return CreateBuilderImpl.this.inBackground(callback, context);
// }
//
// @Override
// public ErrorListenerPathAndBytesable<String> inBackground(BackgroundCallback callback) {
// return CreateBuilderImpl.this.inBackground(callback);
// }
//
// @Override
// public ErrorListenerPathAndBytesable<String> inBackground(Object context) {
// return CreateBuilderImpl.this.inBackground(context);
// }
//
// @Override
// public String forPath(String path) throws Exception {
// return CreateBuilderImpl.this.forPath(path);
// }
//
// @Override
// public String forPath(String path, byte[] data) throws Exception {
// return CreateBuilderImpl.this.forPath(path, data);
// }
//
// @Override
// public ACLBackgroundPathAndBytesable<String> withMode(CreateMode mode) {
// return CreateBuilderImpl.this.withMode(mode);
// }
//
// @Override
// public ACLCreateModeBackgroundPathAndBytesable<String> storingStatIn(Stat stat) {
// storingStat = stat;
// return CreateBuilderImpl.this;
// }
// };
// }
//
// @VisibleForTesting
// volatile boolean debugForceFindProtectedNode = false;
//
// private void pathInBackground(final String path, final byte[] data, final String givenPath) {
// final AtomicBoolean firstTime = new AtomicBoolean(true);
// OperationAndData<PathAndBytes> operationAndData = new OperationAndData<PathAndBytes>(this, new PathAndBytes(path, data), backgrounding.getCallback(),
// new OperationAndData.ErrorCallback<PathAndBytes>() {
// public void retriesExhausted(OperationAndData<PathAndBytes> operationAndData) {
// if (protectedMode.doProtected()) {
// // all retries have failed, findProtectedNodeInForeground(..) included, schedule a clean up
// new FindAndDeleteProtectedNodeInBackground(client, ZKPaths.getPathAndNode(path).getPath(), protectedMode.protectedId()).execute();
// // assign a new id if this builder is used again later
// protectedMode.resetProtectedId();
// }
// }
// },
// backgrounding.getContext(),
// null) {
// @Override
// void callPerformBackgroundOperation() throws Exception {
// boolean callSuper = true;
// boolean localFirstTime = firstTime.getAndSet(false) && !debugForceFindProtectedNode;
//
// protectedMode.checkSetSessionId(client, createMode);
// if (!localFirstTime && protectedMode.doProtected()) {
// debugForceFindProtectedNode = false;
// String createdPath = null;
// try {
// createdPath = findProtectedNodeInForeground(path);
// } catch (KeeperException.ConnectionLossException e) {
// sendBackgroundResponse(KeeperException.Code.CONNECTIONLOSS.intValue(), path, backgrounding.getContext(), null, null, this);
// callSuper = false;
// }
// if (createdPath != null) {
// try {
// sendBackgroundResponse(KeeperException.Code.OK.intValue(), createdPath, backgrounding.getContext(), createdPath, null, this);
// } catch (Exception e) {
// ThreadUtils.checkInterrupted(e);
// client.logError("Processing protected create for path: " + givenPath, e);
// }
// callSuper = false;
// }
// }
//
// if (failNextCreateForTesting) {
// failNextCreateForTesting = false;
// pathInForeground(path, data, acling.getAclList(path)); // simulate success on server without notification to client
// throw new KeeperException.ConnectionLossException();
// }
//
// if (callSuper) {
// super.callPerformBackgroundOperation();
// }
// }
// };
// client.processBackgroundOperation(operationAndData, null);
// }
//
// private String pathInForeground(final String path, final byte[] data, final List<ACL> aclList) throws Exception {
// OperationTrace trace = client.getZookeeperClient().startAdvancedTracer("CreateBuilderImpl-Foreground");
//
// final AtomicBoolean firstTime = new AtomicBoolean(true);
// String returnPath = RetryLoop.callWithRetry
// (
// client.getZookeeperClient(),
// new Callable<String>() {
// @Override
// public String call() throws Exception {
// boolean localFirstTime = firstTime.getAndSet(false) && !debugForceFindProtectedNode;
// protectedMode.checkSetSessionId(client, createMode);
//
// String createdPath = null;
// if (!localFirstTime && protectedMode.doProtected()) {
// debugForceFindProtectedNode = false;
// createdPath = findProtectedNodeInForeground(path);
// }
//
// if (createdPath == null) {
// try {
//// if (client.isZk34CompatibilityMode()) {
//// createdPath = client.getZooKeeper().create(path, data, aclList, createMode);
//// } else {
//// createdPath = client.getZooKeeper().create(path, data, aclList, createMode);
//// }
// createdPath = client.getZooKeeper().create(path, data, acling.getAclList(path), createMode);
// } catch (KeeperException.NoNodeException e) {
// if (createParentsIfNeeded) {
// ZKPaths.mkdirs(client.getZooKeeper(), path, false, acling.getACLProviderForParents(), createParentsAsContainers);
// if (client.isZk34CompatibilityMode()) {
// createdPath = client.getZooKeeper().create(path, data, acling.getAclList(path), createMode);
// } else {
// createdPath = client.getZooKeeper().create(path, data, acling.getAclList(path), createMode);
// }
// } else {
// throw e;
// }
// } catch (KeeperException.NodeExistsException e) {
// if (setDataIfExists) {
// Stat setStat = client.getZooKeeper().setData(path, data, setDataIfExistsVersion);
// if (storingStat != null) {
// DataTree.copyStat(setStat, storingStat);
// }
// createdPath = path;
// } else {
// throw e;
// }
// }
// }
//
// if (failNextCreateForTesting) {
// failNextCreateForTesting = false;
// throw new KeeperException.ConnectionLossException();
// }
// return createdPath;
// }
// }
// );
//
// trace.setRequestBytesLength(data).setPath(path).commit();
// return returnPath;
// }
//
// private String findProtectedNodeInForeground(final String path) throws Exception {
// OperationTrace trace = client.getZookeeperClient().startAdvancedTracer("CreateBuilderImpl-findProtectedNodeInForeground");
//
// String returnPath = RetryLoop.callWithRetry
// (
// client.getZookeeperClient(),
// new Callable<String>() {
// @Override
// public String call() throws Exception {
// String foundNode = null;
// try {
// final ZKPaths.PathAndNode pathAndNode = ZKPaths.getPathAndNode(path);
// List<String> children = client.getZooKeeper().getChildren(pathAndNode.getPath(), false);
//
// foundNode = findNode(children, pathAndNode.getPath(), protectedMode.protectedId());
// log.debug("Protected mode findNode result: {}", foundNode);
//
// foundNode = protectedMode.validateFoundNode(client, createMode, foundNode);
// } catch (KeeperException.NoNodeException ignore) {
// // ignore
// }
// return foundNode;
// }
// }
// );
//
// trace.setPath(path).commit();
// return returnPath;
// }
//
// @VisibleForTesting
// String adjustPath(String path) throws Exception {
// if (protectedMode.doProtected()) {
// ZKPaths.PathAndNode pathAndNode = ZKPaths.getPathAndNode(path);
// String name = getProtectedPrefix(protectedMode.protectedId()) + pathAndNode.getNode();
// path = ZKPaths.makePath(pathAndNode.getPath(), name);
// }
// return path;
// }
//
// /**
// * Attempt to find the znode that matches the given path and protected id
// *
// * @param children a list of candidates znodes
// * @param path the path
// * @param protectedId the protected id
// * @return the absolute path of the znode or <code>null</code> if it is not found
// */
// static String findNode(final List<String> children, final String path, final String protectedId) {
// final String protectedPrefix = getProtectedPrefix(protectedId);
// String foundNode = Iterables.find
// (
// children,
// new Predicate<String>() {
// @Override
// public boolean apply(String node) {
// return node.startsWith(protectedPrefix);
// }
// },
// null
// );
// if (foundNode != null) {
// foundNode = ZKPaths.makePath(path, foundNode);
// }
// return foundNode;
// }
//}
...@@ -41,10 +41,6 @@ ...@@ -41,10 +41,6 @@
<artifactId>jakarta.servlet-api</artifactId> <artifactId>jakarta.servlet-api</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.netflix.ribbon</groupId>
<artifactId>ribbon-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId> <groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId> <artifactId>spring-tx</artifactId>
</dependency> </dependency>
......
package com.glsx.plat.exception; package com.glsx.plat.exception;
import com.glsx.plat.core.web.R; import com.glsx.plat.core.web.R;
import com.netflix.client.ClientException;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.MDC; import org.slf4j.MDC;
...@@ -186,12 +185,6 @@ public class GlobalRExceptionHandler { ...@@ -186,12 +185,6 @@ public class GlobalRExceptionHandler {
return R.error(e.getCode(), e.getMsg()); return R.error(e.getCode(), e.getMsg());
} }
@ExceptionHandler(ClientException.class)
public R handleClientException(ClientException e) {
saveException(e, ExceptionLevel.fatal);
return R.error(e.getErrorCode(), e.getErrorMessage());
}
/** /**
* 未识别异常 * 未识别异常
* *
......
package com.glsx.plat.exception;
import com.glsx.plat.core.web.OpenApiResult;
public class OpenApiResultException extends RuntimeException {
protected OpenApiResult r;
protected static final int MIN_AUTO_CODE = 40000;
protected OpenApiResultException(OpenApiResultException parent) {
if (parent != null) {
this.r = parent.r;
}
}
/**
* 内部系统用,对外api接口不能使用随机错误码
*
* @param message
* @return
*/
public static OpenApiResultException create(String message) {
int value = (int) (MIN_AUTO_CODE + Math.round((Integer.MAX_VALUE - MIN_AUTO_CODE) * Math.random()));
return create(value, message);
}
/**
* 返回码为整型
*
* @param returnCode
* @param message
* @return
*/
public static OpenApiResultException create(int returnCode, String message) {
OpenApiResultException businessException = new OpenApiResultException(null);
businessException.r = OpenApiResult.failure(String.valueOf(returnCode), message);
return businessException;
}
/**
* 返回码可以为字符串型
*
* @param returnCode
* @param message
* @return
*/
public static OpenApiResultException create(String returnCode, String message) {
OpenApiResultException businessException = new OpenApiResultException(null);
businessException.r = OpenApiResult.failure(returnCode, message);
return businessException;
}
public static OpenApiResultException create(OpenApiResult r) {
OpenApiResultException businessException = new OpenApiResultException(null);
businessException.r = r;
return businessException;
}
@Override
public String getMessage() {
return r.getDesc();
}
public OpenApiResult getResultEntity() {
return r;
}
}
package com.glsx.plat.exception; package com.glsx.plat.exception;
import lombok.Getter; import lombok.Data;
import lombok.Setter; import lombok.extern.slf4j.Slf4j;
import java.io.Serializable; import java.io.Serializable;
/** /**
* @author payu * @author payu
*/ */
@Setter @Slf4j
@Getter @Data
public class ServiceException extends RuntimeException implements Serializable { public class ServiceException extends RuntimeException implements Serializable {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
...@@ -17,11 +17,15 @@ public class ServiceException extends RuntimeException implements Serializable { ...@@ -17,11 +17,15 @@ public class ServiceException extends RuntimeException implements Serializable {
private String msg; private String msg;
private String code; private String code;
public ServiceException(String code, String msg) {
super(msg);
this.code = code;
this.msg = msg;
}
public static ServiceException create(String code, String msg) { public static ServiceException create(String code, String msg) {
ServiceException serviceException = new ServiceException(); log.error("Service RuntimeException {} {}", code, msg);
serviceException.setCode(code); return new ServiceException(code, msg);
serviceException.setMsg(msg);
return serviceException;
} }
} }
...@@ -11,55 +11,23 @@ ...@@ -11,55 +11,23 @@
<artifactId>rest-admin-feign</artifactId> <artifactId>rest-admin-feign</artifactId>
<properties>
<feign.form.version>3.8.0</feign.form.version>
</properties>
<dependencies> <dependencies>
<!-- feign -->
<dependency> <dependency>
<groupId>org.springframework.cloud</groupId> <groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId> <artifactId>spring-cloud-starter-openfeign</artifactId>
<exclusions>
<exclusion>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-sentinel</artifactId>
<scope>compile</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>io.github.openfeign</groupId> <groupId>io.github.openfeign</groupId>
<artifactId>feign-httpclient</artifactId> <artifactId>feign-httpclient</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>io.github.openfeign</groupId> <groupId>io.github.openfeign</groupId>
<artifactId>feign-okhttp</artifactId> <artifactId>feign-okhttp</artifactId>
</dependency> </dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-gson</artifactId>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
<!--json-->
<dependency> <dependency>
<groupId>com.alibaba</groupId> <groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId> <artifactId>fastjson</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.glsx</groupId> <groupId>com.glsx</groupId>
<artifactId>rest-admin-exception</artifactId> <artifactId>rest-admin-exception</artifactId>
......
package com.alibaba.cloud.sentinel.feign;
import com.glsx.plat.feign.fallback.FunFallbackFactory;
import feign.Contract;
import feign.Feign;
import feign.InvocationHandlerFactory;
import feign.Target;
import feign.hystrix.FallbackFactory;
import lombok.SneakyThrows;
import org.springframework.beans.BeansException;
import org.springframework.cloud.openfeign.FeignContext;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.util.ReflectionUtils;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Map;
public class FunSentinelFeign {
public static Builder builder() {
return new Builder();
}
public static final class Builder extends Feign.Builder implements ApplicationContextAware {
private Contract contract = new Contract.Default();
private ApplicationContext applicationContext;
private FeignContext feignContext;
@Override
public Feign.Builder invocationHandlerFactory(
InvocationHandlerFactory invocationHandlerFactory) {
throw new UnsupportedOperationException();
}
@Override
public Builder contract(Contract contract) {
this.contract = contract;
return this;
}
@Override
public Feign build() {
super.invocationHandlerFactory(new InvocationHandlerFactory() {
@SneakyThrows
@Override
public InvocationHandler create(Target target, Map<Method, MethodHandler> dispatch) {
Object feignClientFactoryBean = Builder.this.applicationContext
.getBean("&" + target.type().getName());
Class fallback = (Class) getFieldValue(feignClientFactoryBean,
"fallback");
Class fallbackFactory = (Class) getFieldValue(feignClientFactoryBean,
"fallbackFactory");
String name = (String) getFieldValue(feignClientFactoryBean, "name");
Object fallbackInstance;
FallbackFactory fallbackFactoryInstance;
// check fallback and fallbackFactory properties
// //获取指定的构造方法
// Constructor<SentinelInvocationHandler> constructor = SentinelInvocationHandler.class.
// getDeclaredConstructor(Target.class, Map.class, FallbackFactory.class);
// constructor.setAccessible(true);
// if (void.class != fallback) {
// fallbackInstance = getFromContext(name, "fallback", fallback,
// target.type());
// return constructor.newInstance(target, dispatch, new FallbackFactory.Default(fallbackInstance));
// }
// if (void.class != fallbackFactory) {
// fallbackFactoryInstance = (FallbackFactory) getFromContext(name,
// "fallbackFactory", fallbackFactory,
// FallbackFactory.class);
// return constructor.newInstance(target, dispatch, fallbackFactoryInstance);
// }
// // 默认的 fallbackFactory
// FunFallbackFactory funFallbackFactory = new FunFallbackFactory(target);
// return constructor.newInstance(target, dispatch, funFallbackFactory);
if (void.class != fallback) {
fallbackInstance = getFromContext(name, "fallback", fallback,
target.type());
return new SentinelInvocationHandler(target, dispatch,
new FallbackFactory.Default(fallbackInstance));
}
if (void.class != fallbackFactory) {
fallbackFactoryInstance = (FallbackFactory) getFromContext(name,
"fallbackFactory", fallbackFactory,
FallbackFactory.class);
return new SentinelInvocationHandler(target, dispatch,
fallbackFactoryInstance);
}
// 默认的 fallbackFactory
FunFallbackFactory funFallbackFactory = new FunFallbackFactory(target);
return new SentinelInvocationHandler(target, dispatch, funFallbackFactory);
}
private Object getFromContext(String name, String type, Class fallbackType, Class targetType) {
Object fallbackInstance = feignContext.getInstance(name, fallbackType);
if (fallbackInstance == null) {
throw new IllegalStateException(String.format(
"No %s instance of type %s found for feign client %s",
type, fallbackType, name));
}
if (!targetType.isAssignableFrom(fallbackType)) {
throw new IllegalStateException(String.format(
"Incompatible %s instance. Fallback/fallbackFactory of type %s is not assignable to %s for feign client %s",
type, fallbackType, targetType, name));
}
return fallbackInstance;
}
});
super.contract(new SentinelContractHolder(contract));
return super.build();
}
private Object getFieldValue(Object instance, String fieldName) {
Field field = ReflectionUtils.findField(instance.getClass(), fieldName);
field.setAccessible(true);
try {
return field.get(instance);
} catch (IllegalAccessException e) {
// ignore
}
return null;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
this.applicationContext = applicationContext;
feignContext = this.applicationContext.getBean(FeignContext.class);
}
}
}
\ No newline at end of file \ No newline at end of file
...@@ -3,16 +3,23 @@ package com.glsx.plat.feign.config; ...@@ -3,16 +3,23 @@ package com.glsx.plat.feign.config;
import com.alibaba.fastjson.serializer.SerializerFeature; import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig; import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.glsx.plat.feign.properties.FeignProperties;
import feign.Feign;
import feign.Logger; import feign.Logger;
import feign.Retryer;
import feign.codec.Decoder; import feign.codec.Decoder;
import feign.codec.Encoder; import feign.codec.Encoder;
import feign.form.spring.SpringFormEncoder; import feign.form.spring.SpringFormEncoder;
import feign.form.spring.converter.SpringManyMultipartFilesReader; import feign.form.spring.converter.SpringManyMultipartFilesReader;
import feign.optionals.OptionalDecoder; import feign.optionals.OptionalDecoder;
import feign.querymap.BeanQueryMapEncoder;
import org.springframework.beans.factory.ObjectFactory; import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters; import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.openfeign.FeignAutoConfiguration; import org.springframework.cloud.openfeign.FeignAutoConfiguration;
import org.springframework.cloud.openfeign.support.ResponseEntityDecoder; import org.springframework.cloud.openfeign.support.ResponseEntityDecoder;
import org.springframework.cloud.openfeign.support.SpringDecoder; import org.springframework.cloud.openfeign.support.SpringDecoder;
...@@ -30,47 +37,66 @@ import java.util.List; ...@@ -30,47 +37,66 @@ import java.util.List;
* @author payu * @author payu
*/ */
@Configuration @Configuration
@Import({FeignAutoConfiguration.class, OkHttpConfig.class}) @EnableConfigurationProperties({FeignProperties.class})
@Import({FeignAutoConfiguration.class})
public class FeignConfig { public class FeignConfig {
@Autowired @Autowired
private ObjectFactory<HttpMessageConverters> messageConverters; private ObjectFactory<HttpMessageConverters> messageConverters;
@Bean
@ConditionalOnMissingBean(FeignProperties.class)
@ConditionalOnProperty(name = "feign.enable", havingValue = "true")
public Feign.Builder feignBuilder() {
return Feign.builder()
.queryMapEncoder(new BeanQueryMapEncoder())//替换解析 queryMap 的类,实现父类中变量的映射
.retryer(Retryer.NEVER_RETRY);
}
//Feign表单提交配置,还有解决中文乱码问题 //Feign表单提交配置,还有解决中文乱码问题
@Bean @Bean
@Primary @Primary
@Scope(BeanDefinition.SCOPE_PROTOTYPE) @Scope(BeanDefinition.SCOPE_PROTOTYPE)
@ConditionalOnMissingBean(FeignProperties.class)
@ConditionalOnProperty(name = "feign.enable", havingValue = "true")
public SpringFormEncoder feignFormEncoder() { public SpringFormEncoder feignFormEncoder() {
return new SpringFormEncoder(new SpringEncoder(messageConverters)); return new SpringFormEncoder(new SpringEncoder(messageConverters));
} }
//feign拦截器,设置header信息 //feign拦截器,设置header信息
@Bean @Bean
@ConditionalOnMissingBean(FeignProperties.class)
@ConditionalOnProperty(name = "feign.enable", havingValue = "true")
FeignInterceptor feignInterceptor() { FeignInterceptor feignInterceptor() {
return new FeignInterceptor(); return new FeignInterceptor();
} }
//开启feign日志 //开启feign日志
@Bean @Bean
@ConditionalOnMissingBean(FeignProperties.class)
@ConditionalOnProperty(name = "feign.enable", havingValue = "true")
Logger.Level feignLevel() { Logger.Level feignLevel() {
return Logger.Level.FULL; return Logger.Level.FULL;
} }
@Bean @Bean
@ConditionalOnMissingBean(FeignProperties.class)
@ConditionalOnProperty(name = "feign.enable", havingValue = "true")
public Encoder feignEncoder() { public Encoder feignEncoder() {
return new SpringEncoder(feignHttpMessageConverter()); return new SpringEncoder(feignHttpMessageConverter());
} }
@Bean @Bean
@ConditionalOnMissingBean(FeignProperties.class)
@ConditionalOnProperty(name = "feign.enable", havingValue = "true")
public Decoder feignDecoder() { public Decoder feignDecoder() {
// return new SpringDecoder(feignHttpMessageConverter()); return new OptionalDecoder(new ResponseEntityDecoder(new FeignResultDecoder(new SpringDecoder(feignHttpMessageConverter()))));
return new OptionalDecoder(new ResponseEntityDecoder(new ResultDecoder(new SpringDecoder(feignHttpMessageConverter()))));
} }
private ObjectFactory<HttpMessageConverters> feignHttpMessageConverter() { private ObjectFactory<HttpMessageConverters> feignHttpMessageConverter() {
final HttpMessageConverters httpMessageConverters = getSpringConverter(); // final HttpMessageConverters httpMessageConverters = getSpringConverter();
// final HttpMessageConverters httpMessageConverters = getGsonConverter(); // final HttpMessageConverters httpMessageConverters = getGsonConverter();
// final HttpMessageConverters httpMessageConverters = getFastJsonConverter(); final HttpMessageConverters httpMessageConverters = getFastJsonConverter();
return () -> httpMessageConverters; return () -> httpMessageConverters;
} }
...@@ -90,10 +116,11 @@ public class FeignConfig { ...@@ -90,10 +116,11 @@ public class FeignConfig {
} }
private HttpMessageConverters getFastJsonConverter() { private HttpMessageConverters getFastJsonConverter() {
//创建fastJson消息转换器
FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter(); FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
List<MediaType> supportedMediaTypes = new ArrayList<>(); List<MediaType> supportedMediaTypes = new ArrayList<>();
supportedMediaTypes.add(MediaType.APPLICATION_JSON); supportedMediaTypes.add(MediaType.APPLICATION_JSON);
supportedMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
supportedMediaTypes.add(MediaType.APPLICATION_ATOM_XML); supportedMediaTypes.add(MediaType.APPLICATION_ATOM_XML);
supportedMediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED); supportedMediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);
supportedMediaTypes.add(MediaType.APPLICATION_OCTET_STREAM); supportedMediaTypes.add(MediaType.APPLICATION_OCTET_STREAM);
...@@ -110,6 +137,7 @@ public class FeignConfig { ...@@ -110,6 +137,7 @@ public class FeignConfig {
supportedMediaTypes.add(MediaType.TEXT_PLAIN); supportedMediaTypes.add(MediaType.TEXT_PLAIN);
supportedMediaTypes.add(MediaType.TEXT_XML); supportedMediaTypes.add(MediaType.TEXT_XML);
converter.setSupportedMediaTypes(supportedMediaTypes); converter.setSupportedMediaTypes(supportedMediaTypes);
//创建配置类
FastJsonConfig fastJsonConfig = new FastJsonConfig(); FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(SerializerFeature.WriteDateUseDateFormat, fastJsonConfig.setSerializerFeatures(SerializerFeature.WriteDateUseDateFormat,
SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullStringAsEmpty,
......
...@@ -2,10 +2,7 @@ package com.glsx.plat.feign.config; ...@@ -2,10 +2,7 @@ package com.glsx.plat.feign.config;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference; import com.alibaba.fastjson.TypeReference;
import com.glsx.plat.exception.BusinessException; import com.glsx.plat.exception.*;
import com.glsx.plat.exception.ExceptionInfo;
import com.glsx.plat.exception.ServiceException;
import com.glsx.plat.exception.SystemMessage;
import feign.FeignException; import feign.FeignException;
import feign.Response; import feign.Response;
import feign.Util; import feign.Util;
...@@ -19,7 +16,7 @@ import org.springframework.context.annotation.Configuration; ...@@ -19,7 +16,7 @@ import org.springframework.context.annotation.Configuration;
* @author payu * @author payu
*/ */
@Slf4j @Slf4j
//@Configuration @Configuration
public class FeignErrorDecoder implements ErrorDecoder { public class FeignErrorDecoder implements ErrorDecoder {
@Override @Override
...@@ -36,6 +33,9 @@ public class FeignErrorDecoder implements ErrorDecoder { ...@@ -36,6 +33,9 @@ public class FeignErrorDecoder implements ErrorDecoder {
if (exception instanceof BusinessException) { if (exception instanceof BusinessException) {
log.error("业务异常:" + exception.getMessage()); log.error("业务异常:" + exception.getMessage());
} }
if (exception instanceof ResultException) {
log.error("业务异常:" + exception.getMessage());
}
return exception; return exception;
} }
} catch (Exception e) { } catch (Exception e) {
......
...@@ -40,7 +40,7 @@ public class FeignInterceptor implements RequestInterceptor { ...@@ -40,7 +40,7 @@ public class FeignInterceptor implements RequestInterceptor {
} }
} }
} }
log.info("feign interceptor template requestURL:{},querystring:{}", request.getRequestURL(), request.getQueryString()); log.debug("feign interceptor template requestURL:{},querystring:{}", request.getRequestURL(), request.getQueryString());
} }
} }
...@@ -12,17 +12,18 @@ import java.io.IOException; ...@@ -12,17 +12,18 @@ import java.io.IOException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.lang.reflect.Type; import java.lang.reflect.Type;
public class ResultDecoder implements Decoder { public class FeignResultDecoder implements Decoder {
private Decoder decoder; private Decoder decoder;
public ResultDecoder(Decoder decoder) { public FeignResultDecoder(Decoder decoder) {
this.decoder = decoder; this.decoder = decoder;
} }
@Override @Override
public Object decode(Response response, Type type) throws IOException, FeignException { public Object decode(Response response, Type type) throws IOException, FeignException {
Method method = response.request().requestTemplate().methodMetadata().method(); Method method = response.request().requestTemplate().methodMetadata().method();
boolean isResult = method.getReturnType() != Result.class && method.isAnnotationPresent(ResponseResultBody.class); boolean isResult = method.getReturnType() != Result.class &&
(method.getDeclaringClass().isAnnotationPresent(ResponseResultBody.class) || method.isAnnotationPresent(ResponseResultBody.class));
if (isResult) { if (isResult) {
ParameterizedTypeImpl resultType = ParameterizedTypeImpl.make(Result.class, new Type[]{type}, null); ParameterizedTypeImpl resultType = ParameterizedTypeImpl.make(Result.class, new Type[]{type}, null);
Result<?> result = (Result<?>) this.decoder.decode(response, resultType); Result<?> result = (Result<?>) this.decoder.decode(response, resultType);
......
package com.glsx.plat.feign.config; package com.glsx.plat.feign.config;
import com.glsx.plat.feign.interceptor.OkHttpTokenInterceptor; import com.glsx.plat.feign.interceptor.OkHttpTokenInterceptor;
import feign.Feign;
import okhttp3.ConnectionPool; 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.Bean;
import org.springframework.context.annotation.Configuration;
import javax.annotation.Resource; import javax.annotation.Resource;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
...@@ -16,9 +11,9 @@ import java.util.concurrent.TimeUnit; ...@@ -16,9 +11,9 @@ import java.util.concurrent.TimeUnit;
* 配置 okhttp 与连接池 * 配置 okhttp 与连接池
* ConnectionPool 默认创建5个线程,保持5分钟长连接 * ConnectionPool 默认创建5个线程,保持5分钟长连接
*/ */
@Configuration //@Configuration
@ConditionalOnClass(Feign.class) //@ConditionalOnClass(Feign.class)
@AutoConfigureBefore(FeignAutoConfiguration.class) //SpringBoot自动配置 //@AutoConfigureBefore(FeignAutoConfiguration.class) //SpringBoot自动配置
public class OkHttpConfig { public class OkHttpConfig {
@Resource @Resource
...@@ -43,25 +38,4 @@ public class OkHttpConfig { ...@@ -43,25 +38,4 @@ public class OkHttpConfig {
.build(); .build();
} }
//feign:
// # feign启用hystrix,才能熔断、降级
// # hystrix:
// # enabled: true
// # 启用 okhttp 关闭默认 httpclient
// httpclient:
// enabled: false #关闭httpclient
// # 配置连接池
// max-connections: 200 #feign的最大连接数
// max-connections-per-route: 50 #fegin单个路径的最大连接数
// okhttp:
// enabled: true
// # 请求与响应的压缩以提高通信效率
// compression:
// request:
// enabled: true
// min-request-size: 2048
// mime-types: text/xml,application/xml,application/json
// response:
// enabled: true
} }
\ No newline at end of file \ No newline at end of file
package com.glsx.plat.feign.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import java.nio.charset.StandardCharsets;
import java.util.List;
@Configuration
public class RestTemplateConfig {
/**
* 创建http请求工厂
* <p>
* 实例化OkHttp3
*
* @return
*/
@Bean
public OkHttp3ClientHttpRequestFactory httpRequestFactory() {
OkHttp3ClientHttpRequestFactory requestFactory = new OkHttp3ClientHttpRequestFactory();
requestFactory.setConnectTimeout(10000);
requestFactory.setReadTimeout(20000);
return requestFactory;
}
/**
* 实例化RestTemplate模板
*
* @return
*/
@Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate(httpRequestFactory());
// 中文乱码,主要是 StringHttpMessageConverter的默认编码为ISO导致的
List<HttpMessageConverter<?>> list = restTemplate.getMessageConverters();
for (HttpMessageConverter converter : list) {
if (converter instanceof StringHttpMessageConverter) {
((StringHttpMessageConverter) converter).setDefaultCharset(StandardCharsets.UTF_8);
break;
}
}
return restTemplate;
}
}
package com.glsx.plat.feign.fallback; package com.glsx.plat.feign.fallback;
import feign.Target; import feign.Target;
import feign.hystrix.FallbackFactory;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import org.springframework.cglib.proxy.Enhancer; import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cloud.openfeign.FallbackFactory;
@AllArgsConstructor @AllArgsConstructor
public class FunFallbackFactory<T> implements FallbackFactory<T> { public class FunFallbackFactory<T> implements FallbackFactory<T> {
......
...@@ -9,7 +9,6 @@ import lombok.extern.slf4j.Slf4j; ...@@ -9,7 +9,6 @@ import lombok.extern.slf4j.Slf4j;
import org.springframework.cglib.proxy.MethodInterceptor; import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy; import org.springframework.cglib.proxy.MethodProxy;
import javax.annotation.Nullable;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.Objects; import java.util.Objects;
...@@ -21,7 +20,6 @@ public class FunFeignFallback<T> implements MethodInterceptor { ...@@ -21,7 +20,6 @@ public class FunFeignFallback<T> implements MethodInterceptor {
private final String targetName; private final String targetName;
private final Throwable cause; private final Throwable cause;
@Nullable
@Override @Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable { public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
String errorMessage = cause.getMessage(); String errorMessage = cause.getMessage();
......
package com.glsx.plat.feign.fallback; package com.glsx.plat.feign.fallback;
import com.alibaba.csp.sentinel.SphU;
import feign.Feign; import feign.Feign;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import com.alibaba.cloud.sentinel.feign.FunSentinelFeign;
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.context.annotation.Primary; import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Scope; import org.springframework.context.annotation.Scope;
@Configuration //@Configuration
public class FunFeignFallbackConfiguration { public class FunFeignFallbackConfiguration {
@Bean // @Bean
@Scope("prototype") // @Scope("prototype")
@ConditionalOnClass({SphU.class, Feign.class}) // @ConditionalOnClass({SphU.class, Feign.class})
@ConditionalOnProperty(name = "feign.sentinel.enabled") // @ConditionalOnProperty(name = "feign.sentinel.enabled")
@Primary // @Primary
public Feign.Builder feignSentinelBuilder() { // public Feign.Builder feignSentinelBuilder() {
return FunSentinelFeign.builder(); // return SentinelFeign.builder();
} // }
} }
package com.glsx.plat.feign.interceptor;
import lombok.Builder;
import lombok.Data;
import org.springframework.http.HttpHeaders;
/**
* 定义日志的字段
*/
@Data
@Builder
public class RestLog {
private String reqUrl;
private String method;
private HttpHeaders headers;
private String reqBody;
private String resBody;
private long costTime;
private int resStatus;
}
package com.glsx.plat.feign.interceptor;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.glsx.plat.core.enums.SysConstants;
import com.glsx.plat.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.util.StopWatch;
import org.springframework.util.StreamUtils;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
/**
* 自定义的拦截器
* <p>
* 主要打印日志
*/
@Slf4j
public class RestTemplateRequestInterceptor implements ClientHttpRequestInterceptor {
@Override
public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] body, ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {
//记录请求开始时间
StopWatch stopWatch = new StopWatch();
stopWatch.start();
//执行请求
ClientHttpResponse response = clientHttpRequestExecution.execute(httpRequest, body);
//执行完毕后,这里要创建备份,要不然会报io提前关闭的异常错误
ClientHttpResponse responseCopy = new BufferingClientHttpResponseWrapper(response);
//记录请求结束时间
stopWatch.stop();
//获取响应内容
StringBuilder resBody = new StringBuilder();
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(responseCopy.getBody(), StandardCharsets.UTF_8))) {
String line = bufferedReader.readLine();
while (line != null) {
resBody.append(line);
line = bufferedReader.readLine();
}
}
//获取请求内容
String reqBody = "";
//这里可以自定义想打印什么方法或者请求的内容,如下只打印post请求的日志,因为这时候才会带上body
if (httpRequest.getHeaders().getContentType() != null && "POST".equals(httpRequest.getMethod().name())) {
String requestBody = new String(body, StandardCharsets.UTF_8);
//String contentType = httpRequest.getHeaders().getContentType().toString();
//这里可以对contentType做一些判断,针对其格式化请求体的内容,如"application/x-www-form-urlencoded"格式会附带一些boundary(分割线)的内容
reqBody = requestBody;
}
//打印日志的格式可以自定义
log.info(JSONUtil.toJsonStr(RestLog.builder()
.costTime(stopWatch.getLastTaskTimeMillis())
.headers(httpRequest.getHeaders())
.method(httpRequest.getMethodValue())
.reqUrl(httpRequest.getURI().toString())
.reqBody(reqBody)
.resBody(resBody.toString())
.resStatus(responseCopy.getRawStatusCode())
.build()));
JSONObject resultJO = JSONUtil.parseObj(resBody);
if (!Objects.equals(SysConstants.ResultStatus.success.getCode(), resultJO.get("code"))) {
throw ServiceException.create(resultJO.getStr("code"), resultJO.getStr("message"));
}
return responseCopy;
}
}
/**
* 响应内容备份
*/
final class BufferingClientHttpResponseWrapper implements ClientHttpResponse {
private final ClientHttpResponse response;
private byte[] body;
BufferingClientHttpResponseWrapper(ClientHttpResponse response) {
this.response = response;
}
@Override
public HttpStatus getStatusCode() throws IOException {
return this.response.getStatusCode();
}
@Override
public int getRawStatusCode() throws IOException {
return this.response.getRawStatusCode();
}
@Override
public String getStatusText() throws IOException {
return this.response.getStatusText();
}
@Override
public HttpHeaders getHeaders() {
return this.response.getHeaders();
}
@Override
public InputStream getBody() throws IOException {
if (this.body == null) {
this.body = StreamUtils.copyToByteArray(this.response.getBody());
}
return new ByteArrayInputStream(this.body);
}
@Override
public void close() {
this.response.close();
}
}
\ No newline at end of file \ No newline at end of file
package com.glsx.plat.feign.properties;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
@Data
@ConfigurationProperties(prefix = "feign")
public class FeignProperties {
private Boolean enable;
}
package com.glsx.plat.feign.utils;
import lombok.SneakyThrows;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustAllStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContexts;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import javax.net.ssl.SSLContext;
public enum RestTemplateKit {
SCOPE(20000, 20000, 512, 32);
private final int READ_TIMEOUT;
private final int CONNECT_TIMEOUT;
private final int MAX_TOTAL;
private final int MAX_PER_ROUTE;
private final ClientHttpRequestFactory factory;
private final RestTemplate client;
RestTemplateKit(int readTimeout, int connectTimeout, int maxTotal, int perRoute) {
READ_TIMEOUT = readTimeout;
CONNECT_TIMEOUT = connectTimeout;
MAX_TOTAL = maxTotal;
MAX_PER_ROUTE = perRoute;
factory = new HttpComponentsClientHttpRequestFactory(newHttpClient());
client = new RestTemplate(factory);
}
@SneakyThrows
private CloseableHttpClient newHttpClient() {
RequestConfig reqCfg = RequestConfig.custom()
.setSocketTimeout(READ_TIMEOUT)
.setConnectTimeout(CONNECT_TIMEOUT)
.build();
SocketConfig sockCfg = SocketConfig.custom()
.setTcpNoDelay(true)
.setSoTimeout(READ_TIMEOUT)
.build();
SSLContext sslCtx = SSLContexts.custom()
.loadTrustMaterial(TrustAllStrategy.INSTANCE)
.build();
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", new SSLConnectionSocketFactory(sslCtx, NoopHostnameVerifier.INSTANCE))
.build();
PoolingHttpClientConnectionManager manager
= new PoolingHttpClientConnectionManager(registry);
manager.setMaxTotal(MAX_TOTAL);
manager.setDefaultMaxPerRoute(MAX_PER_ROUTE);
HttpClientBuilder builder = HttpClients.custom();
builder.setDefaultRequestConfig(reqCfg);
builder.setDefaultSocketConfig(sockCfg);
builder.setConnectionManager(manager);
builder.setRetryHandler(new DefaultHttpRequestRetryHandler(1, true));
return builder.build();
}
public RestTemplate singleton() {
return client;
}
public RestTemplate prototype() {
return new RestTemplate(factory);
}
}
package com.glsx.plat.feign.utils;
import com.glsx.plat.feign.interceptor.RestTemplateRequestInterceptor;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RequestCallback;
import org.springframework.web.client.ResponseExtractor;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class RestTemplateUtils {
private static final int CONNECT_TIMEOUT = 20000;
private static final int SOCKET_TIMEOUT = 60000;
private static RestTemplate getCustomRestTemplate() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(CONNECT_TIMEOUT);
factory.setReadTimeout(SOCKET_TIMEOUT);
return new RestTemplate(factory);
}
private static RestTemplate getOkHttp3RestTemplate() {
OkHttp3ClientHttpRequestFactory factory = new OkHttp3ClientHttpRequestFactory();
factory.setConnectTimeout(CONNECT_TIMEOUT);
factory.setReadTimeout(SOCKET_TIMEOUT);
RestTemplate restTemplate = new RestTemplate(factory);
//添加拦截器
List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
RestTemplateRequestInterceptor requestInterceptor = new RestTemplateRequestInterceptor();
interceptors.add(requestInterceptor);
restTemplate.setInterceptors(interceptors);
return restTemplate;
}
public static <T> T fetch(String url,
String method,
HttpEntity<?> requestEntity,
ParameterizedType parameterizedType) {
ParameterizedTypeReference<T> responseType = ParameterizedTypeReference.forType(parameterizedType);
return fetch(url, method, requestEntity, responseType);
}
public static <T> T fetch(String url,
String method,
Object body,
HttpHeaders headers,
ParameterizedType parameterizedType) {
HttpEntity<?> requestEntity = new HttpEntity<>(body, headers);
return fetch(url, method, requestEntity, parameterizedType);
}
public static <T> T fetch(String url,
String method,
HttpEntity<?> requestEntity,
ParameterizedTypeReference<T> responseType) {
T ret = null;
RestTemplate restTemplate = getOkHttp3RestTemplate();
HttpMethod httpMethod = HttpMethod.resolve(Objects.nonNull(method) ? method.toUpperCase() : "");
if (Objects.nonNull(httpMethod)) {
ResponseEntity<T> responseEntity = restTemplate.exchange(url, httpMethod, requestEntity, responseType);
ret = responseEntity.getBody();
}
return ret;
}
public static <T> T fetch(String url,
HttpMethod httpMethod,
HttpEntity<?> requestEntity,
ParameterizedTypeReference<T> responseType) {
T ret = null;
RestTemplate restTemplate = getOkHttp3RestTemplate();
if (Objects.nonNull(httpMethod)) {
ResponseEntity<T> responseEntity = restTemplate.exchange(url, httpMethod, requestEntity, responseType);
ret = responseEntity.getBody();
}
return ret;
}
public static <T> T fetchGet(String url, Object body, ParameterizedType parameterizedType) {
HttpEntity<?> requestEntity = new HttpEntity<>(body, new HttpHeaders());
return fetch(url, HttpMethod.GET.name(), requestEntity, parameterizedType);
}
public static <T> T fetchGet(String url, ParameterizedTypeReference<T> responseType) {
HttpEntity<String> entity = new HttpEntity<>(new HttpHeaders());
return fetchGet(url, entity, responseType);
}
public static <T> T fetchGet(String url, MultiValueMap<String, String> params, ParameterizedTypeReference<T> responseType) {
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url).queryParams(params);
HttpEntity<String> entity = new HttpEntity<>(new HttpHeaders());
return fetchGet(builder.toUriString(), entity, responseType);
}
public static <T> T fetchGet(String url, HttpEntity<?> requestEntity, ParameterizedTypeReference<T> responseType) {
RestTemplate restTemplate = getOkHttp3RestTemplate();
ResponseEntity<T> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, responseType);
return responseEntity.getBody();
}
public static <T> T fetchPost(String url,
HttpEntity<?> requestEntity,
ParameterizedTypeReference<T> responseType) {
RestTemplate restTemplate = getOkHttp3RestTemplate();
ResponseEntity<T> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, responseType);
return responseEntity.getBody();
}
public static <T> T fetchPostJson(String url, Object body, ParameterizedTypeReference<T> responseType) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON.toString());
HttpEntity<?> requestEntity = new HttpEntity<>(body, headers);
return fetch(url, HttpMethod.POST.name(), requestEntity, responseType);
}
public static <T> T fetch(String url,
String method,
Object body,
HttpHeaders headers,
ParameterizedTypeReference<T> responseType) {
HttpEntity<?> requestEntity = new HttpEntity<>(body, headers);
return fetch(url, method, requestEntity, responseType);
}
public static <T> T fetch(String url,
String method,
HttpEntity<?> requestEntity,
Class<T> clazz) {
T ret = null;
RestTemplate restTemplate = getOkHttp3RestTemplate();
HttpMethod httpMethod = HttpMethod.resolve(Objects.nonNull(method) ? method.toUpperCase() : "");
if (Objects.nonNull(httpMethod)) {
ResponseEntity<T> responseEntity = restTemplate.exchange(url, httpMethod, requestEntity, clazz);
ret = responseEntity.getBody();
}
return ret;
}
public static <T> T fetch(String url,
String method,
Object body,
HttpHeaders headers,
Class<T> clazz) {
HttpEntity<?> requestEntity = new HttpEntity<>(body, headers);
return fetch(url, method, requestEntity, clazz);
}
public static <T> T fetch(String url,
String method,
RequestCallback callback,
ResponseExtractor<T> extractor) {
T ret = null;
RestTemplate restTemplate = getOkHttp3RestTemplate();
HttpMethod httpMethod = HttpMethod.resolve(Objects.nonNull(method) ? method.toUpperCase() : "");
if (Objects.nonNull(httpMethod)) {
ret = restTemplate.execute(url, httpMethod, callback, extractor);
}
return ret;
}
/*
public static void main(String[] args) {
// HttpHeaders headers = new HttpHeaders();
// headers.setContentType(MediaType.MULTIPART_FORM_DATA);
// MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
// form.add("data", "");
// form.add("file", new FileSystemResource(""));
// form.add("byte", new ByteArrayResource(new byte[0], ""));
// HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(form, headers);
// fetch("url", "POST", requestEntity, JSONObject.class);
// */
}
...@@ -17,10 +17,6 @@ ...@@ -17,10 +17,6 @@
<artifactId>spring-cloud-starter-gateway</artifactId> <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<dependency>
<groupId>com.glsx</groupId> <groupId>com.glsx</groupId>
<artifactId>rest-admin-config</artifactId> <artifactId>rest-admin-config</artifactId>
</dependency> </dependency>
...@@ -40,17 +36,14 @@ ...@@ -40,17 +36,14 @@
<dependency> <dependency>
<groupId>com.glsx</groupId> <groupId>com.glsx</groupId>
<artifactId>rest-admin-common</artifactId> <artifactId>rest-admin-common</artifactId>
<scope>compile</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.glsx</groupId> <groupId>com.glsx</groupId>
<artifactId>rest-admin-core</artifactId> <artifactId>rest-admin-core</artifactId>
<scope>compile</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.glsx</groupId> <groupId>com.glsx</groupId>
<artifactId>rest-admin-exception</artifactId> <artifactId>rest-admin-exception</artifactId>
<scope>compile</scope>
</dependency> </dependency>
</dependencies> </dependencies>
</project> </project>
\ No newline at end of file \ No newline at end of file
...@@ -12,26 +12,18 @@ ...@@ -12,26 +12,18 @@
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>com.auth0</groupId> <groupId>com.glsx</groupId>
<artifactId>java-jwt</artifactId> <artifactId>rest-admin-redis</artifactId>
<version>3.18.2</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>com.auth0</groupId>
<artifactId>spring-boot</artifactId> <artifactId>java-jwt</artifactId>
<version>4.4.0</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.commons</groupId> <groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId> <artifactId>commons-lang3</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
</dependencies> </dependencies>
<build> <build>
......
...@@ -19,21 +19,11 @@ public abstract class BaseJwtUser { ...@@ -19,21 +19,11 @@ public abstract class BaseJwtUser {
private String application; private String application;
/** /**
* 用户标识(用long,)
*/
private String userId;
/**
* 用户账号(如:管理系统admin,消费者系统手机号等) * 用户账号(如:管理系统admin,消费者系统手机号等)
*/ */
private String account; private String account;
/** /**
* 租户
*/
private String tenant;
/**
* 子类的class全限定名 * 子类的class全限定名
*/ */
private String clazz; private String clazz;
......
...@@ -11,10 +11,20 @@ import lombok.Data; ...@@ -11,10 +11,20 @@ import lombok.Data;
public class ComJwtUser extends BaseJwtUser { public class ComJwtUser extends BaseJwtUser {
/** /**
* 租户
*/
private String tenant;
/**
* 归属(租户、组织、机构、部门、个体等等) * 归属(租户、组织、机构、部门、个体等等)
*/ */
private String belong; private String belong;
/**
* 用户标识
*/
private String userId;
@Override @Override
public String getClazz() { public String getClazz() {
return this.getClass().getCanonicalName(); return this.getClass().getCanonicalName();
......
...@@ -11,12 +11,16 @@ ...@@ -11,12 +11,16 @@
<artifactId>rest-admin-kafka-ancient</artifactId> <artifactId>rest-admin-kafka-ancient</artifactId>
<properties>
<kafka.version>0.8.2.2</kafka.version>
<spring-kafka.version>1.3.0.RELEASE</spring-kafka.version>
</properties>
<dependencies> <dependencies>
<!--kafka-->
<dependency> <dependency>
<groupId>org.apache.kafka</groupId> <groupId>org.apache.kafka</groupId>
<artifactId>kafka_2.10</artifactId> <artifactId>kafka_2.10</artifactId>
<version>0.8.1.1</version> <version>${kafka.version}</version>
<exclusions> <exclusions>
<exclusion> <exclusion>
<groupId>org.slf4j</groupId> <groupId>org.slf4j</groupId>
...@@ -32,6 +36,11 @@ ...@@ -32,6 +36,11 @@
</exclusion> </exclusion>
</exclusions> </exclusions>
</dependency> </dependency>
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka-clients</artifactId>
<version>${kafka.version}</version>
</dependency>
<!-- protocol buf --> <!-- protocol buf -->
<dependency> <dependency>
...@@ -39,10 +48,5 @@ ...@@ -39,10 +48,5 @@
<artifactId>protobuf-java</artifactId> <artifactId>protobuf-java</artifactId>
<version>2.6.1</version> <version>2.6.1</version>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot</artifactId>
</dependency>
</dependencies> </dependencies>
</project> </project>
\ No newline at end of file \ No newline at end of file
...@@ -15,8 +15,8 @@ import java.util.Properties; ...@@ -15,8 +15,8 @@ import java.util.Properties;
* @time 2020/12/4 * @time 2020/12/4
* @function kafka的公共配置 * @function kafka的公共配置
*/ */
@Configuration //@Configuration
@EnableConfigurationProperties(KafkaProperties.class) //@EnableConfigurationProperties(KafkaProperties.class)
public class KafkaConfig { public class KafkaConfig {
@Autowired @Autowired
......
...@@ -21,5 +21,4 @@ ...@@ -21,5 +21,4 @@
<artifactId>rest-admin-core</artifactId> <artifactId>rest-admin-core</artifactId>
</dependency> </dependency>
</dependencies> </dependencies>
</project> </project>
\ No newline at end of file \ No newline at end of file
...@@ -22,17 +22,20 @@ ...@@ -22,17 +22,20 @@
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.glsx</groupId> <groupId>com.glsx</groupId>
<artifactId>rest-admin-redis</artifactId>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-mongodb</artifactId> <artifactId>rest-admin-mongodb</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.glsx</groupId> <groupId>com.glsx</groupId>
<artifactId>rest-admin-office</artifactId> <artifactId>rest-admin-elasticsearch</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.glsx</groupId> <groupId>com.glsx</groupId>
<artifactId>rest-admin-web</artifactId> <artifactId>rest-admin-office</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.aspectj</groupId> <groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId> <artifactId>aspectjweaver</artifactId>
...@@ -41,10 +44,6 @@ ...@@ -41,10 +44,6 @@
<groupId>org.springframework</groupId> <groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId> <artifactId>spring-context</artifactId>
</dependency> </dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
</dependency>
</dependencies> </dependencies>
</project> </project>
\ No newline at end of file \ No newline at end of file
...@@ -2,7 +2,7 @@ package com.glsx.plat.loggin; ...@@ -2,7 +2,7 @@ package com.glsx.plat.loggin;
public enum LogginStrategy { public enum LogginStrategy {
MONGODB("mongo"), KAFKA("kafka"), MYSQL("mysql"); MONGODB("mongo"), KAFKA("kafka"), MYSQL("mysql"), Elasticsearch("elasticsearch");
private String strategy; private String strategy;
......
...@@ -19,7 +19,7 @@ public class LogginStrategyFactory { ...@@ -19,7 +19,7 @@ public class LogginStrategyFactory {
public AbstractLogginStrategy getStrategy() throws Exception { public AbstractLogginStrategy getStrategy() throws Exception {
AbstractLogginStrategy strategy = strategys.get(logginProperties.getStrategy()); AbstractLogginStrategy strategy = strategys.get(logginProperties.getStrategy());
if (strategy == null) { if (strategy == null) {
throw new RuntimeException("no strategy defined"); throw new RuntimeException("no log strategy defined");
} }
return strategy; return strategy;
} }
......
package com.glsx.plat.loggin.aop; package com.glsx.plat.loggin.aop;
import com.glsx.plat.common.annotation.SysLog; import com.glsx.plat.common.annotation.SysLog;
import com.glsx.plat.common.utils.IpUtils;
import com.glsx.plat.common.utils.SessionUtils;
import com.glsx.plat.common.utils.StringUtils; import com.glsx.plat.common.utils.StringUtils;
import com.glsx.plat.core.web.R; import com.glsx.plat.core.web.R;
import com.glsx.plat.jwt.util.JwtUtils; import com.glsx.plat.jwt.util.JwtUtils;
...@@ -8,8 +10,6 @@ import com.glsx.plat.loggin.LogginConstants; ...@@ -8,8 +10,6 @@ import com.glsx.plat.loggin.LogginConstants;
import com.glsx.plat.loggin.LogginStrategyFactory; import com.glsx.plat.loggin.LogginStrategyFactory;
import com.glsx.plat.loggin.thread.LogginTask; import com.glsx.plat.loggin.thread.LogginTask;
import com.glsx.plat.redis.service.GainIdService; import com.glsx.plat.redis.service.GainIdService;
import com.glsx.plat.web.utils.IpUtils;
import com.glsx.plat.web.utils.SessionUtils;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
import com.google.gson.Gson; import com.google.gson.Gson;
......
package com.glsx.plat.loggin.strategy;
import com.glsx.plat.loggin.AbstractLogginStrategy;
import com.glsx.plat.loggin.entity.SysLogEntity;
import org.springframework.stereotype.Component;
@Component("elasticsearch")
public class LogginStrategyByElasticsearh extends AbstractLogginStrategy {
@Override
public void saveLog(SysLogEntity entity) {
}
@Override
public void updateLogStatus(String logTraceId, String result) {
}
}
...@@ -3,9 +3,9 @@ package com.glsx.plat.loggin.thread; ...@@ -3,9 +3,9 @@ package com.glsx.plat.loggin.thread;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.glsx.plat.common.annotation.SysLog; import com.glsx.plat.common.annotation.SysLog;
import com.glsx.plat.common.enums.OperateType; import com.glsx.plat.common.enums.OperateType;
import com.glsx.plat.common.utils.IpUtils;
import com.glsx.plat.loggin.AbstractLogginStrategy; import com.glsx.plat.loggin.AbstractLogginStrategy;
import com.glsx.plat.loggin.entity.SysLogEntity; import com.glsx.plat.loggin.entity.SysLogEntity;
import com.glsx.plat.web.utils.IpUtils;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
......
...@@ -19,7 +19,6 @@ ...@@ -19,7 +19,6 @@
<dependency> <dependency>
<groupId>cn.hutool</groupId> <groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId> <artifactId>hutool-all</artifactId>
<version>5.7.20</version>
</dependency> </dependency>
</dependencies> </dependencies>
</project> </project>
\ No newline at end of file \ No newline at end of file
...@@ -16,5 +16,10 @@ ...@@ -16,5 +16,10 @@
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId> <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency> </dependency>
<!-- MongoDB Reactive 依赖组件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb-reactive</artifactId>
</dependency>
</dependencies> </dependencies>
</project> </project>
\ No newline at end of file \ No newline at end of file
package com.glsx.plat.mongodb.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
//@Component
//@ConfigurationProperties(prefix = "spring.data.mongodb.uri")
public class MongoConfig {
}
\ No newline at end of file \ No newline at end of file
...@@ -22,7 +22,7 @@ ...@@ -22,7 +22,7 @@
<dependency> <dependency>
<groupId>de.codecentric</groupId> <groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-client</artifactId> <artifactId>spring-boot-admin-starter-client</artifactId>
<version>2.2.3</version> <version>2.6.11</version>
</dependency> </dependency>
</dependencies> </dependencies>
</project> </project>
\ No newline at end of file \ No newline at end of file
...@@ -9,30 +9,16 @@ ...@@ -9,30 +9,16 @@
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>rest-admin-swagger2</artifactId> <artifactId>rest-admin-mybatis-generator</artifactId>
<properties> <properties>
<swagger2.version>2.7.0</swagger2.version> <mybatis.boot.version>2.2.2</mybatis.boot.version>
</properties> </properties>
<dependencies> <dependencies>
<!--swagger 文档-->
<dependency> <dependency>
<groupId>io.springfox</groupId> <groupId>org.mybatis.generator</groupId>
<artifactId>springfox-swagger2</artifactId> <artifactId>mybatis-generator-core</artifactId>
<version>${swagger2.version}</version>
<scope>compile</scope>
<exclusions>
<exclusion>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger2.version}</version>
</dependency> </dependency>
</dependencies> </dependencies>
</project> </project>
\ No newline at end of file \ No newline at end of file
package com.glsx.plat.generator.plugins;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.api.dom.java.TopLevelClass;
import java.util.List;
/**
* 在实体中生成 Lombok 注解
*/
public class LombokPlugin extends PluginAdapter {
@Override
public boolean validate(List<String> list) {
return true;
}
/**
* 添加注解的方法
*/
@Override
public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
// 添加实体类的 import
topLevelClass.addImportedType("lombok.Data");
topLevelClass.addImportedType("lombok.NoArgsConstructor");
topLevelClass.addImportedType("lombok.AllArgsConstructor");
topLevelClass.addImportedType("lombok.experimental.Accessors");
// 添加实体类的 lombok 注解
topLevelClass.addAnnotation("@Data");
topLevelClass.addAnnotation("@Accessors(chain = true)");
topLevelClass.addAnnotation("@NoArgsConstructor");
topLevelClass.addAnnotation("@AllArgsConstructor");
return true;
}
@Override
public boolean modelSetterMethodGenerated(Method method, TopLevelClass topLevelClass, IntrospectedColumn introspectedColumn, IntrospectedTable introspectedTable, ModelClassType modelClassType) {
// 不生成 setter
return false;
}
@Override
public boolean modelGetterMethodGenerated(Method method, TopLevelClass topLevelClass, IntrospectedColumn introspectedColumn, IntrospectedTable introspectedTable, ModelClassType modelClassType) {
// 不生成 getter
return false;
}
}
\ No newline at end of file \ No newline at end of file
...@@ -14,7 +14,6 @@ ...@@ -14,7 +14,6 @@
<properties> <properties>
<mybatis.boot.version>2.2.2</mybatis.boot.version> <mybatis.boot.version>2.2.2</mybatis.boot.version>
<mapper.boot.version>2.1.5</mapper.boot.version> <mapper.boot.version>2.1.5</mapper.boot.version>
<pagehelper.boot.version>1.4.2</pagehelper.boot.version>
</properties> </properties>
<dependencies> <dependencies>
...@@ -27,11 +26,6 @@ ...@@ -27,11 +26,6 @@
<artifactId>rest-admin-datasource</artifactId> <artifactId>rest-admin-datasource</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId> <groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId> <artifactId>mybatis-spring-boot-starter</artifactId>
<version>${mybatis.boot.version}</version> <version>${mybatis.boot.version}</version>
...@@ -47,6 +41,10 @@ ...@@ -47,6 +41,10 @@
<groupId>org.mybatis</groupId> <groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId> <artifactId>mybatis</artifactId>
</exclusion> </exclusion>
<exclusion>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
</exclusion>
</exclusions> </exclusions>
</dependency> </dependency>
...@@ -54,7 +52,6 @@ ...@@ -54,7 +52,6 @@
<dependency> <dependency>
<groupId>com.github.pagehelper</groupId> <groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId> <artifactId>pagehelper-spring-boot-starter</artifactId>
<version>${pagehelper.boot.version}</version>
<exclusions> <exclusions>
<exclusion> <exclusion>
<groupId>com.github.jsqlparser</groupId> <groupId>com.github.jsqlparser</groupId>
...@@ -66,52 +63,10 @@ ...@@ -66,52 +63,10 @@
<dependency> <dependency>
<groupId>com.github.jsqlparser</groupId> <groupId>com.github.jsqlparser</groupId>
<artifactId>jsqlparser</artifactId> <artifactId>jsqlparser</artifactId>
<version>4.4</version> </dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
</dependency> </dependency>
</dependencies> </dependencies>
<!-- <build>-->
<!-- <plugins>-->
<!-- &lt;!&ndash;mybatis 逆向生成插件&ndash;&gt;-->
<!-- <plugin>-->
<!-- <groupId>org.mybatis.generator</groupId>-->
<!-- <artifactId>mybatis-generator-maven-plugin</artifactId>-->
<!-- <version>1.3.7</version>-->
<!-- <dependencies>-->
<!-- <dependency>-->
<!-- <groupId>mysql</groupId>-->
<!-- <artifactId>mysql-connector-java</artifactId>-->
<!-- <version>${mysql.version}</version>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>org.mybatis.generator</groupId>-->
<!-- <artifactId>mybatis-generator-core</artifactId>-->
<!-- <version>1.3.7</version>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>tk.mybatis</groupId>-->
<!-- <artifactId>mapper</artifactId>-->
<!-- <version>3.4.1</version>-->
<!-- </dependency>-->
<!-- </dependencies>-->
<!-- <executions>-->
<!-- <execution>-->
<!-- <id>Generate MyBatis Artifacts</id>-->
<!-- <phase>deploy</phase>-->
<!-- <goals>-->
<!-- <goal>generate</goal>-->
<!-- </goals>-->
<!-- </execution>-->
<!-- </executions>-->
<!-- <configuration>-->
<!-- &lt;!&ndash;允许移动生成的文件 &ndash;&gt;-->
<!-- <verbose>true</verbose>-->
<!-- &lt;!&ndash; 是否覆盖 &ndash;&gt;-->
<!-- <overwrite>true</overwrite>-->
<!-- &lt;!&ndash; 自动生成的配置 &ndash;&gt;-->
<!-- <configurationFile>src/main/resources/config/generatorConfig.xml</configurationFile>-->
<!-- </configuration>-->
<!-- </plugin>-->
<!-- </plugins>-->
<!-- </build>-->
</project> </project>
\ No newline at end of file \ No newline at end of file
...@@ -22,7 +22,6 @@ ...@@ -22,7 +22,6 @@
<groupId>commons-io</groupId> <groupId>commons-io</groupId>
<artifactId>commons-io</artifactId> <artifactId>commons-io</artifactId>
<version>2.11.0</version> <version>2.11.0</version>
<scope>compile</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>jakarta.servlet</groupId> <groupId>jakarta.servlet</groupId>
......
...@@ -9,13 +9,9 @@ import org.springframework.data.redis.core.RedisCallback; ...@@ -9,13 +9,9 @@ import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations; import org.springframework.data.redis.core.ZSetOperations;
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.util.Collection; import java.util.*;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
/** /**
...@@ -90,7 +86,7 @@ public class RedisUtils { ...@@ -90,7 +86,7 @@ public class RedisUtils {
if (key.length == 1) { if (key.length == 1) {
redisTemplate.delete(key[0]); redisTemplate.delete(key[0]);
} else { } else {
redisTemplate.delete(CollectionUtils.arrayToList(key)); redisTemplate.delete(Arrays.asList(key));
} }
} }
} }
......
...@@ -16,6 +16,17 @@ ...@@ -16,6 +16,17 @@
<dependency> <dependency>
<groupId>com.alibaba.cloud</groupId> <groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
<exclusions>
<!-- 将ribbon排除 -->
<exclusion>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency> </dependency>
</dependencies> </dependencies>
......
...@@ -17,13 +17,6 @@ ...@@ -17,13 +17,6 @@
<groupId>org.springframework.cloud</groupId> <groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-sleuth</artifactId> <artifactId>spring-cloud-starter-sleuth</artifactId>
</dependency> </dependency>
<!--zipkin-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zipkin</artifactId>
</dependency>
<dependency> <dependency>
<groupId>net.logstash.logback</groupId> <groupId>net.logstash.logback</groupId>
<artifactId>logstash-logback-encoder</artifactId> <artifactId>logstash-logback-encoder</artifactId>
......
package com.glsx.plat.swagger2.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
import java.util.List;
@Configuration
@EnableSwagger2
public class Swagger2Config {
@Value("${swagger2.basePackage:cn.com.glsx}")
private String basePackage;
@Value("${swagger2.enable:false}")
private boolean enable;
@Bean
public Docket createRestApi() {
ParameterBuilder ticketPar = new ParameterBuilder();
List<Parameter> pars = new ArrayList<>();
ticketPar.name("Authorization").description("user ticket")//Token 以及Authorization 为自定义的参数,session保存的名字是哪个就可以写成那个
.modelRef(new ModelRef("string")).parameterType("header")
.required(false).build(); //header中的ticket参数非必填,传空也可以
pars.add(ticketPar.build()); //根据每个方法名也知道当前方法在设置什么参数
return new Docket(DocumentationType.SWAGGER_2)
.enable(enable)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage(basePackage))
.paths(PathSelectors.any())
.build()
.globalOperationParameters(pars);
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Spring Boot————Swagger2构建Restful APIs")
.description("XXX使用")
.termsOfServiceUrl("https://swagger.io")
.version("1.0")
.build();
}
}
...@@ -12,15 +12,19 @@ ...@@ -12,15 +12,19 @@
<artifactId>rest-admin-swagger3</artifactId> <artifactId>rest-admin-swagger3</artifactId>
<properties> <properties>
<swagger2.version>3.0.0</swagger2.version> <swagger3.version>3.0.0</swagger3.version>
<knife4j.version>3.0.3</knife4j.version>
</properties> </properties>
<dependencies> <dependencies>
<!--swagger 文档-->
<dependency> <dependency>
<groupId>io.springfox</groupId> <groupId>com.github.xiaoymin</groupId>
<artifactId>springfox-boot-starter</artifactId> <artifactId>knife4j-openapi3-spring-boot-starter</artifactId>
<version>3.0.0</version> <version>4.1.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency> </dependency>
</dependencies> </dependencies>
</project> </project>
\ No newline at end of file \ No newline at end of file
package com.glsx.plat.swagger3.config;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.ExternalDocumentation;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import io.swagger.v3.oas.models.media.StringSchema;
import io.swagger.v3.oas.models.parameters.Parameter;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class OpenApiConfig {
@Value("${spring.application.name}")
private String application;
private static final String TOKEN_HEADER = "Authorization";
@Bean
public OpenAPI openApi() {
// 针对 knife4j(增强UI),这里添加全局请求头(addParameters)无效,只能按组添加,待官方解决
return new OpenAPI().components(new Components().addSecuritySchemes(TOKEN_HEADER,
new SecurityScheme()
.type(SecurityScheme.Type.APIKEY)
.scheme("bearer")//这里配置 bearer 后,你的请求里会自动在 token 前加上 Bearer
.bearerFormat("JWT")
).addParameters(TOKEN_HEADER,
new Parameter()
.in("header")
.schema(new StringSchema())
.name(TOKEN_HEADER)
))
.info(new Info()
.title(application + "文档")
.description("文档描述")
.contact(new Contact().name("作者").email("邮箱").url("可以填关联网站地址或不填"))
//参考 Apache 2.0 许可及地址,可以不配此项
.license(new License().name("Apache 2.0").url("https://www.apache.org/licenses/LICENSE-2.0.html"))
.version("0.1")
)
// 引入外部的文档,我这里引得是 springdoc 官方文档地址,你可以不配此项
.externalDocs(new ExternalDocumentation()
.description("SpringDoc Full Documentation")
.url("https://springdoc.org/")
);
}
// @Bean
// public OpenApiCustomiser sortTagsAlphabetically() {
// return openApi -> openApi.setTags(openApi.getTags()
// .stream()
// .sorted(Comparator.comparing(tag -> StringUtils.stripAccents(tag.getName())))
// .collect(Collectors.toList()));
// }
}
\ No newline at end of file \ No newline at end of file
package com.glsx.plat.swagger3.config; //package com.glsx.plat.swagger3.config;
//
import io.swagger.annotations.ApiOperation; //import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import org.springframework.beans.factory.annotation.Value; //import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean; //import org.springframework.beans.BeansException;
import org.springframework.context.annotation.Configuration; //import org.springframework.beans.factory.annotation.Value;
import springfox.documentation.builders.ApiInfoBuilder; //import org.springframework.beans.factory.config.BeanPostProcessor;
import springfox.documentation.builders.ParameterBuilder; //import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import springfox.documentation.builders.PathSelectors; //import org.springframework.context.annotation.Bean;
import springfox.documentation.builders.RequestHandlerSelectors; //import org.springframework.context.annotation.Configuration;
import springfox.documentation.oas.annotations.EnableOpenApi; //import org.springframework.util.ReflectionUtils;
import springfox.documentation.schema.ModelRef; //import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;
import springfox.documentation.service.*; //import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.spi.DocumentationType; //import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.spi.service.contexts.SecurityContext; //import springfox.documentation.builders.PathSelectors;
import springfox.documentation.spring.web.plugins.Docket; //import springfox.documentation.builders.RequestHandlerSelectors;
//import springfox.documentation.oas.annotations.EnableOpenApi;
import java.util.ArrayList; //import springfox.documentation.schema.ModelRef;
import java.util.Collections; //import springfox.documentation.service.*;
import java.util.List; //import springfox.documentation.spi.DocumentationType;
//import springfox.documentation.spi.service.contexts.SecurityContext;
@Configuration //import springfox.documentation.spring.web.plugins.Docket;
@EnableOpenApi //import springfox.documentation.spring.web.plugins.WebFluxRequestHandlerProvider;
public class Swagger3Config { //import springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider;
//
@Value("${swagger3.enable:false}") //import java.lang.reflect.Field;
private boolean enable; //import java.util.ArrayList;
//import java.util.Collections;
@Bean //import java.util.List;
public Docket createRestApi() { //import java.util.stream.Collectors;
ParameterBuilder ticketPar = new ParameterBuilder(); //
List<Parameter> pars = new ArrayList<>(); //@Configuration
ticketPar.name("Authorization").description("user ticket")//Token 以及Authorization 为自定义的参数,session保存的名字是哪个就可以写成那个 //@EnableOpenApi
.modelRef(new ModelRef("string")).parameterType("header") //@EnableKnife4j
.required(false).build(); //header中的ticket参数非必填,传空也可以 //@ConditionalOnProperty(prefix = "swagger", name = "enabled", matchIfMissing = true)
pars.add(ticketPar.build()); //根据每个方法名也知道当前方法在设置什么参数 //public class Swagger3Config {
//
return new Docket(DocumentationType.OAS_30) // @Value("${swagger.enable:false}")
.enable(enable) // private Boolean enable;
.apiInfo(apiInfo()) //
.select() // @Bean
//扫描所有有注解的api,用这种方式更灵活 // public Docket createRestApi() {
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) // ParameterBuilder ticketPar = new ParameterBuilder();
.paths(PathSelectors.any()) // List<Parameter> pars = new ArrayList<>();
.build() // ticketPar.name("Authorization").description("user ticket")//Token 以及Authorization 为自定义的参数,session保存的名字是哪个就可以写成那个
//支持的通讯协议集合 // .modelRef(new ModelRef("string")).parameterType("header")
//.protocols(Sets.newHashSet("https", "http")) // .required(false).build(); //header中的ticket参数非必填,传空也可以
.securitySchemes(securitySchemes()) // pars.add(ticketPar.build()); //根据每个方法名也知道当前方法在设置什么参数
.securityContexts(Collections.singletonList(securityContext())); //
} // return new Docket(DocumentationType.OAS_30)
// .enable(enable)
private ApiInfo apiInfo() { // .apiInfo(apiInfo())
return new ApiInfoBuilder() // .select()
.title("Spring Boot————Swagger3构建Restful APIs") // //扫描所有有注解的api,用这种方式更灵活
.description("XXX使用") // .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.termsOfServiceUrl("https://swagger.io") // .paths(PathSelectors.any())
.version("1.0.0") // .build()
.build(); // //支持的通讯协议集合
} // //.protocols(Sets.newHashSet("https", "http"))
// .securitySchemes(securitySchemes())
private List<SecurityScheme> securitySchemes() { // .securityContexts(Collections.singletonList(securityContext()));
List<SecurityScheme> apiKeyList = new ArrayList<>(); // }
//注意,这里应对应登录token鉴权对应的k-v //
apiKeyList.add(new ApiKey("Authorization", "Authorization", "header")); // private ApiInfo apiInfo() {
return apiKeyList; // return new ApiInfoBuilder()
} // .title("Spring Boot————Swagger3构建Restful APIs")
// .description("XXX使用")
/** // .termsOfServiceUrl("https://swagger.io")
* 这里设置 swagger2 认证的安全上下文 // .version("1.0.0")
*/ // .build();
private SecurityContext securityContext() { // }
return SecurityContext.builder() //
.securityReferences(Collections.singletonList(new SecurityReference("Authorization", scopes()))) // private List<SecurityScheme> securitySchemes() {
.build(); // List<SecurityScheme> apiKeyList = new ArrayList<>();
} // //注意,这里应对应登录token鉴权对应的k-v
// apiKeyList.add(new ApiKey("Authorization", "Authorization", "header"));
/** // return apiKeyList;
* 这里是写允许认证的scope // }
*/ //
private AuthorizationScope[] scopes() { // /**
return new AuthorizationScope[]{ // * 这里设置 swagger2 认证的安全上下文
new AuthorizationScope("web", "All scope is trusted!") // */
}; // private SecurityContext securityContext() {
} // return SecurityContext.builder()
// .securityReferences(Collections.singletonList(new SecurityReference("Authorization", scopes())))
} // .build();
// }
//
// /**
// * 这里是写允许认证的scope
// */
// private AuthorizationScope[] scopes() {
// return new AuthorizationScope[]{
// new AuthorizationScope("web", "All scope is trusted!")
// };
// }
//
// /**
// * 增加如下配置可解决Spring Boot 6.x 与Swagger 3.0.0 不兼容问题
// **/
// @Bean
// public static BeanPostProcessor springfoxHandlerProviderBeanPostProcessor() {
// return new BeanPostProcessor() {
//
// @Override
// public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
// if (bean instanceof WebMvcRequestHandlerProvider || bean instanceof WebFluxRequestHandlerProvider) {
// customizeSpringfoxHandlerMappings(getHandlerMappings(bean));
// }
// return bean;
// }
//
// private <T extends RequestMappingInfoHandlerMapping> void customizeSpringfoxHandlerMappings(List<T> mappings) {
// List<T> copy = mappings.stream()
// .filter(mapping -> mapping.getPatternParser() == null)
// .collect(Collectors.toList());
// mappings.clear();
// mappings.addAll(copy);
// }
//
// @SuppressWarnings("unchecked")
// private List<RequestMappingInfoHandlerMapping> getHandlerMappings(Object bean) {
// try {
// Field field = ReflectionUtils.findField(bean.getClass(), "handlerMappings");
// field.setAccessible(true);
// return (List<RequestMappingInfoHandlerMapping>) field.get(bean);
// } catch (IllegalArgumentException | IllegalAccessException e) {
// throw new IllegalStateException(e);
// }
// }
// };
// }
//
//}
...@@ -26,12 +26,7 @@ ...@@ -26,12 +26,7 @@
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.glsx</groupId> <groupId>com.glsx</groupId>
<artifactId>rest-admin-redis</artifactId>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-exception</artifactId> <artifactId>rest-admin-exception</artifactId>
<scope>compile</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
...@@ -44,6 +39,10 @@ ...@@ -44,6 +39,10 @@
</exclusions> </exclusions>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId> <groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId> <artifactId>spring-context</artifactId>
</dependency> </dependency>
......
...@@ -2,8 +2,11 @@ package com.glsx.plat.web.advice; ...@@ -2,8 +2,11 @@ package com.glsx.plat.web.advice;
import cn.hutool.json.JSONUtil; import cn.hutool.json.JSONUtil;
import com.glsx.plat.core.annotation.ResponseResultBody; import com.glsx.plat.core.annotation.ResponseResultBody;
import com.glsx.plat.core.web.OpenApiResult;
import com.glsx.plat.core.web.Result; import com.glsx.plat.core.web.Result;
import com.glsx.plat.exception.OpenApiResultException;
import com.glsx.plat.exception.ResultException; import com.glsx.plat.exception.ResultException;
import com.glsx.plat.exception.ServiceException;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter; import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.AnnotatedElementUtils; import org.springframework.core.annotation.AnnotatedElementUtils;
...@@ -44,6 +47,9 @@ public class ResponseResultBodyAdvice implements ResponseBodyAdvice<Object> { ...@@ -44,6 +47,9 @@ public class ResponseResultBodyAdvice implements ResponseBodyAdvice<Object> {
if (body instanceof Result) { if (body instanceof Result) {
return body; return body;
} }
if (body instanceof OpenApiResult) {
return body;
}
if (body instanceof String) { if (body instanceof String) {
return JSONUtil.toJsonStr(Result.success(body)); return JSONUtil.toJsonStr(Result.success(body));
} }
...@@ -65,24 +71,44 @@ public class ResponseResultBodyAdvice implements ResponseBodyAdvice<Object> { ...@@ -65,24 +71,44 @@ public class ResponseResultBodyAdvice implements ResponseBodyAdvice<Object> {
if (ex instanceof ResultException) { if (ex instanceof ResultException) {
return this.handleResultException((ResultException) ex, headers, request); return this.handleResultException((ResultException) ex, headers, request);
} }
if (ex instanceof ServiceException) {
ServiceException exception = (ServiceException) ex;
return this.handleResultException(ResultException.create(exception.getCode(), exception.getMessage()), headers, request);
}
return this.handleException(ex, headers, request); return this.handleException(ex, headers, request);
} }
@ExceptionHandler(OpenApiResultException.class)
public final ResponseEntity<OpenApiResult<?>> openApiResultExceptionHandler(Exception ex, WebRequest request) {
log.error("OpenApiResultExceptionHandler: {}", ex.getMessage());
ex.printStackTrace();
return this.handleResultException((OpenApiResultException) ex, new HttpHeaders(), request);
}
/** /**
* 对ResultException类返回返回结果的处理 * 对ResultException类返回返回结果的处理
*/ */
protected ResponseEntity<Result<?>> handleResultException(ResultException ex, HttpHeaders headers, WebRequest request) { protected ResponseEntity<Result<?>> handleResultException(ResultException ex, HttpHeaders headers, WebRequest request) {
Result<?> body = ex.getResultEntity(); Result<?> body = ex.getResultEntity();
return this.handleExceptionInternal(ex, body, headers, HttpStatus.INTERNAL_SERVER_ERROR, request); return this.handleResultExceptionInternal(ex, body, headers, HttpStatus.INTERNAL_SERVER_ERROR, request);
}
/**
* 对ResultException类返回返回结果的处理
*/
protected ResponseEntity<OpenApiResult<?>> handleResultException(OpenApiResultException ex, HttpHeaders headers, WebRequest request) {
OpenApiResult<?> body = ex.getResultEntity();
return this.handleOpenApiResultExceptionInternal(ex, body, headers, HttpStatus.INTERNAL_SERVER_ERROR, request);
} }
/** /**
* 异常类的统一处理 * 异常类的统一处理
*/ */
protected ResponseEntity<Result<?>> handleException(Exception ex, HttpHeaders headers, WebRequest request) { protected ResponseEntity<Result<?>> handleException(Exception ex, HttpHeaders headers, WebRequest request) {
Result<?> body = Result.failure(); //返回异常消息
HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR; HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
return this.handleExceptionInternal(ex, body, headers, status, request); Result<?> body = new Result(status.value(), ex.getMessage());
return this.handleResultExceptionInternal(ex, body, headers, status, request);
} }
/** /**
...@@ -93,12 +119,21 @@ public class ResponseResultBodyAdvice implements ResponseBodyAdvice<Object> { ...@@ -93,12 +119,21 @@ public class ResponseResultBodyAdvice implements ResponseBodyAdvice<Object> {
* request attribute and creates a {@link ResponseEntity} from the given * request attribute and creates a {@link ResponseEntity} from the given
* body, headers, and status. * body, headers, and status.
*/ */
protected ResponseEntity<Result<?>> handleExceptionInternal( protected ResponseEntity<Result<?>> handleResultExceptionInternal(
Exception ex, Result<?> body, HttpHeaders headers, HttpStatus status, WebRequest request) { Exception ex, Result<?> body, HttpHeaders headers, HttpStatus status, WebRequest request) {
if (HttpStatus.INTERNAL_SERVER_ERROR.equals(status)) {
request.setAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE, ex, WebRequest.SCOPE_REQUEST);
}
return new ResponseEntity<>(body, headers, status);
}
protected ResponseEntity<OpenApiResult<?>> handleOpenApiResultExceptionInternal(
Exception ex, OpenApiResult<?> body, HttpHeaders headers, HttpStatus status, WebRequest request) {
if (HttpStatus.INTERNAL_SERVER_ERROR.equals(status)) { if (HttpStatus.INTERNAL_SERVER_ERROR.equals(status)) {
request.setAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE, ex, WebRequest.SCOPE_REQUEST); request.setAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE, ex, WebRequest.SCOPE_REQUEST);
} }
return new ResponseEntity<>(body, headers, status); return new ResponseEntity<>(body, headers, status);
} }
} }
...@@ -34,7 +34,7 @@ public class CorsFilter implements Filter { ...@@ -34,7 +34,7 @@ public class CorsFilter implements Filter {
response.setHeader("Access-Control-Allow-Origin", reqs.getHeader("Origin")); response.setHeader("Access-Control-Allow-Origin", reqs.getHeader("Origin"));
response.setHeader("Access-Control-Allow-Credentials", "true"); response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "GET, POST, HEAD, PUT, DELETE, OPTIONS"); response.setHeader("Access-Control-Allow-Methods", "GET, POST, HEAD, PUT, DELETE, OPTIONS");
response.setHeader("Access-Control-Allow-Headers", HttpHeaders.AUTHORIZATION + ", Accept, Origin, X-Requested-With, Content-Type, Last-Modified"); response.setHeader("Access-Control-Allow-Headers", HttpHeaders.AUTHORIZATION + ", Accept, Origin, X-Requested-With, Content-Type, Last-Modified, Authorization-Org");
response.setHeader("Access-Control-Expose-Headers", HttpHeaders.AUTHORIZATION); response.setHeader("Access-Control-Expose-Headers", HttpHeaders.AUTHORIZATION);
response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Max-Age", "3600");
if ("OPTIONS".equalsIgnoreCase(((HttpServletRequest) req).getMethod())) { if ("OPTIONS".equalsIgnoreCase(((HttpServletRequest) req).getMethod())) {
......
...@@ -3,12 +3,12 @@ package com.glsx.plat.web.interceptor; ...@@ -3,12 +3,12 @@ package com.glsx.plat.web.interceptor;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.glsx.plat.common.annotation.CheckSign; import com.glsx.plat.common.annotation.CheckSign;
import com.glsx.plat.common.annotation.NoLogin; import com.glsx.plat.common.annotation.NoLogin;
import com.glsx.plat.common.utils.IpUtils;
import com.glsx.plat.common.utils.StringUtils; import com.glsx.plat.common.utils.StringUtils;
import com.glsx.plat.core.web.R; import com.glsx.plat.core.web.R;
import com.glsx.plat.exception.SystemMessage; import com.glsx.plat.exception.SystemMessage;
import com.glsx.plat.jwt.base.BaseJwtUser; import com.glsx.plat.jwt.base.BaseJwtUser;
import com.glsx.plat.jwt.util.JwtUtils; import com.glsx.plat.jwt.util.JwtUtils;
import com.glsx.plat.web.utils.IpUtils;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders; import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
......
...@@ -26,7 +26,7 @@ ...@@ -26,7 +26,7 @@
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.glsx</groupId> <groupId>com.glsx</groupId>
<artifactId>rest-admin-swagger2</artifactId> <artifactId>rest-admin-swagger3</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.github.binarywang</groupId> <groupId>com.github.binarywang</groupId>
......
...@@ -3,8 +3,6 @@ package com.glsx.plat.wechat.modules.controller; ...@@ -3,8 +3,6 @@ package com.glsx.plat.wechat.modules.controller;
import com.github.binarywang.wxpay.bean.entpay.*; import com.github.binarywang.wxpay.bean.entpay.*;
import com.github.binarywang.wxpay.exception.WxPayException; import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService; import com.github.binarywang.wxpay.service.WxPayService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
...@@ -16,7 +14,7 @@ import org.springframework.web.bind.annotation.*; ...@@ -16,7 +14,7 @@ import org.springframework.web.bind.annotation.*;
* *
* @author <a href="https://github.com/binarywang">Binary Wang</a> * @author <a href="https://github.com/binarywang">Binary Wang</a>
*/ */
@Api("企业付款") //@Api("企业付款")
@RequestMapping("/pay") @RequestMapping("/pay")
@RestController @RestController
@AllArgsConstructor @AllArgsConstructor
...@@ -35,7 +33,7 @@ public class EntPayController { ...@@ -35,7 +33,7 @@ public class EntPayController {
* *
* @param request 请求对象 * @param request 请求对象
*/ */
@ApiOperation(value = "企业付款到零钱") // @ApiOperation(value = "企业付款到零钱")
@PostMapping("/entPay") @PostMapping("/entPay")
public EntPayResult entPay(@RequestBody EntPayRequest request) throws WxPayException { public EntPayResult entPay(@RequestBody EntPayRequest request) throws WxPayException {
return this.wxService.getEntPayService().entPay(request); return this.wxService.getEntPayService().entPay(request);
...@@ -51,7 +49,7 @@ public class EntPayController { ...@@ -51,7 +49,7 @@ public class EntPayController {
* *
* @param partnerTradeNo 商户订单号 * @param partnerTradeNo 商户订单号
*/ */
@ApiOperation(value = "查询企业付款到零钱的结果") // @ApiOperation(value = "查询企业付款到零钱的结果")
@GetMapping("/queryEntPay/{partnerTradeNo}") @GetMapping("/queryEntPay/{partnerTradeNo}")
public EntPayQueryResult queryEntPay(@PathVariable String partnerTradeNo) throws WxPayException { public EntPayQueryResult queryEntPay(@PathVariable String partnerTradeNo) throws WxPayException {
return this.wxService.getEntPayService().queryEntPay(partnerTradeNo); return this.wxService.getEntPayService().queryEntPay(partnerTradeNo);
...@@ -77,7 +75,7 @@ public class EntPayController { ...@@ -77,7 +75,7 @@ public class EntPayController {
* @return the public key * @return the public key
* @throws WxPayException the wx pay exception * @throws WxPayException the wx pay exception
*/ */
@ApiOperation(value = "获取RSA加密公钥") // @ApiOperation(value = "获取RSA加密公钥")
@GetMapping("/getPublicKey") @GetMapping("/getPublicKey")
public String getPublicKey() throws WxPayException { public String getPublicKey() throws WxPayException {
return this.wxService.getEntPayService().getPublicKey(); return this.wxService.getEntPayService().getPublicKey();
...@@ -96,7 +94,7 @@ public class EntPayController { ...@@ -96,7 +94,7 @@ public class EntPayController {
* @return the ent pay bank result * @return the ent pay bank result
* @throws WxPayException the wx pay exception * @throws WxPayException the wx pay exception
*/ */
@ApiOperation(value = "企业付款到银行卡") // @ApiOperation(value = "企业付款到银行卡")
@PostMapping("/payBank") @PostMapping("/payBank")
public EntPayBankResult payBank(EntPayBankRequest request) throws WxPayException { public EntPayBankResult payBank(EntPayBankRequest request) throws WxPayException {
return this.wxService.getEntPayService().payBank(request); return this.wxService.getEntPayService().payBank(request);
...@@ -114,7 +112,7 @@ public class EntPayController { ...@@ -114,7 +112,7 @@ public class EntPayController {
* @return the ent pay bank query result * @return the ent pay bank query result
* @throws WxPayException the wx pay exception * @throws WxPayException the wx pay exception
*/ */
@ApiOperation(value = "查询企业付款到银行卡的结果") // @ApiOperation(value = "查询企业付款到银行卡的结果")
@GetMapping("/queryPayBank/{partnerTradeNo}") @GetMapping("/queryPayBank/{partnerTradeNo}")
public EntPayBankQueryResult queryPayBank(@PathVariable String partnerTradeNo) throws WxPayException { public EntPayBankQueryResult queryPayBank(@PathVariable String partnerTradeNo) throws WxPayException {
return this.wxService.getEntPayService().queryPayBank(partnerTradeNo); return this.wxService.getEntPayService().queryPayBank(partnerTradeNo);
......
...@@ -12,8 +12,6 @@ import com.github.binarywang.wxpay.service.WxPayService; ...@@ -12,8 +12,6 @@ import com.github.binarywang.wxpay.service.WxPayService;
import com.glsx.plat.common.annotation.SysLog; import com.glsx.plat.common.annotation.SysLog;
import com.glsx.plat.common.utils.SnowFlake; import com.glsx.plat.common.utils.SnowFlake;
import com.glsx.plat.core.web.R; import com.glsx.plat.core.web.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
...@@ -26,7 +24,7 @@ import java.util.Map; ...@@ -26,7 +24,7 @@ import java.util.Map;
* @author Binary Wang * @author Binary Wang
*/ */
@Slf4j @Slf4j
@Api("微信支付") //@Api("微信支付")
@RestController @RestController
@RequestMapping("/pay") @RequestMapping("/pay")
@AllArgsConstructor @AllArgsConstructor
...@@ -49,7 +47,7 @@ public abstract class WxPayController { ...@@ -49,7 +47,7 @@ public abstract class WxPayController {
* @param transactionId 微信订单号 * @param transactionId 微信订单号
* @param outTradeNo 商户系统内部的订单号,当没提供transactionId时需要传这个。 * @param outTradeNo 商户系统内部的订单号,当没提供transactionId时需要传这个。
*/ */
@ApiOperation(value = "查询订单") // @ApiOperation(value = "查询订单")
@GetMapping("/queryOrder") @GetMapping("/queryOrder")
public WxPayOrderQueryResult queryOrder(@RequestParam(required = false) String transactionId, public WxPayOrderQueryResult queryOrder(@RequestParam(required = false) String transactionId,
@RequestParam(required = false) String outTradeNo) @RequestParam(required = false) String outTradeNo)
...@@ -57,7 +55,7 @@ public abstract class WxPayController { ...@@ -57,7 +55,7 @@ public abstract class WxPayController {
return this.wxPayService.queryOrder(transactionId, outTradeNo); return this.wxPayService.queryOrder(transactionId, outTradeNo);
} }
@ApiOperation(value = "查询订单") // @ApiOperation(value = "查询订单")
@PostMapping("/queryOrder") @PostMapping("/queryOrder")
public WxPayOrderQueryResult queryOrder(@RequestBody WxPayOrderQueryRequest wxPayOrderQueryRequest) throws WxPayException { public WxPayOrderQueryResult queryOrder(@RequestBody WxPayOrderQueryRequest wxPayOrderQueryRequest) throws WxPayException {
return this.wxPayService.queryOrder(wxPayOrderQueryRequest); return this.wxPayService.queryOrder(wxPayOrderQueryRequest);
...@@ -77,13 +75,13 @@ public abstract class WxPayController { ...@@ -77,13 +75,13 @@ public abstract class WxPayController {
* *
* @param outTradeNo 商户系统内部的订单号 * @param outTradeNo 商户系统内部的订单号
*/ */
@ApiOperation(value = "关闭订单") // @ApiOperation(value = "关闭订单")
@GetMapping("/closeOrder/{outTradeNo}") @GetMapping("/closeOrder/{outTradeNo}")
public WxPayOrderCloseResult closeOrder(@PathVariable String outTradeNo) throws WxPayException { public WxPayOrderCloseResult closeOrder(@PathVariable String outTradeNo) throws WxPayException {
return this.wxPayService.closeOrder(outTradeNo); return this.wxPayService.closeOrder(outTradeNo);
} }
@ApiOperation(value = "关闭订单") // @ApiOperation(value = "关闭订单")
@PostMapping("/closeOrder") @PostMapping("/closeOrder")
public WxPayOrderCloseResult closeOrder(@RequestBody WxPayOrderCloseRequest wxPayOrderCloseRequest) throws WxPayException { public WxPayOrderCloseResult closeOrder(@RequestBody WxPayOrderCloseRequest wxPayOrderCloseRequest) throws WxPayException {
return this.wxPayService.closeOrder(wxPayOrderCloseRequest); return this.wxPayService.closeOrder(wxPayOrderCloseRequest);
...@@ -96,7 +94,7 @@ public abstract class WxPayController { ...@@ -96,7 +94,7 @@ public abstract class WxPayController {
* @param <T> 请使用{@link com.github.binarywang.wxpay.bean.order}包下的类 * @param <T> 请使用{@link com.github.binarywang.wxpay.bean.order}包下的类
* @return 返回 {@link com.github.binarywang.wxpay.bean.order}包下的类对象 * @return 返回 {@link com.github.binarywang.wxpay.bean.order}包下的类对象
*/ */
@ApiOperation(value = "统一下单,并组装所需支付参数") // @ApiOperation(value = "统一下单,并组装所需支付参数")
@PostMapping("/createOrder") @PostMapping("/createOrder")
public <T> T createOrder(@RequestBody WxPayUnifiedOrderRequest request) throws WxPayException { public <T> T createOrder(@RequestBody WxPayUnifiedOrderRequest request) throws WxPayException {
return this.wxPayService.createOrder(request); return this.wxPayService.createOrder(request);
...@@ -110,7 +108,7 @@ public abstract class WxPayController { ...@@ -110,7 +108,7 @@ public abstract class WxPayController {
* @param request 请求对象,注意一些参数如appid、mchid等不用设置,方法内会自动从配置对象中获取到(前提是对应配置中已经设置) * @param request 请求对象,注意一些参数如appid、mchid等不用设置,方法内会自动从配置对象中获取到(前提是对应配置中已经设置)
*/ */
@SysLog @SysLog
@ApiOperation(value = "原生的统一下单接口") // @ApiOperation(value = "原生的统一下单接口")
@PostMapping("/unifiedOrder") @PostMapping("/unifiedOrder")
public R<WxPayUnifiedOrderResult> unifiedOrder(@RequestBody WxPayUnifiedOrderRequest request) throws WxPayException { public R<WxPayUnifiedOrderResult> unifiedOrder(@RequestBody WxPayUnifiedOrderRequest request) throws WxPayException {
String outTradeNo = "B" + SnowFlake.nextSerialNumber(); String outTradeNo = "B" + SnowFlake.nextSerialNumber();
...@@ -137,7 +135,7 @@ public abstract class WxPayController { ...@@ -137,7 +135,7 @@ public abstract class WxPayController {
* @param request 请求对象 * @param request 请求对象
* @return 退款操作结果 * @return 退款操作结果
*/ */
@ApiOperation(value = "退款") // @ApiOperation(value = "退款")
@PostMapping("/refund") @PostMapping("/refund")
public WxPayRefundResult refund(@RequestBody WxPayRefundRequest request) throws WxPayException { public WxPayRefundResult refund(@RequestBody WxPayRefundRequest request) throws WxPayException {
return this.wxPayService.refund(request); return this.wxPayService.refund(request);
...@@ -160,7 +158,7 @@ public abstract class WxPayController { ...@@ -160,7 +158,7 @@ public abstract class WxPayController {
* @param refundId 微信退款单号 * @param refundId 微信退款单号
* @return 退款信息 * @return 退款信息
*/ */
@ApiOperation(value = "退款查询") // @ApiOperation(value = "退款查询")
@GetMapping("/refundQuery") @GetMapping("/refundQuery")
public WxPayRefundQueryResult refundQuery(@RequestParam(required = false) String transactionId, public WxPayRefundQueryResult refundQuery(@RequestParam(required = false) String transactionId,
@RequestParam(required = false) String outTradeNo, @RequestParam(required = false) String outTradeNo,
...@@ -170,13 +168,13 @@ public abstract class WxPayController { ...@@ -170,13 +168,13 @@ public abstract class WxPayController {
return this.wxPayService.refundQuery(transactionId, outTradeNo, outRefundNo, refundId); return this.wxPayService.refundQuery(transactionId, outTradeNo, outRefundNo, refundId);
} }
@ApiOperation(value = "退款查询") // @ApiOperation(value = "退款查询")
@PostMapping("/refundQuery") @PostMapping("/refundQuery")
public WxPayRefundQueryResult refundQuery(@RequestBody WxPayRefundQueryRequest wxPayRefundQueryRequest) throws WxPayException { public WxPayRefundQueryResult refundQuery(@RequestBody WxPayRefundQueryRequest wxPayRefundQueryRequest) throws WxPayException {
return this.wxPayService.refundQuery(wxPayRefundQueryRequest); return this.wxPayService.refundQuery(wxPayRefundQueryRequest);
} }
@ApiOperation(value = "支付回调通知处理") // @ApiOperation(value = "支付回调通知处理")
@PostMapping("/notify/order") @PostMapping("/notify/order")
public String parseOrderNotifyResult(@RequestBody String xmlData) throws WxPayException { public String parseOrderNotifyResult(@RequestBody String xmlData) throws WxPayException {
final WxPayOrderNotifyResult notifyResult = this.wxPayService.parseOrderNotifyResult(xmlData); final WxPayOrderNotifyResult notifyResult = this.wxPayService.parseOrderNotifyResult(xmlData);
...@@ -192,7 +190,7 @@ public abstract class WxPayController { ...@@ -192,7 +190,7 @@ public abstract class WxPayController {
return WxPayNotifyResponse.success("成功"); return WxPayNotifyResponse.success("成功");
} }
@ApiOperation(value = "退款回调通知处理") // @ApiOperation(value = "退款回调通知处理")
@PostMapping("/notify/refund") @PostMapping("/notify/refund")
public String parseRefundNotifyResult(@RequestBody String xmlData) throws WxPayException { public String parseRefundNotifyResult(@RequestBody String xmlData) throws WxPayException {
final WxPayRefundNotifyResult result = this.wxPayService.parseRefundNotifyResult(xmlData); final WxPayRefundNotifyResult result = this.wxPayService.parseRefundNotifyResult(xmlData);
...@@ -200,7 +198,7 @@ public abstract class WxPayController { ...@@ -200,7 +198,7 @@ public abstract class WxPayController {
return WxPayNotifyResponse.success("成功"); return WxPayNotifyResponse.success("成功");
} }
@ApiOperation(value = "扫码支付回调通知处理") // @ApiOperation(value = "扫码支付回调通知处理")
@PostMapping("/notify/scanpay") @PostMapping("/notify/scanpay")
public String parseScanPayNotifyResult(String xmlData) throws WxPayException { public String parseScanPayNotifyResult(String xmlData) throws WxPayException {
final WxScanPayNotifyResult result = this.wxPayService.parseScanPayNotifyResult(xmlData); final WxScanPayNotifyResult result = this.wxPayService.parseScanPayNotifyResult(xmlData);
...@@ -220,7 +218,7 @@ public abstract class WxPayController { ...@@ -220,7 +218,7 @@ public abstract class WxPayController {
* *
* @param request 请求对象 * @param request 请求对象
*/ */
@ApiOperation(value = "发送红包") // @ApiOperation(value = "发送红包")
@PostMapping("/sendRedpack") @PostMapping("/sendRedpack")
public WxPaySendRedpackResult sendRedpack(@RequestBody WxPaySendRedpackRequest request) throws WxPayException { public WxPaySendRedpackResult sendRedpack(@RequestBody WxPaySendRedpackRequest request) throws WxPayException {
return this.wxPayService.getRedpackService().sendRedpack(request); return this.wxPayService.getRedpackService().sendRedpack(request);
...@@ -237,7 +235,7 @@ public abstract class WxPayController { ...@@ -237,7 +235,7 @@ public abstract class WxPayController {
* *
* @param mchBillNo 商户发放红包的商户订单号,比如10000098201411111234567890 * @param mchBillNo 商户发放红包的商户订单号,比如10000098201411111234567890
*/ */
@ApiOperation(value = "查询红包") // @ApiOperation(value = "查询红包")
@GetMapping("/queryRedpack/{mchBillNo}") @GetMapping("/queryRedpack/{mchBillNo}")
public WxPayRedpackQueryResult queryRedpack(@PathVariable String mchBillNo) throws WxPayException { public WxPayRedpackQueryResult queryRedpack(@PathVariable String mchBillNo) throws WxPayException {
return this.wxPayService.getRedpackService().queryRedpack(mchBillNo); return this.wxPayService.getRedpackService().queryRedpack(mchBillNo);
...@@ -305,7 +303,7 @@ public abstract class WxPayController { ...@@ -305,7 +303,7 @@ public abstract class WxPayController {
* 是否需要证书:不需要 * 是否需要证书:不需要
* </pre> * </pre>
*/ */
@ApiOperation(value = "提交交易保障数据") // @ApiOperation(value = "提交交易保障数据")
@PostMapping("/report") @PostMapping("/report")
public void report(@RequestBody WxPayReportRequest request) throws WxPayException { public void report(@RequestBody WxPayReportRequest request) throws WxPayException {
this.wxPayService.report(request); this.wxPayService.report(request);
...@@ -330,14 +328,14 @@ public abstract class WxPayController { ...@@ -330,14 +328,14 @@ public abstract class WxPayController {
* @param deviceInfo 设备号 device_info 非必传参数,终端设备号 * @param deviceInfo 设备号 device_info 非必传参数,终端设备号
* @return 保存到本地的临时文件 * @return 保存到本地的临时文件
*/ */
@ApiOperation(value = "下载对账单") // @ApiOperation(value = "下载对账单")
@GetMapping("/downloadBill/{billDate}/{billType}/{tarType}/{deviceInfo}") @GetMapping("/downloadBill/{billDate}/{billType}/{tarType}/{deviceInfo}")
public WxPayBillResult downloadBill(@PathVariable String billDate, @PathVariable String billType, public WxPayBillResult downloadBill(@PathVariable String billDate, @PathVariable String billType,
@PathVariable String tarType, @PathVariable String deviceInfo) throws WxPayException { @PathVariable String tarType, @PathVariable String deviceInfo) throws WxPayException {
return this.wxPayService.downloadBill(billDate, billType, tarType, deviceInfo); return this.wxPayService.downloadBill(billDate, billType, tarType, deviceInfo);
} }
@ApiOperation(value = "下载对账单") // @ApiOperation(value = "下载对账单")
@PostMapping("/downloadBill") @PostMapping("/downloadBill")
public WxPayBillResult downloadBill(WxPayDownloadBillRequest wxPayDownloadBillRequest) throws WxPayException { public WxPayBillResult downloadBill(WxPayDownloadBillRequest wxPayDownloadBillRequest) throws WxPayException {
return this.wxPayService.downloadBill(wxPayDownloadBillRequest); return this.wxPayService.downloadBill(wxPayDownloadBillRequest);
...@@ -355,7 +353,7 @@ public abstract class WxPayController { ...@@ -355,7 +353,7 @@ public abstract class WxPayController {
* 是否需要证书:不需要。 * 是否需要证书:不需要。
* </pre> * </pre>
*/ */
@ApiOperation(value = "提交刷卡支付") // @ApiOperation(value = "提交刷卡支付")
@PostMapping("/micropay") @PostMapping("/micropay")
public WxPayMicropayResult micropay(@RequestBody WxPayMicropayRequest request) throws WxPayException { public WxPayMicropayResult micropay(@RequestBody WxPayMicropayRequest request) throws WxPayException {
return this.wxPayService.micropay(request); return this.wxPayService.micropay(request);
...@@ -373,37 +371,37 @@ public abstract class WxPayController { ...@@ -373,37 +371,37 @@ public abstract class WxPayController {
* 是否需要证书:请求需要双向证书。 * 是否需要证书:请求需要双向证书。
* </pre> * </pre>
*/ */
@ApiOperation(value = "撤销订单") // @ApiOperation(value = "撤销订单")
@PostMapping("/reverseOrder") @PostMapping("/reverseOrder")
public WxPayOrderReverseResult reverseOrder(@RequestBody WxPayOrderReverseRequest request) throws WxPayException { public WxPayOrderReverseResult reverseOrder(@RequestBody WxPayOrderReverseRequest request) throws WxPayException {
return this.wxPayService.reverseOrder(request); return this.wxPayService.reverseOrder(request);
} }
@ApiOperation(value = "获取沙箱环境签名key") // @ApiOperation(value = "获取沙箱环境签名key")
@GetMapping("/getSandboxSignKey") @GetMapping("/getSandboxSignKey")
public String getSandboxSignKey() throws WxPayException { public String getSandboxSignKey() throws WxPayException {
return this.wxPayService.getSandboxSignKey(); return this.wxPayService.getSandboxSignKey();
} }
@ApiOperation(value = "发放代金券") // @ApiOperation(value = "发放代金券")
@PostMapping("/sendCoupon") @PostMapping("/sendCoupon")
public WxPayCouponSendResult sendCoupon(@RequestBody WxPayCouponSendRequest request) throws WxPayException { public WxPayCouponSendResult sendCoupon(@RequestBody WxPayCouponSendRequest request) throws WxPayException {
return this.wxPayService.sendCoupon(request); return this.wxPayService.sendCoupon(request);
} }
@ApiOperation(value = "查询代金券批次") // @ApiOperation(value = "查询代金券批次")
@PostMapping("/queryCouponStock") @PostMapping("/queryCouponStock")
public WxPayCouponStockQueryResult queryCouponStock(@RequestBody WxPayCouponStockQueryRequest request) throws WxPayException { public WxPayCouponStockQueryResult queryCouponStock(@RequestBody WxPayCouponStockQueryRequest request) throws WxPayException {
return this.wxPayService.queryCouponStock(request); return this.wxPayService.queryCouponStock(request);
} }
@ApiOperation(value = "查询代金券信息") // @ApiOperation(value = "查询代金券信息")
@PostMapping("/queryCouponInfo") @PostMapping("/queryCouponInfo")
public WxPayCouponInfoQueryResult queryCouponInfo(@RequestBody WxPayCouponInfoQueryRequest request) throws WxPayException { public WxPayCouponInfoQueryResult queryCouponInfo(@RequestBody WxPayCouponInfoQueryRequest request) throws WxPayException {
return this.wxPayService.queryCouponInfo(request); return this.wxPayService.queryCouponInfo(request);
} }
@ApiOperation(value = "拉取订单评价数据") // @ApiOperation(value = "拉取订单评价数据")
@PostMapping("/queryComment") @PostMapping("/queryComment")
public String queryComment(Date beginDate, Date endDate, Integer offset, Integer limit) throws WxPayException { public String queryComment(Date beginDate, Date endDate, Integer offset, Integer limit) throws WxPayException {
return this.wxPayService.queryComment(beginDate, endDate, offset, limit); return this.wxPayService.queryComment(beginDate, endDate, offset, limit);
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!