提交 a2a44677 authored 作者: 陈世营's avatar 陈世营

Initial commit

上级
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**
!**/src/test/**
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
### VS Code ###
.vscode/
/*
* Copyright 2007-present the original author or authors.
*
* Licensed 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
*
* https://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 java.net.*;
import java.io.*;
import java.nio.channels.*;
import java.util.Properties;
public class MavenWrapperDownloader {
private static final String WRAPPER_VERSION = "0.5.6";
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
+ WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
* use instead of the default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
".mvn/wrapper/maven-wrapper.properties";
/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH =
".mvn/wrapper/maven-wrapper.jar";
/**
* Name of the property which should be used to override the default download url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
public static void main(String args[]) {
System.out.println("- Downloader started");
File baseDirectory = new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
// If the maven-wrapper.properties exists, read it and check if it contains a custom
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if(mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if(mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if(!outputFile.getParentFile().exists()) {
if(!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url, outputFile);
System.out.println("Done");
System.exit(0);
} catch (Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
String username = System.getenv("MVNW_USERNAME");
char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
}
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar
差异被折叠。
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM https://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
)
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%" == "on" pause
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
exit /B %ERROR_CODE%
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-build</artifactId>
<version>2.0.6.RELEASE</version>
<relativePath/>
</parent>
<groupId>com.timeloit.cloud</groupId>
<artifactId>spring-cloud-timeloit</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>pom</packaging>
<name>Spring Cloud Timeloit</name>
<description>Spring Cloud Timeloit</description>
<modules>
<module>spring-cloud-timeloit-dependencies</module>
<module>spring-cloud-timeloit-nacos-discovery</module>
<module>spring-cloud-timeloit-examples</module>
<module>spring-cloud-timeloit-seata</module>
<module>spring-cloud-timeloit-sentinel</module>
<module>spring-cloud-timeloit-sentinel-datasource</module>
<module>spring-cloud-starter-timeloit</module>
<module>spring-cloud-timeloit-nacos-config</module>
<module>spring-cloud-timeloit-sentinel-gateway</module>
</modules>
<developers>
<developer>
<name>chenshiying</name>
<email>512889371@qq.com</email>
</developer>
</developers>
<properties>
<!-- Dependency Versions -->
<spring-cloud-commons.version>2.0.4.RELEASE</spring-cloud-commons.version>
<spring-cloud-netflix.version>2.0.4.RELEASE</spring-cloud-netflix.version>
<spring-cloud-openfeign.version>2.0.4.RELEASE</spring-cloud-openfeign.version>
<spring-cloud-bus.version>2.0.2.RELEASE</spring-cloud-bus.version>
<spring-cloud-gateway.version>2.0.4.RELEASE</spring-cloud-gateway.version>
<junit.version>4.12</junit.version>
<javax-servlet-api>3.0</javax-servlet-api>
<slf4j-api.version>1.7.25</slf4j-api.version>
<!-- Maven Plugin Versions -->
<maven-compiler-plugin.version>3.7.0</maven-compiler-plugin.version>
<maven-deploy-plugin.version>2.8.2</maven-deploy-plugin.version>
<maven-surefire-plugin.version>2.21.0</maven-surefire-plugin.version>
<gmavenplus-plugin.version>1.6</gmavenplus-plugin.version>
<jacoco.version>0.8.3</jacoco.version>
</properties>
<dependencyManagement>
<dependencies>
<!-- Spring Boot -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>com.timeloit.cloud</groupId>
<artifactId>spring-cloud-timeloit-dependencies</artifactId>
<version>${project.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-commons-dependencies</artifactId>
<version>${spring-cloud-commons.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-test-support</artifactId>
<scope>test</scope>
<version>${spring-cloud-commons.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-netflix</artifactId>
<version>${spring-cloud-netflix.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-openfeign-dependencies</artifactId>
<version>${spring-cloud-openfeign.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-bus-dependencies</artifactId>
<version>${spring-cloud-bus.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-gateway-dependencies</artifactId>
<version>${spring-cloud-gateway.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<inherited>true</inherited>
<configuration>
<source>1.8</source>
<target>1.8</target>
<parameters>true</parameters>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<inherited>true</inherited>
<configuration>
<forkCount>1</forkCount>
<reuseForks>false</reuseForks>
</configuration>
</plugin>
</plugins>
</build>
<distributionManagement>
<repository>
<id>nexus-releases</id>
<name>Nexus Release Repository</name>
<url>http://39.100.254.140:12010/repository/maven-releases/</url>
</repository>
<snapshotRepository>
<id>nexus-snapshots</id>
<name>Nexus Snapshot Repository</name>
<url>http://39.100.254.140:12010/repository/maven-snapshots/</url>
</snapshotRepository>
</distributionManagement>
<repositories>
<repository>
<id>nexus-loit-dev</id>
<name>Nexus Repository</name>
<url>http://39.100.254.140:12010/repository/maven-public/</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
<releases>
<enabled>true</enabled>
</releases>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>nexus-loit-dev</id>
<name>Nexus Plugin Repository</name>
<url>http://39.100.254.140:12010/repository/maven-public/</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
<releases>
<enabled>true</enabled>
</releases>
</pluginRepository>
</pluginRepositories>
</project>
<?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>spring-cloud-timeloit</artifactId>
<groupId>com.timeloit.cloud</groupId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-cloud-starter-timeloit</artifactId>
<packaging>pom</packaging>
<name>Spring Cloud Timeloit Starters</name>
<description>Spring Cloud Timeloit Starters</description>
<modules>
<module>spring-cloud-starter-timeloit-sentinel</module>
<module>spring-cloud-starter-timeloit-nacos-discovery</module>
</modules>
</project>
\ 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>spring-cloud-starter-timeloit</artifactId>
<groupId>com.timeloit.cloud</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-cloud-starter-timeloit-nacos-discovery</artifactId>
<name>Spring Cloud Starter Timeloit Nacos Discovery</name>
<dependencies>
<dependency>
<groupId>com.timeloit.cloud</groupId>
<artifactId>spring-cloud-timeloit-nacos-discovery</artifactId>
</dependency>
</dependencies>
</project>
\ 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>spring-cloud-starter-timeloit</artifactId>
<groupId>com.timeloit.cloud</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-cloud-starter-timeloit-sentinel</artifactId>
<name>Spring Cloud Starter Timeloit Sentinel</name>
<dependencies>
<dependency>
<groupId>com.timeloit.cloud</groupId>
<artifactId>spring-cloud-timeloit-sentinel</artifactId>
</dependency>
</dependencies>
</project>
\ 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>spring-cloud-timeloit</artifactId>
<groupId>com.timeloit.cloud</groupId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-cloud-timeloit-examples</artifactId>
<packaging>pom</packaging>
<name>Spring Cloud Timeloit Examples</name>
<description>Example showing how to use features of Spring Cloud Timeloit</description>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<version>${maven-deploy-plugin.version}</version>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**
!**/src/test/**
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
### VS Code ###
.vscode/
/*
* Copyright 2007-present the original author or authors.
*
* Licensed 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
*
* https://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 java.net.*;
import java.io.*;
import java.nio.channels.*;
import java.util.Properties;
public class MavenWrapperDownloader {
private static final String WRAPPER_VERSION = "0.5.6";
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
+ WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
* use instead of the default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
".mvn/wrapper/maven-wrapper.properties";
/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH =
".mvn/wrapper/maven-wrapper.jar";
/**
* Name of the property which should be used to override the default download url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
public static void main(String args[]) {
System.out.println("- Downloader started");
File baseDirectory = new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
// If the maven-wrapper.properties exists, read it and check if it contains a custom
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if(mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if(mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if(!outputFile.getParentFile().exists()) {
if(!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url, outputFile);
System.out.println("Done");
System.exit(0);
} catch (Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
String username = System.getenv("MVNW_USERNAME");
char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
}
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar
Git 全局设置
```
git config --global user.name "xxx"
git config --global user.email "ddd@qq.com"
```
创建新版本库
```
git clone ssh://git@192.168.66.40:2222/loit-Infrastructure/loit-seata-order-example.git
cd loit-seata-order-example
touch README.md
git add README.md
git commit -m "add README"
git push -u origin master
```
已存在的文件夹
```
cd existing_folder
git init
git remote add origin ssh://git@192.168.66.40:2222/loit-Infrastructure/loit-seata-order-example.git
git add .
git commit -m "Initial commit"
git push -u origin master
```
已存在的 Git 版本库
```
cd existing_repo
git remote rename origin old-origin
git remote add origin ssh://git@192.168.66.40:2222/loit-Infrastructure/loit-seata-order-example.git
git push -u origin --all
git push -u origin --tags
```
<?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>spring-cloud-dependencies-parent</artifactId>
<groupId>org.springframework.cloud</groupId>
<version>2.0.6.RELEASE</version>
<relativePath/>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.timeloit.project</groupId>
<artifactId>loit-seata-order-example-dependencies</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<properties>
<!-- Maven Plugin Versions -->
<maven-compiler-plugin.version>3.7.0</maven-compiler-plugin.version>
<maven-deploy-plugin.version>2.8.2</maven-deploy-plugin.version>
<loit-seata-mybatis-mysql-suport.version>0.0.1-SNAPSHOT</loit-seata-mybatis-mysql-suport.version>
<fastjson.version>1.2.41</fastjson.version>
<swagger.version>2.9.2</swagger.version>
<swagger-annotations.version>1.5.22</swagger-annotations.version>
<swagger-models.version>1.5.22</swagger-models.version>
<modelmapper.version>1.1.0</modelmapper.version>
<spring-tuple.version>1.0.0.RELEASE</spring-tuple.version>
<loit-build-spi-common.version>1.0-SNAPSHOT</loit-build-spi-common.version>
<loit-build-web-common.version>1.0-SNAPSHOT</loit-build-web-common.version>
</properties>
<dependencyManagement>
<dependencies>
<!--Own dependencies -->
<dependency>
<groupId>com.timeloit.project</groupId>
<artifactId>loit-build-spi-common</artifactId>
<version>${loit-build-spi-common.version}</version>
</dependency>
<dependency>
<groupId>com.timeloit.project</groupId>
<artifactId>loit-build-web-common</artifactId>
<version>${loit-build-web-common.version}</version>
</dependency>
<dependency>
<groupId>com.timeloit.project</groupId>
<artifactId>loit-seata-mybatis-mysql-suport</artifactId>
<version>${loit-seata-mybatis-mysql-suport.version}</version>
</dependency>
<dependency>
<groupId>com.timeloit.project</groupId>
<artifactId>loit-seata-example-common</artifactId>
<version>${project.version}</version>
</dependency>
<!--Own dependencies - Starters -->
<!--tools-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>${modelmapper.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tuple</artifactId>
<version>${spring-tuple.version}</version>
</dependency>
<!-- 集成swagger ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
</dependency>
<!-- 解决Integer类型example为空时,访问swagger报错问题 -->
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
<version>${swagger-annotations.version}</version>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
<version>${swagger-models.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<pluginManagement>
<plugins>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<encoding>${project.build.sourceEncoding}</encoding>
<compilerVersion>${java.version}</compilerVersion>
</configuration>
</plugin>
</plugins>
</build>
<distributionManagement>
<repository>
<id>nexus-releases</id>
<name>Nexus Release Repository</name>
<url>http://39.100.254.140:12010/repository/maven-releases/</url>
</repository>
<snapshotRepository>
<id>nexus-snapshots</id>
<name>Nexus Snapshot Repository</name>
<url>http://39.100.254.140:12010/repository/maven-snapshots/</url>
</snapshotRepository>
</distributionManagement>
<repositories>
<repository>
<id>nexus-loit-dev</id>
<name>Nexus Repository</name>
<url>http://39.100.254.140:12010/repository/maven-public/</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
<releases>
<enabled>true</enabled>
</releases>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>nexus-loit-dev</id>
<name>Nexus Plugin Repository</name>
<url>http://39.100.254.140:12010/repository/maven-public/</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
<releases>
<enabled>true</enabled>
</releases>
</pluginRepository>
</pluginRepositories>
</project>
\ 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>loit-seata-order-example</artifactId>
<groupId>com.timeloit.project</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>loit-seata-order-example-main</artifactId>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>com.timeloit.project</groupId>
<artifactId>loit-build-spi-common</artifactId>
</dependency>
<dependency>
<groupId>com.timeloit.project</groupId>
<artifactId>loit-build-web-common</artifactId>
</dependency>
<!--common-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tuple</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--Own dependencies -->
<dependency>
<groupId>com.timeloit.project</groupId>
<artifactId>loit-seata-example-common</artifactId>
</dependency>
<!-- spring cloud -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<!-- nacos -->
<dependency>
<groupId>com.timeloit.cloud</groupId>
<artifactId>spring-cloud-timeloit-nacos-discovery</artifactId>
</dependency>
<dependency>
<groupId>com.timeloit.cloud</groupId>
<artifactId>spring-cloud-timeloit-nacos-config</artifactId>
</dependency>
<!-- 熔断 限流-->
<dependency>
<groupId>com.timeloit.cloud</groupId>
<artifactId>spring-cloud-starter-timeloit-sentinel</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-datasource-nacos</artifactId>
</dependency>
<!-- seata-->
<dependency>
<groupId>com.timeloit.cloud</groupId>
<artifactId>spring-cloud-timeloit-seata</artifactId>
</dependency>
<!-- mysql -->
<dependency>
<groupId>com.timeloit.project</groupId>
<artifactId>loit-seata-mybatis-mysql-suport</artifactId>
</dependency>
<!--swagger-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
<!-- 解决Integer类型example为空时,访问swagger报错问题 -->
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot.version}</version>
<configuration>
<mainClass>com.loit.seata.order.example.LoitSeataOrderExampleApplication</mainClass>
</configuration>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file
package com.loit.seata.order.example;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.Banner;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
@EnableDiscoveryClient
@EnableFeignClients
@SpringBootApplication(scanBasePackages = {"com.loit.seata"}, exclude = DataSourceAutoConfiguration.class)
@Slf4j
public class LoitSeataOrderExampleApplication {
public static void main(String[] args) {
log.info("start execute LoitSeataOrderExampleApplication....\n");
System.out.println("start execute LoitSeataOrderExampleApplication....\n");
new SpringApplicationBuilder(LoitSeataOrderExampleApplication.class).bannerMode(Banner.Mode.OFF).run(args);
System.out.println("end execute LoitSeataOrderExampleApplication....\n");
log.info("end execute LoitSeataOrderExampleApplication....\n");
}
}
package com.loit.seata.order.example.model;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.experimental.Accessors;
import java.math.BigDecimal;
@Data
@Accessors(chain = true)
@TableName("order_tbl")
public class Order {
@TableId(type=IdType.AUTO)
private Integer id;
private String userId;
private String commodityCode;
private Integer count;
private BigDecimal money;
}
package com.loit.seata.order.example.repository;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.loit.seata.order.example.model.Order;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
@Mapper
@Repository
public interface OrderDAO extends BaseMapper<Order> {
}
package com.loit.seata.order.example.service.biz;
import com.loit.seata.order.example.model.Order;
import com.loit.seata.order.example.repository.OrderDAO;
import com.loit.seata.order.example.service.comsumer.AccountFeignClient;
import com.loit.seata.order.example.service.comsumer.StorageFeignClient;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.math.BigDecimal;
@Service
public class OrderService {
@Resource
private AccountFeignClient accountFeignClient;
@Resource
private StorageFeignClient storageFeignClient;
@Resource
private OrderDAO orderDAO;
/**
* 下单:创建订单、减库存,涉及到两个服务
*
* @param userId
* @param commodityCode
* @param count
*/
@GlobalTransactional
@Transactional(rollbackFor = Exception.class)
public void placeOrder(String userId, String commodityCode, Integer count) {
BigDecimal orderMoney = new BigDecimal(count).multiply(new BigDecimal(5));
Order order = new Order()
.setUserId(userId)
.setCommodityCode(commodityCode)
.setCount(count)
.setMoney(orderMoney);
orderDAO.insert(order);
storageFeignClient.deduct(commodityCode, count);
}
@Transactional(rollbackFor = Exception.class)
public void create(String userId, String commodityCode, Integer count) {
BigDecimal orderMoney = new BigDecimal(count).multiply(new BigDecimal(5));
Order order = new Order()
.setUserId(userId)
.setCommodityCode(commodityCode)
.setCount(count)
.setMoney(orderMoney);
orderDAO.insert(order);
accountFeignClient.reduce(userId, orderMoney);
}
}
package com.loit.seata.order.example.service.comsumer;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.math.BigDecimal;
@FeignClient(name = "account-service")
public interface AccountFeignClient {
@GetMapping("/reduce")
Boolean reduce(@RequestParam("userId") String userId, @RequestParam("money") BigDecimal money);
}
package com.loit.seata.order.example.service.comsumer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
@Component
@Slf4j
public class EchoServiceFallback implements StorageFeignClient{
@Override
public Boolean deduct(String commodityCode, Integer count) {
throw new RuntimeException("服务关闭了");
}
}
package com.loit.seata.order.example.service.comsumer;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
@FeignClient(name = "storage-service")
//@FeignClient(name = "storage-service", fallback = EchoServiceFallback.class)
public interface StorageFeignClient {
@GetMapping("storage/deduct")
Boolean deduct(@RequestParam("commodityCode") String commodityCode, @RequestParam("count") Integer count);
}
package com.loit.seata.order.example.web.config;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("统一用户API接口管理")
.description("统一用户API接口管理")
.version("1.0")
.build();
}
}
package com.loit.seata.order.example.web.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import static springfox.documentation.builders.PathSelectors.regex;
@Configuration
@EnableSwagger2
public class SwaggerUumsConfig extends SwaggerConfig {
@Bean
public Docket createRestfulApi() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("order")
.apiInfo(apiInfo())
.select()
.paths(regex("/order/.*"))
.build();
}
}
package com.loit.seata.order.example.web.config;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.ToStringSerializer;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.modelmapper.ModelMapper;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.core.convert.ConversionService;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.ResourceHttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter;
import org.springframework.http.converter.xml.SourceHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.math.BigInteger;
import java.util.List;
/**
* Spring Boot 配置web启动信息,
* 用于替换 web.xml
* <p>
*/
@SpringBootConfiguration
public class WebMvcConfigBean implements WebMvcConfigurer, ApplicationContextAware {
@Autowired
@Qualifier("mvcConversionService")
private ObjectFactory<ConversionService> conversionService;
@Autowired
private ObjectFactory<ObjectMapper> objectMapper;
private ApplicationContext applicationContext;
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
StringHttpMessageConverter stringConverter = new StringHttpMessageConverter();
stringConverter.setWriteAcceptCharset(false);
converters.add(new ByteArrayHttpMessageConverter());
converters.add(stringConverter);
converters.add(new ResourceHttpMessageConverter());
converters.add(new SourceHttpMessageConverter<>());
converters.add(new AllEncompassingFormHttpMessageConverter());
/**
* 集成FastJson
*/
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(
SerializerFeature.PrettyFormat
);
SerializeConfig serializeConfig = SerializeConfig.getGlobalInstance();
serializeConfig.put(BigInteger.class, ToStringSerializer.instance);
serializeConfig.put(Long.class, ToStringSerializer.instance);
serializeConfig.put(Long.TYPE, ToStringSerializer.instance);
fastJsonConfig.setSerializeConfig(serializeConfig);
fastJsonConfig.setDateFormat("yyyy-MM-dd");
fastConverter.setFastJsonConfig(fastJsonConfig);
converters.add(fastConverter);
}
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter(
objectMapper.getObject());
converters.add(jackson2HttpMessageConverter);
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
//registry.addInterceptor(httpLogInteceptor()).addPathPatterns("/**");
//registry.addInterceptor(userInterceptor()).addPathPatterns("/**");
}
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*")
.allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
.allowCredentials(false).maxAge(3600);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
/**
* Bean Utils
*/
@Bean
public ModelMapper modelMapper() {
ModelMapper modelMapper = new ModelMapper();
modelMapper.getConfiguration().setAmbiguityIgnored(true);
return modelMapper;
}
}
\ No newline at end of file
package com.loit.seata.order.example.web.controller;
import com.loit.build.spi.common.dto.BaseResponse;
import com.loit.build.spi.common.exception.BusinessException;
import com.loit.seata.order.example.service.biz.OrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
@RestController
@RequestMapping("order")
@RefreshScope
@Api(tags = "订单管理", value = "OrderController")
@Slf4j
public class OrderController {
@Resource
private OrderService orderService;
@Value("${user.name}")
private String userName;
@Value("${user.age}")
private int age;
@RequestMapping("/user")
public String simple() {
return "userName: " + userName + "age:" + age;
}
/**
* 下单:插入订单表、扣减库存, 成功下单
*
* @return
*/
@ApiOperation(value = "成功下单", notes = "下单:插入订单表、扣减库存, 成功下单")
@GetMapping("/placeOrder/commit")
public BaseResponse placeOrderCommit() {
try {
orderService.placeOrder("1", "product-1", 1);
} catch (Exception e) {
log.error("下单失败", e);
throw new BusinessException("下单失败");
}
return BaseResponse.ofSuccess(true);
}
/**
* 下单:插入订单表、扣减库存,模拟回滚
*
* @return
*/
@ApiOperation(value = "模拟回滚", notes = "下单:插入订单表、扣减库存,模拟回滚")
@GetMapping("/placeOrder/rollback")
public BaseResponse placeOrderRollback() {
// product-2 扣库存时模拟了一个业务异常,
orderService.placeOrder("1", "product-2", 1);
return BaseResponse.ofSuccess(true);
}
@PostMapping("/placeOrder")
@ApiOperation(value = "下单(传参数)", notes = "插入订单表、扣减库存,模拟回滚, 传参数")
@ApiImplicitParams({
@ApiImplicitParam(paramType = "query", name = "userId", value = "用户ID", dataType = "String"),
@ApiImplicitParam(paramType = "query", name = "commodityCode", value = "商品code", dataType = "String"),
@ApiImplicitParam(paramType = "query", name = "count", value = "购买数量", dataType = "Integer")
})
public BaseResponse placeOrder(String userId, String commodityCode, Integer count) {
orderService.placeOrder(userId, commodityCode, count);
return BaseResponse.ofSuccess(true);
}
}
package com.loit.seata.order.example.web.exception;
public class BeanUtilsException extends RuntimeException{
public BeanUtilsException(Throwable e){
super(e);
}
}
package com.loit.seata.order.example.web.exception.base;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.loit.build.spi.common.dto.BaseResponse;
import com.loit.build.spi.common.dto.ResponseStatusEnum;
import com.loit.build.spi.common.exception.BusinessException;
import com.loit.build.web.common.exception.base.ArgumentInvalidResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpStatus;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* 全局异常处理
*/
@ControllerAdvice
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
@Autowired
ObjectMapper objectMapper;
private Environment env;
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
@ResponseStatus(value = HttpStatus.METHOD_NOT_ALLOWED)
public Object handleRequestMethodException(HttpServletRequest request,
HttpRequestMethodNotSupportedException exception) {
log.error(exception.getMessage(), exception);
BaseResponse baseResponse = new BaseResponse();
baseResponse.setCode(HttpStatus.METHOD_NOT_ALLOWED.getReasonPhrase());
baseResponse.setMessage(exception.getMessage());
baseResponse.setData("HttpRequestMethodNotSupported Exception");
return baseResponse;
}
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
public Object methodArgumentNotValidHandler(MethodArgumentNotValidException exception) throws JsonProcessingException {
List<ArgumentInvalidResult> argumentInvalidResults = new ArrayList<ArgumentInvalidResult>();
for (FieldError error : exception.getBindingResult().getFieldErrors()) {
ArgumentInvalidResult argumentInvalidResult = new ArgumentInvalidResult();
argumentInvalidResult.setField(error.getField());
argumentInvalidResult.setRejectedValue(error.getRejectedValue());
argumentInvalidResult.setDefaultMessage(error.getDefaultMessage());
argumentInvalidResults.add(argumentInvalidResult);
}
log.error(" 方法参数无效错误: message:{}, parameter: {}, result:{}",
exception.getMessage(),
objectMapper.writeValueAsString(exception.getParameter()),
objectMapper.writeValueAsString(exception.getBindingResult())
);
BaseResponse baseResponse = new BaseResponse();
baseResponse.setCode(ResponseStatusEnum.PARAMETER_ERROR.getCode());
baseResponse.setMessage(env.getProperty(ResponseStatusEnum.PARAMETER_ERROR.getCode(), ResponseStatusEnum.PARAMETER_ERROR.getMessage()));
baseResponse.setData(argumentInvalidResults);
return baseResponse;
}
@ExceptionHandler(BusinessException.class)
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
public Object businessExceptionHandler(BusinessException exception) {
log.error(exception.getMessage(), exception);
BaseResponse baseResponse = new BaseResponse();
baseResponse.setCode(exception.getCode());
baseResponse.setMessage(exception.getMessage());
baseResponse.setData(exception.toString());
return baseResponse;
}
@ExceptionHandler(SQLException.class)
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
public Object handleSQLException(HttpServletRequest request,
SQLException exception) {
log.error(exception.getMessage(), exception);
BaseResponse baseResponse = new BaseResponse();
baseResponse.setCode(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase());
baseResponse.setMessage(exception.getMessage());
baseResponse.setData("SQLQuery Error");
return baseResponse;
}
@ExceptionHandler(ConstraintViolationException.class)
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
public Object handleConstraintViolationException(HttpServletRequest request,
ConstraintViolationException exception) {
BaseResponse baseResponse = new BaseResponse();
baseResponse.setCode(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase());
Set<ConstraintViolation<?>> violations = exception.getConstraintViolations();
StringBuffer errorMsg = new StringBuffer();
for (ConstraintViolation<?> item : violations) {
errorMsg.append(item.getMessage());
}
baseResponse.setMessage(errorMsg.toString());
log.error(errorMsg.toString());
baseResponse.setData("参数校验异常 Error");
return baseResponse;
}
@ExceptionHandler(RuntimeException.class)
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
public Object handleAllException(HttpServletRequest request,
RuntimeException exception) {
log.error(exception.getMessage(), exception);
BaseResponse baseResponse = new BaseResponse();
baseResponse.setCode(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase());
baseResponse.setMessage(exception.getMessage());
baseResponse.setData("Runtime Error");
return baseResponse;
}
@ExceptionHandler(Exception.class)
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
public Object handleAllException(HttpServletRequest request,
Exception exception) {
log.error(exception.getMessage(), exception);
BaseResponse baseResponse = new BaseResponse();
baseResponse.setCode(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase());
baseResponse.setMessage(exception.getMessage());
baseResponse.setData("Error");
return baseResponse;
}
}
package com.loit.seata.order.example.web.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.Map;
/**
* 于page配合 填充数据
*
* @Title: BulkMapper
*/
public abstract class BulkMapper<T> {
//private static final String PRE_NAME = "Name";
private static final Logger logger = LoggerFactory.getLogger(BulkMapper.class);
public abstract void mapBulk(T entity, Map<String, Object> paramMap, Map<String, Object> requestMap);
/*
* 加载 延时加载的collection 数据
*/
public void loadCollectionInfo(Object entity, Map<String, Object> paramMap) {
try {
Field[] fields = entity.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
if (Collection.class.isAssignableFrom(field.getType())) {
paramMap.put(field.getName(), field.get(entity));
}
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
/*public void loadIndexInfo(Object entity, Map<String, Object> paramMap, boolean isNeedSetInfo) {
try {
String tableName = entity.getClass().getSimpleName();
Field[] fields = entity.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
if (Collection.class.isAssignableFrom(field.getType())) {
buildSetInfo(entity, paramMap, isNeedSetInfo, field);
} else {
buildCodeName(entity, paramMap, tableName, field);
}
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
private void buildCodeName(Object entity, Map<String, Object> paramMap, String tableName, Field field) throws IllegalAccessException {
DataDictService dataDictService = (DataDictService) SpringUtils.getBean("dataDictServiceImpl");
Object value = field.get(entity);
if (value == null) {
return;
}
ZtreeDictNote dataDict = dataDictService.findByFieldInfo(tableName, field.getName(), String.valueOf(value));
if (dataDict == null) {
return;
}
String codeName = dataDict.getCodeName();
if (!StringUtil.isEmpty(codeName)) {
paramMap.put(field.getName() + PRE_NAME, codeName);
}
}
@SuppressWarnings("rawtypes")
private void buildSetInfo(Object entity, Map<String, Object> paramMap, boolean isNeedSetInfo, Field field) throws IllegalAccessException {
if (!isNeedSetInfo) {
return;
}
Collection collection = (Collection) field.get(entity);
if (collection == null || collection.isEmpty()) {
return;
}
for (Object info : collection) {
if (info == null) {
continue;
}
Map<String, Object> setInfoMap = FastjsonUtils.toMap(info);
paramMap.put(field.getName(), setInfoMap);
}
}*/
}
\ No newline at end of file
package com.loit.seata.order.example.web.utils;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
import java.io.IOException;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Map;
import java.util.TimeZone;
/**
* Utils - JSON
*
*/
public final class FastjsonUtils {
private static final Logger logger = LoggerFactory.getLogger(FastjsonUtils.class);
/** ObjectMapper */
private static ObjectMapper mapper = new ObjectMapper();
/**
* 不可实例化
*/
private FastjsonUtils() {
}
/**
* 将对象转换为JSON字符串
*
* @param value
* 对象
* @return JSOn字符串
*/
public static String toJson(Object value) {
try {
mapper.setTimeZone(TimeZone.getTimeZone("GMT+08"));
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
return mapper.writeValueAsString(value);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return null;
}
/**
* 将对象转换为Map字符串
*
* @param value
* 对象
* @return JSOn字符串
*/
@SuppressWarnings("unchecked")
public static Map<String, Object> toMap(Object value) {
try {
String json = mapper.writeValueAsString(value);
return mapper.readValue(json, Map.class);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return null;
}
@SuppressWarnings("unchecked")
public static Map<String, Object> jsonToMap(String json) {
try {
return mapper.readValue(json, Map.class);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return null;
}
/**
* 将JSON字符串转换为对象
*
* @param json
* JSON字符串
* @param valueType
* 对象类型
* @return 对象
*/
public static <T> T toObject(String json, Class<T> valueType) {
Assert.hasText(json);
Assert.notNull(valueType);
try {
return mapper.readValue(json, valueType);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return null;
}
/**
* 将JSON字符串转换为对象
*
* @param json
* JSON字符串
* @param typeReference
* 对象类型
* @return 对象
*/
public static <T> T toObject(String json, TypeReference<?> typeReference) {
Assert.hasText(json);
Assert.notNull(typeReference);
try {
return mapper.readValue(json, typeReference);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return null;
}
/**
* 将JSON字符串转换为对象
*
* @param json
* JSON字符串
* @param javaType
* 对象类型
* @return 对象
*/
public static <T> T toObject(String json, JavaType javaType) {
Assert.hasText(json);
Assert.notNull(javaType);
try {
return mapper.readValue(json, javaType);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return null;
}
/**
* 将对象转换为JSON流
*
* @param writer
* writer
* @param value
* 对象
*/
public static void writeValue(Writer writer, Object value) {
try {
mapper.writeValue(writer, value);
} catch (JsonGenerationException e) {
logger.error(e.getMessage(), e);
} catch (JsonMappingException e) {
logger.error(e.getMessage(), e);
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
/**
* 将Json格式字符串转换成Java对象
*
* @param jsonString
* Json格式字符串
* @param beanClass
* Java对象Class
* @param classMap
* 包含的对象集合中的Java对象Class
* @return Object
*/
/*public static Object jsonToBean(String jsonString, Class beanClass, Map classMap) {
JSONObject jsonObject = null;
try {
jsonObject = JSONObject.fromObject(jsonString);
} catch (Exception e) {
e.printStackTrace();
}
return JSONObject.toBean(jsonObject, beanClass, classMap);
}
public static Map jsonToMap(String jsonString) {
JSONObject jsonObject = JSONObject.fromObject(jsonString);
Map map = new HashMap();
for (Iterator iter = jsonObject.keys(); iter.hasNext();) {
String key = (String) iter.next();
map.put(key, jsonObject.get(key));
}
return map;
}*/
}
\ No newline at end of file
package com.loit.seata.order.example.web.utils;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Collection;
import java.util.Enumeration;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Http 工具类
* 用于对HttpServletRequest或HttpServletResponse进行操作
* Created by zhangzhiyi on 2018/3/8.
*/
@Slf4j
public class HttpUtil {
private static final Pattern PATTERN_HEADER = Pattern.compile("(^|-)([a-zA-Z])([a-zA-Z]*)");
/**
* 转换 Http 请求头 或 响应头
* @param headerName
* @return
*/
public static String convertHeaderName(String headerName) {
Matcher matcher = PATTERN_HEADER.matcher(headerName);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(sb,
matcher.group(1) + matcher.group(2).toUpperCase() + matcher.group(3).toLowerCase());
}
matcher.appendTail(sb);
return sb.toString();
}
/**
* 打印请求参数
*
* @param request
*/
public static void printRequestParameter(HttpServletRequest request) {
request.getParameterMap().forEach((k, v) ->
log.info(" {}=\"{}\"",
k,
request.getParameter(k)
)
);
}
/**
* 打印请求头
*
* @param request
*/
public static void printRequestHeader(HttpServletRequest request) {
Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String key = headerNames.nextElement();
log.info(" {}: \"{}\"",
convertHeaderName(key),
request.getHeader(key)
);
}
}
/**
* 打印响应头
*
* @param response
*/
public static void printResponseHeader(HttpServletResponse response) {
Collection<String> headerNames = response.getHeaderNames();
headerNames.forEach(key ->
log.info(" {}: \"{}\"",
convertHeaderName(key),
response.getHeader(key)
)
);
}
/**
* 打印cookie
*
* @param request
*/
public static void printRequestCookie(HttpServletRequest request) {
Cookie[] cookies = request.getCookies();
if (null == cookies) {
return;
}
for (Cookie cookie : cookies) {
try {
log.info(" {Domain:{}, Path:{}, Name:{}, Value:{}, MaxAge:{}, Comment:{}, Version:{}, Secure:{}}",
cookie.getDomain(),
cookie.getPath(),
cookie.getName(),
null != cookie.getValue()
? URLDecoder.decode(cookie.getValue(), "UTF-8")
: null,
cookie.getMaxAge(),
cookie.getComment(),
cookie.getVersion(),
cookie.getSecure()
);
} catch (UnsupportedEncodingException e) {
log.error("不支持的编码", e);
}
}
}
}
package com.loit.seata.order.example.web.utils;
import org.springframework.context.MessageSource;
public class MessageUtils {
private static MessageSource messageSource;
/**
* 根据消息键和参数 获取消息
* 委托给spring messageSource
*
* @param code 消息键
* @param args 参数
* @return msg
*/
public static String message(String code, Object... args) {
if (messageSource == null) {
messageSource = SpringUtils.getBean(MessageSource.class);
}
return messageSource.getMessage(code, args, null);
}
}
package com.loit.seata.order.example.web.utils;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class MulBulkMapperConverter<T> {
/**
* @Title: 将resultList 里面的 entity 转换为对应的map<String, String>
*/
/*public void convertResultToMap(Page<T> page, BulkMapper<T> bulkMapper) {
// 1. 清除
page.getResultMapList().clear();
ParamRequest pageRequest = page.getPageRequest();
List<T> resultList = page.getResult();
if (resultList != null && !resultList.isEmpty()) {
for (T entity : resultList) {
Map<String, Object> objectMap = FastjsonUtils.toMap(entity);
// 3.附加属性
if (bulkMapper != null && entity != null) {
if (pageRequest == null) {
bulkMapper.mapBulk(entity, objectMap, null);
} else {
bulkMapper.mapBulk(entity, objectMap, pageRequest.getRequestMap());
}
}
page.getResultMapList().add(objectMap);
}
}
}*/
/**
*
* @Title: convertMulResultToMap
* @Description: (将resultList 里面的 entity 转换为对应的Map<String, Object>)
* @param bulkMapper
* @param userId
* 如果userId = null,则查询当前登录用户ID
* @return void 返回类型
* @throws
* @author Administrator
*/
/*@SuppressWarnings({ "rawtypes", "unchecked" })
public void convertMulResultToMap(Page<T> page, MulBulkMapper bulkMapper, Integer userId) {
// 1. 清除
page.getResultMapList().clear();
Iterator iterator = page.getResult().iterator();
ParamRequest pageRequest = page.getPageRequest();
// hql join 查询 返回 多个对象
while (iterator.hasNext()) {
Object object = iterator.next();
Object[] entitys = null;
T mainEntity = null;
if (object instanceof Object[]) {
entitys = (Object[]) object;
mainEntity = (T) entitys[0];
} else {
mainEntity = (T) object;
entitys = new Object[] { object };
}
Map<String, Object> objectMap = FastjsonUtils.toMap(mainEntity);
// 3.附加属性
if (bulkMapper != null && mainEntity != null) {
if (pageRequest == null) {
bulkMapper.mapBulk(entitys, objectMap, null, userId);
} else {
bulkMapper.mapBulk(entitys, objectMap, pageRequest.getRequestMap(), userId);
}
}
page.getResultMapList().add(objectMap);
}
}*/
/**
*
* @Title: convertMulResultToMap
* @Description: (将resultList 里面的 entity 转换为对应的List<Map<String, Object>>)
* @param bulkMapper
* @param resultList
* @param userId
* 如果userId = null,则查询当前登录用户ID
* @return void 返回类型
* @throws
* @author Administrator
*/
/*@SuppressWarnings({ "rawtypes", "unchecked" })
public List<Map<String, Object>> convertMulResultToMap(MulBulkMapper bulkMapper, List<T> resultList, Integer userId) {
// 1. 清除
List<Map<String, Object>> resultMapList = new ArrayList<Map<String, Object>>();
Iterator iterator = resultList.iterator();
// hql join 查询 返回 多个对象
while (iterator.hasNext()) {
Object object = iterator.next();
Object[] entitys = null;
T mainEntity = null;
if (object instanceof Object[]) {
entitys = (Object[]) object;
mainEntity = ((T) entitys[0]);
} else {
mainEntity = (T) object;
entitys = new Object[] { object };
}
Map<String, Object> objectMap = FastjsonUtils.toMap(mainEntity);
// 3.附加属性
if (bulkMapper != null && mainEntity != null) {
bulkMapper.mapBulk(entitys, objectMap, null, null);
}
resultMapList.add(objectMap);
}
return resultMapList;
}*/
/**
* @Title: 将list<T> 里面的 entity 转换为对应的map<String, String> 返回
*/
public List<Map<String, Object>> convertListResultToMap(BulkMapper<T> bulkMapper, List<T> resultList) {
List<Map<String, Object>> resultMapList = new ArrayList<Map<String, Object>>();
if (resultList != null && !resultList.isEmpty()) {
for (T result : resultList) {
// 2.先将基本属性 转换为map
Map<String, Object> objectMap = FastjsonUtils.toMap(result);
// 3.附加属性
if (bulkMapper != null || result == null) {
bulkMapper.mapBulk(result, objectMap, null);
}
resultMapList.add(objectMap);
}
}
return resultMapList;
}
}
\ No newline at end of file
package com.loit.seata.order.example.web.utils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
public final class SpringUtils implements BeanFactoryPostProcessor {
private static ConfigurableListableBeanFactory beanFactory; // Spring应用上下文环境
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
SpringUtils.beanFactory = beanFactory;
}
/**
* 获取对象
*
* @param name
* @return Object 一个以所给名字注册的bean的实例
* @throws BeansException
*
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) throws BeansException {
return (T) beanFactory.getBean(name);
}
/**
* 获取类型为requiredType的对象
*
* @param clz
* @return
* @throws BeansException
*
*/
public static <T> T getBean(Class<T> clz) throws BeansException {
T result = (T) beanFactory.getBean(clz);
return result;
}
/**
* 如果BeanFactory包含一个与所给名称匹配的bean定义,则返回true
*
* @param name
* @return boolean
*/
public static boolean containsBean(String name) {
return beanFactory.containsBean(name);
}
/**
* 判断以给定名字注册的bean定义是一个singleton还是一个prototype。 如果与给定名字相应的bean定义没有被找到,将会抛出一个异常(NoSuchBeanDefinitionException)
*
* @param name
* @return boolean
* @throws NoSuchBeanDefinitionException
*
*/
public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
return beanFactory.isSingleton(name);
}
/**
* @param name
* @return Class 注册对象的类型
* @throws NoSuchBeanDefinitionException
*
*/
public static Class<?> getType(String name) throws NoSuchBeanDefinitionException {
return beanFactory.getType(name);
}
/**
* 如果给定的bean名字在bean定义中有别名,则返回这些别名
*
* @param name
* @return
* @throws NoSuchBeanDefinitionException
*
*/
public static String[] getAliases(String name) throws NoSuchBeanDefinitionException {
return beanFactory.getAliases(name);
}
}
feign.sentinel.enabled=true
logging.level.io.seata=debug
management.endpoints.web.exposure.include=*
server.port=9091
spring.application.name=order-service
# seata 服务分组,要与服务端nacos-config.txt中service.vgroup_mapping的后缀对应
spring.cloud.alibaba.seata.tx-service-group=order-service-seata-service-group
# Nacos 注册中心地址
spring.cloud.nacos.discovery.server-addr=192.168.66.40:8848
spring.cloud.nacos.discovery.namespace=e15d31e9-88f3-4f8d-be57-916992ea757c
spring.cloud.sentinel.datasource.ds.nacos.dataId=${spring.application.name}-sentinel
spring.cloud.sentinel.datasource.ds.nacos.groupId=DEFAULT_GROUP
spring.cloud.sentinel.datasource.ds.nacos.rule-type=flow
spring.cloud.sentinel.datasource.ds.nacos.server-addr=192.168.66.40:8848
spring.cloud.sentinel.datasource.ds.nacos.namespace=e15d31e9-88f3-4f8d-be57-916992ea757c
spring.cloud.sentinel.transport.dashboard=localhost:8090
spring.cloud.sentinel.transport.port=8720
# 数据源配置
spring.datasource.druid.driverClassName=com.mysql.jdbc.Driver
spring.datasource.druid.password=abcd1234A!
spring.datasource.druid.url=jdbc:mysql://39.98.202.173:3306/seata_order?allowMultiQueries=true&amp;characterEncoding=utf8&amp;useSSL=false
spring.datasource.druid.username=root
user.age=24
user.name=example-yaml
feign:
sentinel:
enabled: true
logging:
level:
io:
seata: debug
management:
endpoints:
web:
exposure:
include: '*'
server:
port: 9091
spring:
application:
name: order-service
cloud:
alibaba:
seata:
tx-service-group: loit_server_tx_group
nacos:
discovery:
server-addr: 192.168.66.40:8848
sentinel:
datasource:
ds:
nacos:
dataId: ${spring.application.name}-sentinel
groupId: DEFAULT_GROUP
rule-type: flow
server-addr: 192.168.66.40:8848
namespace: e15d31e9-88f3-4f8d-be57-916992ea757c
transport:
dashboard: localhost:8090
port: 8720
datasource:
druid:
driverClassName: com.mysql.jdbc.Driver
password: abcd1234A!
url: jdbc:mysql://39.98.202.173:3306/seata_order?allowMultiQueries=true&amp;characterEncoding=utf8&amp;useSSL=false
username: root
user:
age: 24
name: example-yaml
feign.sentinel.enabled=true
logging.level.io.seata=debug
management.endpoints.web.exposure.include=*
server.port=9091
spring.application.name=order-service
# seata 服务分组,要与服务端nacos-config.txt中service.vgroup_mapping的后缀对应
spring.cloud.alibaba.seata.tx-service-group=order-service-seata-service-group
# Nacos 注册中心地址
spring.cloud.nacos.discovery.server-addr=192.168.66.40:8848
spring.cloud.sentinel.datasource.ds.nacos.dataId=${spring.application.name}-sentinel
spring.cloud.sentinel.datasource.ds.nacos.groupId=DEFAULT_GROUP
spring.cloud.sentinel.datasource.ds.nacos.rule-type=flow
spring.cloud.sentinel.datasource.ds.nacos.server-addr=192.168.66.40:8848
spring.cloud.sentinel.datasource.ds.nacos.namespace=e15d31e9-88f3-4f8d-be57-916992ea757c
spring.cloud.sentinel.transport.dashboard=localhost:8090
spring.cloud.sentinel.transport.port=8720
# 数据源配置
spring.datasource.druid.driverClassName=com.mysql.jdbc.Driver
spring.datasource.druid.password=abcd1234A!
spring.datasource.druid.url=jdbc:mysql://39.98.202.173:3306/seata_order?allowMultiQueries=true&amp;characterEncoding=utf8&amp;useSSL=false
spring.datasource.druid.username=root
user.age=24
user.name=example-yaml
spring.profiles.active=dev
spring.application.name=order-service
# Nacos ĵַ
spring.cloud.nacos.config.server-addr=192.168.66.40:8848
spring.cloud.nacos.config.group=DEFAULT_GROUP
# spring.cloud.nacos.config.file-extension=properties
# spring.cloud.nacos.config.file-extension=yaml
spring.cloud.nacos.config.file-extension=yaml
spring.cloud.nacos.config.namespace=e15d31e9-88f3-4f8d-be57-916992ea757c
transport {
# tcp udt unix-domain-socket
type = "TCP"
#NIO NATIVE
server = "NIO"
#enable heartbeat
heartbeat = true
#thread factory for netty
thread-factory {
boss-thread-prefix = "NettyBoss"
worker-thread-prefix = "NettyServerNIOWorker"
server-executor-thread-prefix = "NettyServerBizHandler"
share-boss-worker = false
client-selector-thread-prefix = "NettyClientSelector"
client-selector-thread-size = 1
client-worker-thread-prefix = "NettyClientWorkerThread"
# netty boss thread size,will not be used for UDT
boss-thread-size = 1
#auto default pin or 8
worker-thread-size = 8
}
shutdown {
# when destroy server, wait seconds
wait = 3
}
serialization = "seata"
compressor = "none"
}
service {
#transaction service group mapping
vgroup_mapping.order-service-seata-service-group = "default"
#only support when registry.type=file, please don't set multiple addresses
default.grouplist = "127.0.0.1:8091"
#degrade, current not support
enableDegrade = false
#disable seata
disableGlobalTransaction = false
}
client {
rm {
async.commit.buffer.limit = 10000
lock {
retry.internal = 10
retry.times = 30
retry.policy.branch-rollback-on-conflict = true
}
report.retry.count = 5
table.meta.check.enable = false
report.success.enable = true
}
tm {
commit.retry.count = 5
rollback.retry.count = 5
}
undo {
data.validation = true
log.serialization = "jackson"
log.table = "undo_log"
}
log {
exceptionRate = 100
}
support {
# auto proxy the DataSource bean
spring.datasource.autoproxy = false
}
}
## transaction log store
store {
## store mode: file、db
mode = "db"
## file store property
file {
## store location dir
dir = "sessionStore"
# branch session size , if exceeded first try compress lockkey, still exceeded throws exceptions
max-branch-session-size = 16384
# globe session size , if exceeded throws exceptions
max-global-session-size = 512
# file buffer size , if exceeded allocate new buffer
file-write-buffer-cache-size = 16384
# when recover batch read size
session.reload.read_size = 100
# async, sync
flush-disk-mode = async
}
## database store property
db {
## the implement of javax.sql.DataSource, such as DruidDataSource(druid)/BasicDataSource(dbcp) etc.
datasource = "dbcp"
## mysql/oracle/h2/oceanbase etc.
db-type = "mysql"
driver-class-name = "com.mysql.jdbc.Driver"
url = "jdbc:mysql://39.98.202.173:3306/seata_server"
user = "root"
password = "abcd1234A!"
min-conn = 1
max-conn = 10
global.table = "global_table"
branch.table = "branch_table"
lock-table = "lock_table"
query-limit = 100
}
}
server {
recovery {
#schedule committing retry period in milliseconds
committing-retry-period = 1000
#schedule asyn committing retry period in milliseconds
asyn-committing-retry-period = 1000
#schedule rollbacking retry period in milliseconds
rollbacking-retry-period = 1000
#schedule timeout retry period in milliseconds
timeout-retry-period = 1000
}
undo {
log.save.days = 7
#schedule delete expired undo_log in milliseconds
log.delete.period = 86400000
}
#unit ms,s,m,h,d represents milliseconds, seconds, minutes, hours, days, default permanent
max.commit.retry.timeout = "-1"
max.rollback.retry.timeout = "-1"
}
## metrics settings
metrics {
enabled = false
registry-type = "compact"
# multi exporters use comma divided
exporter-list = "prometheus"
exporter-prometheus-port = 9898
}
\ No newline at end of file
registry {
# file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
type = "nacos"
nacos {
serverAddr = "192.168.66.40:8848"
namespace = "public"
cluster = "default"
}
eureka {
serviceUrl = "http://localhost:8761/eureka"
application = "default"
weight = "1"
}
redis {
serverAddr = "localhost:6379"
db = "0"
}
zk {
cluster = "default"
serverAddr = "127.0.0.1:2181"
session.timeout = 6000
connect.timeout = 2000
}
consul {
cluster = "default"
serverAddr = "127.0.0.1:8500"
}
etcd3 {
cluster = "default"
serverAddr = "http://localhost:2379"
}
sofa {
serverAddr = "127.0.0.1:9603"
application = "default"
region = "DEFAULT_ZONE"
datacenter = "DefaultDataCenter"
cluster = "default"
group = "SEATA_GROUP"
addressWaitTime = "3000"
}
file {
name = "file.conf"
}
}
config {
# file、nacos 、apollo、zk、consul、etcd3
type = "file"
nacos {
serverAddr = "192.168.66.40:8848"
namespace = "public"
}
consul {
serverAddr = "127.0.0.1:8500"
}
apollo {
app.id = "seata-server"
apollo.meta = "http://192.168.1.204:8801"
}
zk {
serverAddr = "127.0.0.1:2181"
session.timeout = 6000
connect.timeout = 2000
}
etcd3 {
serverAddr = "http://localhost:2379"
}
file {
name = "file.conf"
}
}
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论