first commit

This commit is contained in:
yexuejc 2018-04-09 15:11:25 +08:00
commit a27ee11b35
28 changed files with 2358 additions and 0 deletions

24
.gitignore vendored Normal file
View File

@ -0,0 +1,24 @@
target/
!.mvn/wrapper/maven-wrapper.jar
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
nbproject/private/
build/
nbbuild/
dist/
nbdist/
.nb-gradle/

201
LICENSE Normal file
View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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
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.

51
README.md Normal file
View File

@ -0,0 +1,51 @@
# yexuejc-base
基于springboot maven 封装可继承基础工程
### 目录
<table>
<tr>
<td>\src\main\java</td>
<td>核心代码</td>
</tr>
<tr>
<td>\src\main\resources</td>
<td>核心配置</td>
</tr>
<tr>
<td>com.yexuejc.base.autoconfigure.*</td>
<td>模块封装</td>
</tr>
<tr>
<td>com.yexuejc.base.constant.*</td>
<td>系统常量</td>
</tr>
<tr>
<td>com.yexuejc.base.filter.*</td>
<td>过滤器</td>
</tr>
<tr>
<td>com.yexuejc.base.interceptor.*</td>
<td>拦截器</td>
</tr>
<tr>
<td>com.yexuejc.base.http.*</td>
<td>网络层</td>
</tr>
<tr>
<td>com.yexuejc.base.pojo.*</td>
<td>bean</td>
</tr>
<tr>
<td>com.yexuejc.base.util.*</td>
<td>工具包</td>
</tr>
<tr>
<td>\src\test\</td>
<td>测试部分</td>
</tr>
<tr>
<td>com.yexuejc.base.ApplicationRun</td>
<td>测试启动入口</td>
</tr>
</table>

23
UPDATE.md Normal file
View File

@ -0,0 +1,23 @@
uselaw-base 更新内容
-------------------
#### version 1.0.2
**time** 2018-4-1 17:00:15<br/>
**env** prod <br/>
**update** <br/>
>1.修复工具包ApiVO
#
#### version 0.0.2
**time** 2018-1-31 13:48:34<br/>
**env** ivt <br/>
**update** <br/>
>1.集成日志【security】
#
##### version 0.0.1
**time** 2018-1-31 12:16:10<br/>
**env** ivt <br/>
**update** <br/>
>1.第一次上传,集成通用环境
#

312
pom.xml Normal file
View File

@ -0,0 +1,312 @@
<?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">
<modelVersion>4.0.0</modelVersion>
<groupId>com.yexuejc.springboot</groupId>
<artifactId>yexuejc-springboot-parent</artifactId>
<version>1.0.3</version>
<packaging>pom</packaging>
<name>${project.artifactId}</name>
<description>yexuejc-springboot-parent project for Spring Boot</description>
<parent>
<!-- spring boot父级,包含了统一版本管理,统一插件管理等 -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<repos.yexuejc.ivt.url>http://47.100.13.178:7081/nexus/content/groups/public</repos.yexuejc.ivt.url>
<repos.yexuejc.prod.url>http://47.100.13.178:7081/nexus/content/groups/public</repos.yexuejc.prod.url>
<repos.yexuejc.dist.url>http://47.100.13.178:7081/nexus/content/repositories</repos.yexuejc.dist.url>
<repos.aliyun.url>http://maven.aliyun.com/nexus/content/groups/public</repos.aliyun.url>
<repos.jitpack.url>https://jitpack.io</repos.jitpack.url>
<maven.compiler.verbose>true</maven.compiler.verbose>
<java.version>1.8</java.version>
<validation-api.version>1.1.0.Final</validation-api.version>
<springfox-swagger2.version>2.2.2</springfox-swagger2.version>
<mybatis-spring-boot-starter.version>1.2.0</mybatis-spring-boot-starter.version>
<mybatis.version>3.4.2</mybatis.version>
<yexuejc.base.version>1.0.0</yexuejc.base.version>
<jjwt.version>0.7.0</jjwt.version>
<fastjson.version>1.1.46</fastjson.version>
<commons-codec.version>1.10</commons-codec.version>
<!-- 阿里云相关 -->
<aliyun-java-sdk-core.version>2.1.7</aliyun-java-sdk-core.version>
<aliyun-java-sdk-sts.version>2.1.6</aliyun-java-sdk-sts.version>
<aliyun-sdk-oss.version>2.8.1</aliyun-sdk-oss.version>
<aliyun-java-sdk-dysmsapi.version>1.0.0</aliyun-java-sdk-dysmsapi.version>
<aliyun-sdk-mns.version>1.1.8</aliyun-sdk-mns.version>
<!-- 支付宝相关 -->
<alipay-sdk-java.version>20171023143759</alipay-sdk-java.version>
<!-- 微信相关 -->
<WXPay-SDK-Java.version>0.0.4</WXPay-SDK-Java.version>
<postgresql.version>9.4.1212</postgresql.version>
<!--thymeleaf 相关-->
<thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
<thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version>
<thymeleaf-extras-springsecurity4.version>3.0.2.RELEASE</thymeleaf-extras-springsecurity4.version>
</properties>
<!-- 声明包版本 继承项目自引入 -->
<dependencyManagement>
<dependencies>
<!--基础包-->
<dependency>
<groupId>com.github.yexuejc</groupId>
<artifactId>yexuejc-base</artifactId>
<version>${yexuejc.base.version}</version>
</dependency>
<!--<dependency>-->
<!--<groupId>com.yexuejc.base</groupId>-->
<!--<artifactId>yexuejc-base</artifactId>-->
<!--<version>${yexuejc.base.version}</version>-->
<!--</dependency>-->
<!-- 编码包 说明http://blog.csdn.net/jianggujin/article/details/51149133 -->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>${commons-codec.version}</version>
</dependency>
<!-- JJWT -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>${jjwt.version}</version>
</dependency>
<!-- fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
<!-- MVC数据校验框架 -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>${validation-api.version}</version>
</dependency>
<!-- swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${springfox-swagger2.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${springfox-swagger2.version}</version>
</dependency>
<!-- 使用mybatis的starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>${mybatis-spring-boot-starter.version}</version>
<exclusions>
<!-- 禁用默认的tomcat连接池 -->
<exclusion>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jdbc</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!-- PostgreSQL JDBC DriverJDK1.8版) -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>${postgresql.version}</version>
</dependency>
<!-- 支付宝支付SDK -->
<dependency>
<groupId>com.alipay</groupId>
<artifactId>alipay-sdk-java</artifactId>
<version>${alipay-sdk-java.version}</version>
</dependency>
<!-- 微信支付SDK -->
<dependency>
<groupId>com.github.wxpay</groupId>
<artifactId>WXPay-SDK-Java</artifactId>
<version>${WXPay-SDK-Java.version}</version>
</dependency>
<!-- 阿里云基础SDK -->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>${aliyun-java-sdk-core.version}</version>
</dependency>
<!-- 阿里云STS相关SDK -->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-sts</artifactId>
<version>${aliyun-java-sdk-sts.version}</version>
</dependency>
<!-- 阿里云OSS相关SDK -->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>${aliyun-sdk-oss.version}</version>
</dependency>
<!-- 阿里云短信服务SMS相关SDK -->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-dysmsapi</artifactId>
<version>${aliyun-java-sdk-dysmsapi.version}</version>
</dependency>
<!-- 阿里云消息服务MNS相关SDK -->
<dependency>
<groupId>com.aliyun.mns</groupId>
<artifactId>aliyun-sdk-mns</artifactId>
<version>${aliyun-sdk-mns.version}</version>
<classifier>jar-with-dependencies</classifier>
</dependency>
<!-- spring-boot-admin相关 -->
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-client</artifactId>
<version>${spring-boot-admin.version}</version>
</dependency>
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-server</artifactId>
<version>${spring-boot-admin.version}</version>
</dependency>
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-server-ui</artifactId>
<version>${spring-boot-admin.version}</version>
</dependency>
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-server-ui-hystrix</artifactId>
<version>${spring-boot-admin.version}</version>
</dependency>
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-server-ui-turbine</artifactId>
<version>${spring-boot-admin.version}</version>
</dependency>
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-server-ui-activiti</artifactId>
<version>${spring-boot-admin.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<pluginManagement>
<plugins>
<!-- 打包源码 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.0.1</version>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar-no-fork</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- 使用spring boot的maven插件进行打包 -->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>build-info</goal>
</goals>
</execution>
</executions>
<configuration>
<!-- 是否打出可执行的jar包(仅支持Linux格式) -->
<executable>false</executable>
</configuration>
</plugin>
<!-- 将jar包和外部配置等文件整体打包(zip,tar等) -->
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<finalName>${project.artifactId}-${project.version}</finalName>
</configuration>
<executions>
<execution>
<id>full</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<descriptor>${basedir}/assembly/assembly.xml</descriptor>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
</build>
<repositories>
<repository>
<id>yexuejc-prod-nexus-public</id>
<name>yexuejc-prod-nexus-public</name>
<url>${repos.yexuejc.prod.url}</url>
</repository>
<repository>
<id>yexuejc-ivt-nexus-public</id>
<name>yexuejc-ivt-nexus-public</name>
<url>${repos.yexuejc.ivt.url}</url>
</repository>
<repository>
<id>aliyun-nexus-public</id>
<name>aliyun-nexus-public</name>
<url>${repos.aliyun.url}</url>
</repository>
<repository>
<id>jitpack.io</id>
<url>${repos.jitpack.url}</url>
</repository>
</repositories>
<!-- 中间件jar包发布目标 -->
<distributionManagement>
<repository>
<id>releases</id>
<name>nexus-release</name>
<url>${repos.yexuejc.dist.url}/releases</url>
</repository>
<snapshotRepository>
<id>snapshots</id>
<name>nexus-snapshots</name>
<url>${repos.yexuejc.dist.url}/snapshots</url>
</snapshotRepository>
</distributionManagement>
<modules>
<module>yexuejc-springboot-base</module>
</modules>
</project>

24
yexuejc-springboot-base/.gitignore vendored Normal file
View File

@ -0,0 +1,24 @@
target/
!.mvn/wrapper/maven-wrapper.jar
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
nbproject/private/
build/
nbbuild/
dist/
nbdist/
.nb-gradle/

225
yexuejc-springboot-base/mvnw vendored Normal file
View File

@ -0,0 +1,225 @@
#!/bin/sh
# ----------------------------------------------------------------------------
# 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.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven2 Start Up Batch script
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# M2_HOME - location of maven2's installed home dir
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
if [ -f /etc/mavenrc ] ; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ] ; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
case "`uname`" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
if [ -z "$JAVA_HOME" ]; then
if [ -x "/usr/libexec/java_home" ]; then
export JAVA_HOME="`/usr/libexec/java_home`"
else
export JAVA_HOME="/Library/Java/Home"
fi
fi
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=`java-config --jre-home`
fi
fi
if [ -z "$M2_HOME" ] ; then
## resolve links - $0 may be a link to maven's home
PRG="$0"
# need this for relative symlinks
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG="`dirname "$PRG"`/$link"
fi
done
saveddir=`pwd`
M2_HOME=`dirname "$PRG"`/..
# make it fully qualified
M2_HOME=`cd "$M2_HOME" && pwd`
cd "$saveddir"
# echo Using m2 at $M2_HOME
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --unix "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi
# For Migwn, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$M2_HOME" ] &&
M2_HOME="`(cd "$M2_HOME"; pwd)`"
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
# TODO classpath?
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="`which javac`"
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=`which readlink`
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
if $darwin ; then
javaHome="`dirname \"$javaExecutable\"`"
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
else
javaExecutable="`readlink -f \"$javaExecutable\"`"
fi
javaHome="`dirname \"$javaExecutable\"`"
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ] ; then
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
else
JAVACMD="`which java`"
fi
fi
if [ ! -x "$JAVACMD" ] ; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ] ; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
if [ -z "$1" ]
then
echo "Path not specified to find_maven_basedir"
return 1
fi
basedir="$1"
wdir="$1"
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
if [ -d "${wdir}" ]; then
wdir=`cd "$wdir/.."; pwd`
fi
# end of workaround
done
echo "${basedir}"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
echo "$(tr -s '\n' ' ' < "$1")"
fi
}
BASE_DIR=`find_maven_basedir "$(pwd)"`
if [ -z "$BASE_DIR" ]; then
exit 1;
fi
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
echo $MAVEN_PROJECTBASEDIR
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --path --windows "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
fi
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
exec "$JAVACMD" \
$MAVEN_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"

143
yexuejc-springboot-base/mvnw.cmd vendored Normal file
View File

@ -0,0 +1,143 @@
@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 http://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 Maven2 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 key stroke 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 enable echoing my 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
%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%

View File

@ -0,0 +1,94 @@
<?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">
<modelVersion>4.0.0</modelVersion>
<artifactId>yexuejc-springboot-base</artifactId>
<packaging>jar</packaging>
<parent>
<groupId>com.yexuejc.springboot</groupId>
<artifactId>yexuejc-springboot-parent</artifactId>
<version>1.0.3</version>
<!-- 本地打包:使用相对关联路径 -->
<!--<relativePath>../../yexuejc</relativePath>-->
</parent>
<name>${project.artifactId}</name>
<!--<properties>-->
<!--<main.basedir>${basedir}/..</main.basedir>-->
<!--</properties>-->
<dependencies>
<!--基础包-->
<dependency>
<groupId>com.github.yexuejc</groupId>
<artifactId>yexuejc-base</artifactId>
</dependency>
<!-- 使用springMVC -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<optional>true</optional><!-- optional=true,依赖不会传递该项目依赖devtools之后依赖base项目的项目如果想要使用devtools需要重新引入 -->
</dependency>
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
<optional>true</optional>
</dependency>
<!-- 用于生成application.properties等配置文件中的自定义配置项(非默认项)的meta-data -->
<!-- meta-data用于帮助IDE自动完成代码。程序运行不需要该依赖,可以不用引入,只是用于消除STS的警告信息 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<!-- 阿里云基础SDK -->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<optional>true</optional>
</dependency>
<!-- 阿里云OSS相关SDK -->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<optional>true</optional>
</dependency>
<!-- JJWT -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<optional>true</optional>
</dependency>
<!-- 使用Redis -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<optional>true</optional>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-source-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,463 @@
package com.yexuejc.springboot.base.autoconfigure;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties.Cluster;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties.Sentinel;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisNode;
import org.springframework.data.redis.connection.RedisSentinelConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnection;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPoolConfig;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
@Configuration
@ConditionalOnClass({ JedisConnection.class, RedisOperations.class, Jedis.class })
@EnableConfigurationProperties(RedisProperties.class)
@Order(1)
public class MutiRedisAutoConfiguration {
public static final String BEAN_REDIS_FACTORY0 = "redisConnectionFactory";
public static final String BEAN_REDIS_TEMPLATE0 = "redisTemplate";
public static final String BEAN_REDIS_STRING_TEMPLATE0 = "stringRedisTemplate";
public static final String BEAN_REDIS_FACTORY1 = "redis-factory-1";
public static final String BEAN_REDIS_TEMPLATE1 = "redis-template-1";
public static final String BEAN_REDIS_STRING_TEMPLATE1 = "redis-string-template-1";
public static final String BEAN_REDIS_FACTORY2 = "redis-factory-2";
public static final String BEAN_REDIS_TEMPLATE2 = "redis-template-2";
public static final String BEAN_REDIS_STRING_TEMPLATE2 = "redis-string-template-2";
public static final String BEAN_REDIS_FACTORY3 = "redis-factory-3";
public static final String BEAN_REDIS_TEMPLATE3 = "redis-template-3";
public static final String BEAN_REDIS_STRING_TEMPLATE3 = "redis-string-template-3";
public static final String BEAN_REDIS_FACTORY4 = "redis-factory-4";
public static final String BEAN_REDIS_TEMPLATE4 = "redis-template-4";
public static final String BEAN_REDIS_STRING_TEMPLATE4 = "redis-string-template-4";
public static final String BEAN_REDIS_FACTORY5 = "redis-factory-5";
public static final String BEAN_REDIS_TEMPLATE5 = "redis-template-5";
public static final String BEAN_REDIS_STRING_TEMPLATE5 = "redis-string-template-5";
public static final String BEAN_REDIS_FACTORY6 = "redis-factory-6";
public static final String BEAN_REDIS_TEMPLATE6 = "redis-template-6";
public static final String BEAN_REDIS_STRING_TEMPLATE6 = "redis-string-template-6";
public static final String BEAN_REDIS_FACTORY7 = "redis-factory-7";
public static final String BEAN_REDIS_TEMPLATE7 = "redis-template-7";
public static final String BEAN_REDIS_STRING_TEMPLATE7 = "redis-string-template-7";
public static final String BEAN_REDIS_FACTORY8 = "redis-factory-8";
public static final String BEAN_REDIS_TEMPLATE8 = "redis-template-8";
public static final String BEAN_REDIS_STRING_TEMPLATE8 = "redis-string-template-8";
public static final String BEAN_REDIS_FACTORY9 = "redis-factory-9";
public static final String BEAN_REDIS_TEMPLATE9 = "redis-template-9";
public static final String BEAN_REDIS_STRING_TEMPLATE9 = "redis-string-template-9";
/**
* Redis connection configuration.
*/
@Configuration
@ConditionalOnClass(GenericObjectPool.class)
protected static class RedisConnectionConfiguration {
private final RedisProperties properties;
private final RedisSentinelConfiguration sentinelConfiguration;
private final RedisClusterConfiguration clusterConfiguration;
public RedisConnectionConfiguration(RedisProperties properties,
ObjectProvider<RedisSentinelConfiguration> sentinelConfiguration,
ObjectProvider<RedisClusterConfiguration> clusterConfiguration) {
this.properties = properties;
this.sentinelConfiguration = sentinelConfiguration.getIfAvailable();
this.clusterConfiguration = clusterConfiguration.getIfAvailable();
}
@Primary
@Bean(BEAN_REDIS_FACTORY0)
@ConditionalOnProperty(name = "afound.redis.db0", matchIfMissing = true)
public JedisConnectionFactory redisConnectionFactory0() throws UnknownHostException {
return applyProperties(createJedisConnectionFactory(), 0);
}
@Bean(BEAN_REDIS_FACTORY1)
@ConditionalOnProperty(name = "afound.redis.db1")
public JedisConnectionFactory redisConnectionFactory1() throws UnknownHostException {
return applyProperties(createJedisConnectionFactory(), 1);
}
@Bean(BEAN_REDIS_FACTORY2)
@ConditionalOnProperty(name = "afound.redis.db2")
public JedisConnectionFactory redisConnectionFactory2() throws UnknownHostException {
return applyProperties(createJedisConnectionFactory(), 2);
}
@Bean(BEAN_REDIS_FACTORY3)
@ConditionalOnProperty(name = "afound.redis.db3")
public JedisConnectionFactory redisConnectionFactory3() throws UnknownHostException {
return applyProperties(createJedisConnectionFactory(), 3);
}
@Bean(BEAN_REDIS_FACTORY4)
@ConditionalOnProperty(name = "afound.redis.db4")
public JedisConnectionFactory redisConnectionFactory4() throws UnknownHostException {
return applyProperties(createJedisConnectionFactory(), 4);
}
@Bean(BEAN_REDIS_FACTORY5)
@ConditionalOnProperty(name = "afound.redis.db5")
public JedisConnectionFactory redisConnectionFactory5() throws UnknownHostException {
return applyProperties(createJedisConnectionFactory(), 5);
}
@Bean(BEAN_REDIS_FACTORY6)
@ConditionalOnProperty(name = "afound.redis.db6")
public JedisConnectionFactory redisConnectionFactory6() throws UnknownHostException {
return applyProperties(createJedisConnectionFactory(), 6);
}
@Bean(BEAN_REDIS_FACTORY7)
@ConditionalOnProperty(name = "afound.redis.db7")
public JedisConnectionFactory redisConnectionFactory7() throws UnknownHostException {
return applyProperties(createJedisConnectionFactory(), 7);
}
@Bean(BEAN_REDIS_FACTORY8)
@ConditionalOnProperty(name = "afound.redis.db8")
public JedisConnectionFactory redisConnectionFactory8() throws UnknownHostException {
return applyProperties(createJedisConnectionFactory(), 8);
}
@Bean(BEAN_REDIS_FACTORY9)
@ConditionalOnProperty(name = "afound.redis.db9")
public JedisConnectionFactory redisConnectionFactory9() throws UnknownHostException {
return applyProperties(createJedisConnectionFactory(), 9);
}
protected final JedisConnectionFactory applyProperties(JedisConnectionFactory factory, int database) {
configureConnection(factory);
if (this.properties.isSsl()) {
factory.setUseSsl(true);
}
factory.setDatabase(database);
if (this.properties.getTimeout() > 0) {
factory.setTimeout(this.properties.getTimeout());
}
return factory;
}
private void configureConnection(JedisConnectionFactory factory) {
if (StringUtils.hasText(this.properties.getUrl())) {
configureConnectionFromUrl(factory);
} else {
factory.setHostName(this.properties.getHost());
factory.setPort(this.properties.getPort());
if (this.properties.getPassword() != null) {
factory.setPassword(this.properties.getPassword());
}
}
}
private void configureConnectionFromUrl(JedisConnectionFactory factory) {
String url = this.properties.getUrl();
if (url.startsWith("rediss://")) {
factory.setUseSsl(true);
}
try {
URI uri = new URI(url);
factory.setHostName(uri.getHost());
factory.setPort(uri.getPort());
if (uri.getUserInfo() != null) {
String password = uri.getUserInfo();
int index = password.lastIndexOf(":");
if (index >= 0) {
password = password.substring(index + 1);
}
factory.setPassword(password);
}
} catch (URISyntaxException ex) {
throw new IllegalArgumentException("Malformed 'spring.redis.url' " + url, ex);
}
}
protected final RedisSentinelConfiguration getSentinelConfig() {
if (this.sentinelConfiguration != null) {
return this.sentinelConfiguration;
}
Sentinel sentinelProperties = this.properties.getSentinel();
if (sentinelProperties != null) {
RedisSentinelConfiguration config = new RedisSentinelConfiguration();
config.master(sentinelProperties.getMaster());
config.setSentinels(createSentinels(sentinelProperties));
return config;
}
return null;
}
/**
* Create a {@link RedisClusterConfiguration} if necessary.
*
* @return {@literal null} if no cluster settings are set.
*/
protected final RedisClusterConfiguration getClusterConfiguration() {
if (this.clusterConfiguration != null) {
return this.clusterConfiguration;
}
if (this.properties.getCluster() == null) {
return null;
}
Cluster clusterProperties = this.properties.getCluster();
RedisClusterConfiguration config = new RedisClusterConfiguration(clusterProperties.getNodes());
if (clusterProperties.getMaxRedirects() != null) {
config.setMaxRedirects(clusterProperties.getMaxRedirects());
}
return config;
}
private List<RedisNode> createSentinels(Sentinel sentinel) {
List<RedisNode> nodes = new ArrayList<RedisNode>();
for (String node : StringUtils.commaDelimitedListToStringArray(sentinel.getNodes())) {
try {
String[] parts = StringUtils.split(node, ":");
Assert.state(parts.length == 2, "Must be defined as 'host:port'");
nodes.add(new RedisNode(parts[0], Integer.valueOf(parts[1])));
} catch (RuntimeException ex) {
throw new IllegalStateException("Invalid redis sentinel " + "property '" + node + "'", ex);
}
}
return nodes;
}
private JedisConnectionFactory createJedisConnectionFactory() {
JedisPoolConfig poolConfig = this.properties.getPool() != null ? jedisPoolConfig() : new JedisPoolConfig();
if (getSentinelConfig() != null) {
return new JedisConnectionFactory(getSentinelConfig(), poolConfig);
}
if (getClusterConfiguration() != null) {
return new JedisConnectionFactory(getClusterConfiguration(), poolConfig);
}
return new JedisConnectionFactory(poolConfig);
}
private JedisPoolConfig jedisPoolConfig() {
JedisPoolConfig config = new JedisPoolConfig();
RedisProperties.Pool props = this.properties.getPool();
config.setMaxTotal(props.getMaxActive());
config.setMaxIdle(props.getMaxIdle());
config.setMinIdle(props.getMinIdle());
config.setMaxWaitMillis(props.getMaxWait());
return config;
}
}
/**
* Standard Redis configuration.
*/
@Configuration
protected static class RedisConfiguration {
@Primary
@Bean(BEAN_REDIS_TEMPLATE0)
@ConditionalOnProperty(name = "afound.redis.db0", matchIfMissing = true)
public RedisTemplate<Object, Object> redisTemplate(
@Qualifier(BEAN_REDIS_FACTORY0) RedisConnectionFactory redisConnectionFactory)
throws UnknownHostException {
return createRedisTemplate(redisConnectionFactory);
}
@Bean(BEAN_REDIS_STRING_TEMPLATE0)
@ConditionalOnProperty(name = "afound.redis.db0", matchIfMissing = true)
public StringRedisTemplate stringRedisTemplate(
@Qualifier(BEAN_REDIS_FACTORY0) RedisConnectionFactory redisConnectionFactory)
throws UnknownHostException {
return createStringRedisTemplate(redisConnectionFactory);
}
@Bean(BEAN_REDIS_TEMPLATE1)
@ConditionalOnProperty(name = "afound.redis.db1")
public RedisTemplate<Object, Object> redisTemplate1(
@Qualifier(BEAN_REDIS_FACTORY1) RedisConnectionFactory redisConnectionFactory)
throws UnknownHostException {
return createRedisTemplate(redisConnectionFactory);
}
@Bean(BEAN_REDIS_STRING_TEMPLATE1)
@ConditionalOnProperty(name = "afound.redis.db1")
public StringRedisTemplate stringRedisTemplate1(
@Qualifier(BEAN_REDIS_FACTORY1) RedisConnectionFactory redisConnectionFactory)
throws UnknownHostException {
return createStringRedisTemplate(redisConnectionFactory);
}
@Bean(BEAN_REDIS_TEMPLATE2)
@ConditionalOnProperty(name = "afound.redis.db2")
public RedisTemplate<Object, Object> redisTemplate2(
@Qualifier(BEAN_REDIS_FACTORY2) RedisConnectionFactory redisConnectionFactory)
throws UnknownHostException {
return createRedisTemplate(redisConnectionFactory);
}
@Bean(BEAN_REDIS_STRING_TEMPLATE2)
@ConditionalOnProperty(name = "afound.redis.db2")
public StringRedisTemplate stringRedisTemplate2(
@Qualifier(BEAN_REDIS_FACTORY2) RedisConnectionFactory redisConnectionFactory)
throws UnknownHostException {
return createStringRedisTemplate(redisConnectionFactory);
}
@Bean(BEAN_REDIS_TEMPLATE3)
@ConditionalOnProperty(name = "afound.redis.db3")
public RedisTemplate<Object, Object> redisTemplate3(
@Qualifier(BEAN_REDIS_FACTORY3) RedisConnectionFactory redisConnectionFactory)
throws UnknownHostException {
return createRedisTemplate(redisConnectionFactory);
}
@Bean(BEAN_REDIS_STRING_TEMPLATE3)
@ConditionalOnProperty(name = "afound.redis.db3")
public StringRedisTemplate stringRedisTemplate3(
@Qualifier(BEAN_REDIS_FACTORY3) RedisConnectionFactory redisConnectionFactory)
throws UnknownHostException {
return createStringRedisTemplate(redisConnectionFactory);
}
@Bean(BEAN_REDIS_TEMPLATE4)
@ConditionalOnProperty(name = "afound.redis.db4")
public RedisTemplate<Object, Object> redisTemplate4(
@Qualifier(BEAN_REDIS_FACTORY4) RedisConnectionFactory redisConnectionFactory)
throws UnknownHostException {
return createRedisTemplate(redisConnectionFactory);
}
@Bean(BEAN_REDIS_STRING_TEMPLATE4)
@ConditionalOnProperty(name = "afound.redis.db4")
public StringRedisTemplate stringRedisTemplate4(
@Qualifier(BEAN_REDIS_FACTORY4) RedisConnectionFactory redisConnectionFactory)
throws UnknownHostException {
return createStringRedisTemplate(redisConnectionFactory);
}
@Bean(BEAN_REDIS_TEMPLATE5)
@ConditionalOnProperty(name = "afound.redis.db5")
public RedisTemplate<Object, Object> redisTemplate5(
@Qualifier(BEAN_REDIS_FACTORY5) RedisConnectionFactory redisConnectionFactory)
throws UnknownHostException {
return createRedisTemplate(redisConnectionFactory);
}
@Bean(BEAN_REDIS_STRING_TEMPLATE5)
@ConditionalOnProperty(name = "afound.redis.db5")
public StringRedisTemplate stringRedisTemplate5(
@Qualifier(BEAN_REDIS_FACTORY5) RedisConnectionFactory redisConnectionFactory)
throws UnknownHostException {
return createStringRedisTemplate(redisConnectionFactory);
}
@Bean(BEAN_REDIS_TEMPLATE6)
@ConditionalOnProperty(name = "afound.redis.db6")
public RedisTemplate<Object, Object> redisTemplate6(
@Qualifier(BEAN_REDIS_FACTORY6) RedisConnectionFactory redisConnectionFactory)
throws UnknownHostException {
return createRedisTemplate(redisConnectionFactory);
}
@Bean(BEAN_REDIS_STRING_TEMPLATE6)
@ConditionalOnProperty(name = "afound.redis.db6")
public StringRedisTemplate stringRedisTemplate6(
@Qualifier(BEAN_REDIS_FACTORY6) RedisConnectionFactory redisConnectionFactory)
throws UnknownHostException {
return createStringRedisTemplate(redisConnectionFactory);
}
@Bean(BEAN_REDIS_TEMPLATE7)
@ConditionalOnProperty(name = "afound.redis.db7")
public RedisTemplate<Object, Object> redisTemplate7(
@Qualifier(BEAN_REDIS_FACTORY7) RedisConnectionFactory redisConnectionFactory)
throws UnknownHostException {
return createRedisTemplate(redisConnectionFactory);
}
@Bean(BEAN_REDIS_STRING_TEMPLATE7)
@ConditionalOnProperty(name = "afound.redis.db7")
public StringRedisTemplate stringRedisTemplate7(
@Qualifier(BEAN_REDIS_FACTORY7) RedisConnectionFactory redisConnectionFactory)
throws UnknownHostException {
return createStringRedisTemplate(redisConnectionFactory);
}
@Bean(BEAN_REDIS_TEMPLATE8)
@ConditionalOnProperty(name = "afound.redis.db8")
public RedisTemplate<Object, Object> redisTemplate8(
@Qualifier(BEAN_REDIS_FACTORY8) RedisConnectionFactory redisConnectionFactory)
throws UnknownHostException {
return createRedisTemplate(redisConnectionFactory);
}
@Bean(BEAN_REDIS_STRING_TEMPLATE8)
@ConditionalOnProperty(name = "afound.redis.db8")
public StringRedisTemplate stringRedisTemplate8(
@Qualifier(BEAN_REDIS_FACTORY8) RedisConnectionFactory redisConnectionFactory)
throws UnknownHostException {
return createStringRedisTemplate(redisConnectionFactory);
}
@Bean(BEAN_REDIS_TEMPLATE9)
@ConditionalOnProperty(name = "afound.redis.db9")
public RedisTemplate<Object, Object> redisTemplate9(
@Qualifier(BEAN_REDIS_FACTORY9) RedisConnectionFactory redisConnectionFactory)
throws UnknownHostException {
return createRedisTemplate(redisConnectionFactory);
}
@Bean(BEAN_REDIS_STRING_TEMPLATE9)
@ConditionalOnProperty(name = "afound.redis.db9")
public StringRedisTemplate stringRedisTemplate9(
@Qualifier(BEAN_REDIS_FACTORY9) RedisConnectionFactory redisConnectionFactory)
throws UnknownHostException {
return createStringRedisTemplate(redisConnectionFactory);
}
private RedisTemplate<Object, Object> createRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<Object, Object> template = new RedisTemplate<Object, Object>();
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(new Jackson2JsonRedisSerializer<Object>(Object.class));
template.setKeySerializer(new StringRedisSerializer());
template.setDefaultSerializer(new StringRedisSerializer());
template.setValueSerializer(new StringRedisSerializer());
template.setConnectionFactory(redisConnectionFactory);
return template;
}
private StringRedisTemplate createStringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
}
}

View File

@ -0,0 +1,32 @@
package com.yexuejc.springboot.base.autoconfigure;
import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* OSS相关配置
*/
@Configuration
@ConditionalOnClass({ OSSClient.class })
@EnableConfigurationProperties(OssProperties.class)
public class OssAutoConfiguration {
private final OssProperties properties;
public OssAutoConfiguration(OssProperties properties) {
this.properties = properties;
}
@Bean
@ConditionalOnMissingBean
public OssFacade ossFacade() {
ClientConfiguration configuration = new ClientConfiguration();
configuration.setSupportCname(false);
return new OssFacade(properties, configuration);
}
}

View File

@ -0,0 +1,68 @@
package com.yexuejc.springboot.base.autoconfigure;
import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.CopyObjectResult;
import com.aliyun.oss.model.PutObjectResult;
import java.io.InputStream;
/**
* 阿里云OSS服务MNS操作类
*/
public class OssFacade {
private final OssProperties properties;
private final ClientConfiguration configuration;
public OssFacade(OssProperties properties, ClientConfiguration configuration) {
this.properties = properties;
this.configuration = configuration;
}
/**
* 拷贝对象在默认Bucket中拷贝
*
* @param srcKey 元对象Key
* @param destKey 目标对象Key
* @return CopyObjectResult
*/
public CopyObjectResult copyObject(String srcKey, String destKey) {
OSSClient client = ossClient();
CopyObjectResult result = client.copyObject(properties.getBucket(), srcKey, properties.getBucket(), destKey);
client.shutdown();
return result;
}
/**
* 上传文件简单上传适合小文件
*
* @param key 上传位置
* @param inputStream
* @return
*/
public PutObjectResult putObject(String key, InputStream inputStream) {
OSSClient client = ossClient();
PutObjectResult result = client.putObject(properties.getBucket(), key, inputStream);
client.shutdown();
return result;
}
/**
* 判断文件是否存在
*
* @param key 文件位置
* @return
*/
public boolean doesObjectExist(String key) {
OSSClient client = ossClient();
boolean isExist = client.doesObjectExist(properties.getBucket(), key);
client.shutdown();
return isExist;
}
private OSSClient ossClient() {
return new OSSClient(properties.getEndpoint(), properties.getAccessKeyID(), properties.getAccessKeySecret(),
configuration);
}
}

View File

@ -0,0 +1,49 @@
package com.yexuejc.springboot.base.autoconfigure;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "yexuejc.oss")
public class OssProperties {
/** Endpoint 默认内网外网需要自行配置http://oss-cn-hangzhou.aliyuncs.com */
private String endpoint = "oss-cn-hangzhou-internal.aliyuncs.com";
/** 产品域名(固定) */
private String accessKeyID = "LTAInCYwtsprAu8g";
/** 区域ID(固定) */
private String accessKeySecret = "6aqMtyFuJPUPChYpZSLsQ11cg4qby7";
/** 默认bucket */
private String bucket = "ecentm-res";
public String getEndpoint() {
return endpoint;
}
public void setEndpoint(String endpoint) {
this.endpoint = endpoint;
}
public String getAccessKeyID() {
return accessKeyID;
}
public void setAccessKeyID(String accessKeyID) {
this.accessKeyID = accessKeyID;
}
public String getAccessKeySecret() {
return accessKeySecret;
}
public void setAccessKeySecret(String accessKeySecret) {
this.accessKeySecret = accessKeySecret;
}
public String getBucket() {
return bucket;
}
public void setBucket(String bucket) {
this.bucket = bucket;
}
}

View File

@ -0,0 +1,114 @@
package com.yexuejc.springboot.base.autoconfigure;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.yexuejc.base.http.Resps;
import com.yexuejc.base.util.DateUtil;
import com.yexuejc.springboot.base.filter.ValidationFilter;
import com.yexuejc.springboot.base.filter.ValidationFilterProperties;
import com.yexuejc.springboot.base.interceptor.LogInterceptor;
import com.yexuejc.springboot.base.util.LogUtil;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
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 org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* WebMvc相关配置
*
* @PackageName: com.yexuejc.util.base.http
* @Description:
* @author: maxf
* @date: 2018/1/11 19:51
*/
@Configuration
@ConditionalOnWebApplication
@EnableConfigurationProperties(ValidationFilterProperties.class)
public class WebAutoConfiguration extends WebMvcConfigurerAdapter {
public WebAutoConfiguration(ValidationFilterProperties properties) {
this.properties = properties;
}
/**
* 添加拦截器
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 日志拦截器
registry.addInterceptor(new LogInterceptor()).addPathPatterns("/**");
super.addInterceptors(registry);
}
/**
* 重写jsonConverter参数
*
* @param objectMapper
* @return
*/
@Bean
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter(ObjectMapper objectMapper) {
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
objectMapper.setDateFormat(DateUtil.DATE_TIME_FORMAT);
return new MappingJackson2HttpMessageConverter(objectMapper);
}
private final ValidationFilterProperties properties;
/**
* 添加校验过滤器目前校验HTTP Header是否符合规范
*
* @return
*/
@Bean
@ConditionalOnProperty(name = "yexuejc.web.validation-filter.enable", matchIfMissing = true)
public FilterRegistrationBean validationFilter() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new ValidationFilter(properties));
registration.addUrlPatterns("/*");
registration.setName("validationFilter");
registration.setOrder(Ordered.HIGHEST_PRECEDENCE + 20);
return registration;
}
/**
* 全局异常处理
*/
@ControllerAdvice
static class GlobalExceptionHandler {
private static final String ERROR_MSG = "系统错误,请联系管理员";
/**
* 出现异常时用于返回Json数据
*
* @param e
* @return
*/
@ExceptionHandler(value = Throwable.class)
@ResponseBody
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public Resps<Object> jsonErrorHandler(Throwable e) {
LogUtil.exceptionLogger.error(e.getMessage(), e);
return Resps.error(ERROR_MSG);
}
}
}

View File

@ -0,0 +1,72 @@
package com.yexuejc.springboot.base.constant;
/**
* <pre>
* 名称项目+业务code
* 业务code:项目编号+业务编号
* base:100
* api:101
* wap:102
* admin:103
* </pre>
*
* @author: maxf
* @date: 2018/3/13 19:43
*/
public class BizConsts {
/**
* base_code:100
*/
public static String BASE_CODE = "100";
/**
* 100001:该账户已被禁用
*/
public static String BASE_IS_LOCK_CODE = BASE_CODE + "001";
public static String BASE_IS_LOCK_MSG = "该账户已被禁用";
/**
* 100002:该帐户已过期
*/
public static String BASE_IS_EXPIRE_CODE = BASE_CODE + "002";
public static String BASE_IS_EXPIRE_MSG = "该帐户已过期";
/**
* 100003:登陆凭证已经过期请重新登陆
*/
public static String BASE_LOGIN_IS_EXPIRE_CODE = BASE_CODE + "003";
public static String BASE_LOGIN_IS_EXPIRE_MSG = "登陆凭证已经过期,请重新登陆";
/**
* 100004:该账户被锁定
*/
public static String BASE_IS_LOCKED_CODE = BASE_CODE + "004";
public static String BASE_IS_LOCKED_MSG = "该账户被锁定";
/**
* 100005:身份验证凭证未找到
*/
public static String BASE_CREDENTIALS_NOT_FOUND_CODE = BASE_CODE + "005";
public static String BASE_CREDENTIALS_NOT_FOUND_MSG = "身份验证凭证未找到";
/**
* 100006:密码错误
*/
public static String BASE_PWD_IS_ERR_CODE = BASE_CODE + "006";
public static String BASE_PWD_IS_ERR_MSG = "密码错误";
/**
* 100007:该账户名不存在
*/
public static String BASE_ACCOUNT_NOT_FOUND_CODE = BASE_CODE + "007";
public static String BASE_ACCOUNT_NOT_FOUND_MSG = "该账户名不存在";
/**
* 100008:登录时发生错误请联系系统管理员
*/
public static String BASE_SYS_ERR_CODE = BASE_CODE + "008";
public static String BASE_SYS_ERR_MSG = "登录时发生错误,请联系系统管理员";
/**
* 100009:权限不足
*/
public static String BASE_NOT_ROLE_CODE = BASE_CODE + "009";
public static String BASE_NOT_ROLE_MSG = "您无权访问该资源";
/**
* 100010:尚未登陆
*/
public static String BASE_NOT_LOGIN_CODE = BASE_CODE + "010";
public static String BASE_NOT_LOGIN_MSG = "您尚未登陆";
}

View File

@ -0,0 +1,15 @@
package com.yexuejc.springboot.base.constant;
/**
* redis 业务常量
*
* @author: maxf
* @date: 2018/3/13 20:20
*/
public class RedisConsts {
/**
* 用户登录
* consumer-session-13512345678
*/
public static String CONSUMER_SESSION = "consumer-session";
}

View File

@ -0,0 +1,71 @@
package com.yexuejc.springboot.base.filter;
import com.yexuejc.base.constant.RespsConsts;
import com.yexuejc.base.http.Resps;
import com.yexuejc.base.util.JsonUtil;
import com.yexuejc.springboot.base.util.LogUtil;
import com.yexuejc.springboot.base.util.NetUtil;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class ValidationFilter implements Filter {
ValidationFilterProperties properties;
public ValidationFilter(ValidationFilterProperties properties) {
this.properties = properties;
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
if (!(servletRequest instanceof HttpServletRequest) || !(servletResponse instanceof HttpServletResponse)) {
throw new ServletException("OncePerRequestFilter just supports HTTP requests");
}
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
String sp = request.getServletPath();
if (properties.getType() == 0) {
if (properties.getIgnored().contains(sp)) {
filterChain.doFilter(servletRequest, servletResponse);
return;
}
} else {
if (!properties.getIntercepts().contains(sp)) {
filterChain.doFilter(servletRequest, servletResponse);
return;
}
}
String xuserAgent = request.getHeader(RespsConsts.HEADER_X_USER_AGENT);
if (xuserAgent == null || xuserAgent.length() == 0) {
// 写日志
String uri = request.getRequestURI();
String userAgent = LogUtil.format(request.getHeader(HttpHeaders.USER_AGENT));
String ip = NetUtil.getIp(request);
LogUtil.accessLogger.warn("{};{};{};{};", uri, userAgent, xuserAgent, ip);
// 返回Response->400-E:请求错误
response.setContentType("application/json;charset=UTF-8");
response.setStatus(HttpStatus.BAD_REQUEST.value());
response.getWriter().write(JsonUtil.obj2Json(Resps.error(RespsConsts.CODE_ERROR, RespsConsts
.MSG_ERROT_HTTP)));
response.getWriter().close();
return;
}
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
}
}

View File

@ -0,0 +1,59 @@
package com.yexuejc.springboot.base.filter;
import com.yexuejc.base.util.JsonUtil;
import org.springframework.boot.context.properties.ConfigurationProperties;
import java.util.ArrayList;
import java.util.List;
/**
* 过滤路径
* @PackageName: com.uselaw.base.filter
* @Description:
* @author: maxf
* @date: 2018/2/7 19:11
*/
@ConfigurationProperties(prefix = "yexuejc.http.filter")
public class ValidationFilterProperties {
/**
* 拦截类型0忽略模式默认拦截全部1拦截模式默认一个都不拦截
*/
private int type = 1;
/**
* 忽略拦截列表路径
*/
private List<String> ignored = new ArrayList<>();
/**
* 拦截列表路径
*/
private List<String> intercepts = new ArrayList<>();
@Override
public String toString() {
return JsonUtil.obj2Json(this);
}
public List<String> getIgnored() {
return ignored;
}
public void setIgnored(List<String> ignored) {
this.ignored = ignored;
}
public List<String> getIntercepts() {
return intercepts;
}
public void setIntercepts(List<String> intercepts) {
this.intercepts = intercepts;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
}

View File

@ -0,0 +1,39 @@
package com.yexuejc.springboot.base.interceptor;
import com.yexuejc.base.constant.RespsConsts;
import com.yexuejc.springboot.base.util.LogUtil;
import com.yexuejc.springboot.base.util.NetUtil;
import org.springframework.http.HttpHeaders;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 访问日志拦截器用于记录用户访问日志
*
* @author PHY
*/
public class LogInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
// 如登录用户访问则记录其用户名手机号
String username = null;
if (SecurityContextHolder.getContext() != null && SecurityContextHolder.getContext().getAuthentication() != null
&& SecurityContextHolder.getContext().getAuthentication().getName() != null) {
username = SecurityContextHolder.getContext().getAuthentication().getName();
}
// 写日志
String uri = request.getRequestURI();
String userAgent = LogUtil.format(request.getHeader(HttpHeaders.USER_AGENT));
String xuserAgent = request.getHeader(RespsConsts.HEADER_X_USER_AGENT);
String ip = NetUtil.getIp(request);
LogUtil.accessLogger.info("{};{};{};{};{}", uri, userAgent, xuserAgent, ip, username);
return true;
}
}

View File

@ -0,0 +1,50 @@
package com.yexuejc.springboot.base.pojo;
import com.yexuejc.base.pojo.BaseVO;
import com.yexuejc.base.util.JsonUtil;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
/**
* 分页 VO
*
* @author: maxf
* @date: 2018/3/28 14:23
*/
public class PagerVO extends BaseVO {
private static final long serialVersionUID = 3490440129554644587L;
@NotNull
@Min(1L)
private Integer page = 1;
@NotNull
@Min(1L)
private Integer size = 20;
public int getOffset() {
return (this.page - 1) * this.size;
}
@Override
public String toString() {
return JsonUtil.obj2Json(this);
}
public Integer getPage() {
return page;
}
public void setPage(Integer page) {
this.page = page;
}
public Integer getSize() {
return size;
}
public void setSize(Integer size) {
this.size = size;
}
}

View File

@ -0,0 +1,38 @@
package com.yexuejc.springboot.base.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 日志处理类
*/
public class LogUtil {
private LogUtil() {
}
/**
* 用于记录访问日志输出到access.log
*/
public final static Logger accessLogger = LoggerFactory.getLogger("com.yexuejc.uselaw.access");
/**
* 用于记录业务日志输出到biz.log
*/
public final static Logger bizLogger = LoggerFactory.getLogger("com.yexuejc.uselaw.biz");
/**
* 用于记录程序异常日志输出到exception.log
*/
public final static Logger exceptionLogger = LoggerFactory.getLogger("com.yexuejc.uselaw.exception");
/**
* 格式化日志消息;替换为_)
*
* @param msg 需要被格式化的字符串
* @return 当传入参数为null时返回null
*/
public final static String format(String msg) {
if (msg == null) {
return null;
}
return msg.replaceAll(";", "_");
}
}

View File

@ -0,0 +1,52 @@
package com.yexuejc.springboot.base.util;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
/**
* 网络工具类
*/
public class NetUtil {
private NetUtil() {
}
/**
* 获取请求主机IP地址,如果通过代理进来则透过防火墙获取真实IP地址;
*
* @param request
* @return
* @throws IOException
*/
public final static String getIp(HttpServletRequest request) throws IOException {
// 获取请求主机IP地址,如果通过代理进来则透过防火墙获取真实IP地址
String ip = request.getHeader("X-Forwarded-For");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
} else if (ip.length() > 15) {
String[] ips = ip.split(",");
for (int index = 0; index < ips.length; index++) {
String strIp = (String) ips[index];
if (!("unknown".equalsIgnoreCase(strIp))) {
ip = strIp;
break;
}
}
}
return ip;
}
}

View File

@ -0,0 +1,42 @@
package com.yexuejc.springboot.base.util;
import com.yexuejc.base.constant.RespsConsts;
import com.yexuejc.base.http.Resps;
import org.springframework.http.HttpStatus;
import org.springframework.validation.Errors;
import org.springframework.validation.ObjectError;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
/**
* 检查SpringMVC提交是否有数据校验错误
*
* @PackageName: com.yexuejc.util.base.util
* @Description:
* @author: maxf
* @date: 2018/1/17 14:01
*/
public class ValidUtil {
private ValidUtil() {
}
/**
* APP用 检查SpringMVC提交是否有数据校验错误如果有错则直接response错误信息
*
* @param errors
* @return
* @throws IOException
*/
public static Resps<Object> errResps(HttpServletResponse response, Errors errors) throws IOException {
List<ObjectError> objectErrorList = errors.getAllErrors();
String[] err = new String[objectErrorList.size()];
for (int i = 0; i < objectErrorList.size(); i++) {
err[i] = objectErrorList.get(i).getDefaultMessage() == null ? objectErrorList.get(i).getCode() : objectErrorList.get(i).getDefaultMessage();
}
response.setStatus(HttpStatus.BAD_REQUEST.value());
return Resps.error(RespsConsts.CODE_VALIDATION, err);
}
}

View File

@ -0,0 +1,4 @@
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.yexuejc.springboot.base.autoconfigure.WebAutoConfiguration,\
com.yexuejc.springboot.base.autoconfigure.OssAutoConfiguration,\
com.yexuejc.springboot.base.autoconfigure.MutiRedisAutoConfiguration

View File

@ -0,0 +1,63 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!-- 固定配置 START -->
<property name="context.name" value="yexuejc-springboot-base" />
<property name="log.path" value="../logs" />
<property name="log.pattern"
value='%d{yyyy-MM-dd_HH:mm:ss.SSS};%level;%C{0};%M;%L;%msg%n' />
<property name="roll.file.suffix" value="%d{yyyy-MM-dd}.tar.gz" />
<contextName>${context.name}</contextName>
<appender name="ACCESS"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/access.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${log.path}/access.${roll.file.suffix}
</fileNamePattern>
</rollingPolicy>
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
</appender>
<appender name="BIZ"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/biz.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${log.path}/biz.${roll.file.suffix}
</fileNamePattern>
</rollingPolicy>
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
</appender>
<appender name="EXCEPTION"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/exception.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${log.path}/exception.${roll.file.suffix}
</fileNamePattern>
</rollingPolicy>
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
</appender>
<logger name="com.yexuejc.uselaw.access" level="INFO">
<appender-ref ref="ACCESS" />
</logger>
<logger name="com.yexuejc.uselaw.biz" level="INFO">
<appender-ref ref="BIZ" />
</logger>
<logger name="com.yexuejc.uselaw.exception" level="ERROR">
<appender-ref ref="EXCEPTION" />
</logger>
<!-- 固定配置 END -->
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<!-- encoder 默认配置为PatternLayoutEncoder -->
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
</appender>
<root level="debug">
<appender-ref ref="CONSOLE" />
</root>
</configuration>

View File

@ -0,0 +1,11 @@
package com.yexuejc.springboot.base;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ApplicationRun {
public static void main(String[] args) {
SpringApplication.run(ApplicationRun.class, args);
}
}

View File

@ -0,0 +1,17 @@
package com.yexuejc.springboot.base;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = ApplicationRun.class)
public class ApplicationTest {
@Test
public void contextLoads() {
System.out.printf("springboot test is runing");
}
}

View File

@ -0,0 +1,2 @@
server.port=8080
logging.level.root=info