做者:霜花似雪css
www.imooc.com/article/292…
html
|
<
plugin
>
<
groupid
>org.apache.maven.plugins</
groupid
>
<
artifactid
>maven-compiler-plugin</
artifactid
>
<
version
>3.6</
version
>
<
configuration
>
<
source
>1.8</
source
>
<
target
>1.8</
target
>
</
configuration
>
</
plugin
>
|
|
<
properties
>
<
project.build.sourceEncoding
>UTF-8</
project.build.sourceEncoding
>
<
project.reporting.outputEncoding
>UTF-8</
project.reporting.outputEncoding
>
<
java.version
>1.8</
java.version
>
</
properties
>
|
|
#啓動端口
server.port=
8080
#當項目出錯時跳轉的頁面
server.error.path=/error
#session失效時間,30m表示
30
分鐘
server.servlet.session.timeout=30m
#項目路徑名稱,默認爲/
server.servlet.context-path=/
#配置tomcat請求編碼
server.tomcat.uri-encoding=utf-
8
#Tomcat最大線程數
server.tomcat.max-threads=
500
#存放Tomcat運行日誌和臨時文件的目錄,若不配值則默認使用系統的臨時目錄
server.tomcat.basedir=/home/tmp
|
利用Java數字證書管理工具keytool生成一個數字證書,cmd命令窗口生成命令:java
keytool -genkey -alias tomcathttps -keyalg RSA -keysize
2048
-keystore key.p12 -validity
365
|
命令解釋:mysql
• -genkey 表示要建立一個新的密鑰。web
• -alias 表示 keystore 的別名。redis
• -keyalg 表示使用的加密算法是 RSA, 一種非對稱加密算法.算法
• -keysize 表示密鑰的長度.spring
• -keystore 表示生成的密鑰存放位直。sql
• -validity 表示密鑰的有效時間,單位爲天。mongodb
將生成的數字證書添加到項目根目錄下,在application.properties中作以下配置:
|
#祕鑰文件名
server.ssl.key- store=key.pl2
#祕鑰別名,就是在cmd命令執行中alias的參數
server.ssl.key-alias=tomcathttps
#祕鑰密碼,就是在cmd命令執行中輸入的密碼
server.ssl.key- store-password=l23456
|
在瀏覽器中訪問項目時,記得添加信任便可訪問。
|
<
dependency
>
<
groupid
>org. springframework.boot</
groupid
>
<
artifactid
>spring-boot-starter-web</
artifactid
>
<!--禁用tomcat服務器-->
<
exclusions
>
<
exclusion
>
<
groupid
>org.springframework.boot</
groupid
>
<
artifactid
>spring-boot-starter-tomcat </
artifactid
>
</
exclusion
>
</
exclusions
>
</
dependency
>
<
dependency
>
<
groupid
>org.springframework.boot</
groupid
>
<
artifactid
>spring-boot-starter-jetty</
artifactid
>
</
dependency
>
|
|
#test:測試環境/dev:開發環境/prod:生產環境
spring.profiles.active=test/dev/prod
|
在pom.xml中引入thymeleaf依賴,以下:
|
<
dependency
>
<
groupid
>org.springframework.boot</
groupid
>
<
artifactid
>spring-boot-starter-thymeleaf</
artifactid
>
</
dependency
>
|
常見的屬性配置:
|
#是否開啓緩存,開發時可設置爲
false
,默認爲
true
spring.thymeleaf.cache=
true
#檢查模板是否存在,默認爲
true
spring.thymeleaf.check-template=
true
#檢查模板位置是否存在,默認爲
true
spring.thymeleaf.check-template-location=
true
#模板文件編碼
spring.thymeleaf.encoding=UTF-
8
#模板文件位置
spring.thymeleaf.prefix=classpath:/templates/
#Content-Type 配置
spring.thymeleaf.servlet.content-type=text/html
#模板文件後綴
spring.thymeleaf.suffix=.html
|
在pom.xml中引入freemarker依賴配置,以下:
<
dependency
>
<
groupId
>org.springframework.boot</
groupId
>
<
artifactId
>spring-boot-starter-freemarker</
artifactId
>
</
dependency
>
|
常見的屬性配置:
#HttpServletRequest 的屬性是否能夠覆蓋 controller 中 model 的同名項
spring.freemarker.allow-request-override=
false
#HttpSession 的屬性是否能夠覆蓋 controller 中 model 的同名項
spring.freemarker.allow-session-override=
false
#是否開啓緩存
spring.freemarker.cache=
false
#模板文件編碼
spring.freemarker.charset=UTF-
8
#是否檢查模板位置
spring.freemarker.check-template-location=
true
#Content-Type 的值
spring.freemarker.content-type=text/html
#是否將 HttpServletRequest 中的屬性添加到 Model 中
spring.freemarker.expose-request-attributes=
false
#是否將 HttpSession 中的屬性添加到 Model 中
spring.freemarker.expose-session-attributes=
false
#模板文件後綴
spring.freemarker.suffix=.ftl
#模板文件位置
spring.freemarker.template-loader-path=classpath: /templates/
#設定靜態文件路徑,js,css等
spring.mvc.
static
-path-pattern=/
static
/**
|
MySQL鏈接配置:
(1) 引入jar包依賴環境
<
dependency
>
<
groupId
>mysql</
groupId
>
<
artifactId
>mysql-connector-java</
artifactId
>
<
scope
>runtime</
scope
>
</
dependency
>
|
(2)屬性文件配置
#鏈接驅動
#spring.datasource.driver-
class
-name=com.mysql.jdbc.Driver
spring.datasource.driver-
class
-name=com.mysql.cj.jdbc.Driver
#鏈接url
spring.datasource.url=jdbc:mysql:
//127.0.0.1:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
#帳號
spring.datasource.username=root
#密碼
spring.datasource.password=root
|
Oracle鏈接配置:
(1) 引入jar包依賴環境
<!-- https://mvnrepository.com/artifact/com.oracle/ojdbc6 -->
<
dependency
>
<
groupId
>com.oracle</
groupId
>
<
artifactId
>ojdbc6</
artifactId
>
<
version
>11.2.0.3</
version
>
</
dependency
>
|
(2)屬性文件配置
#oracle配置
spring.datasource.driverClassName=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:
@127
.0.
0.1
:
1521
:test
spring.datasource.username=root
spring.datasource.password=
123456
|
SQL Server鏈接配置:
(1) 引入jar包依賴環境
<
dependency
>
<
groupId
>com.microsoft.sqlserver</
groupId
>
<
artifactId
>mssql-jdbc</
artifactId
>
<
scope
>runtime</
scope
>
</
dependency
>
|
(2)屬性文件配置
#SQLServer配置
spring.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.datasource.url=jdbc:sqlserver:
//127.0.0.1:1433;DatabaseName=test
spring.datasource.username=sa
spring.datasource.password=
123456
|
PostgreSQL鏈接配置
(1) 引入jar包依賴環境
<!-- postgresql驅動 -->
<
dependency
>
<
groupId
>org.postgresql</
groupId
>
<
artifactId
>postgresql</
artifactId
>
</
dependency
>
|
(2)屬性文件配置
#PostgreSQL配置
spring.datasource.driverClassName=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql:
//127.0.0.1:5432/test
spring.datasource.username=postgres
spring.datasource.password=
123456
|
H2數據源鏈接配置:
(1) 引入jar包依賴環境
<
dependency
>
<
groupId
>com.h2database</
groupId
>
<
artifactId
>h2</
artifactId
>
<
scope
>runtime</
scope
>
</
dependency
>
|
(2)屬性文件配置
#鏈接驅動
spring.datasource.driver-
class
-name=org.h2.Driver
#數據表結構信息
spring.datasource.schema=classpath:db/schema-h2.sql
#數據表數據
spring.datasource.data=classpath:db/data-h2.sql
#鏈接url
spring.datasource.url=jdbc:h2:mem:test
#帳戶密碼
spring.datasource.username=root
spring.datasource.password=test
|
MongoDB鏈接配置
(1)引入jar包依賴環境
!-- spring-boot-starter-data-mongodb -->
<
dependency
>
<
groupId
>org.springframework.boot</
groupId
>
<
artifactId
>spring-boot-starter-data-mongodb</
artifactId
>
</
dependency
>
|
(2)屬性文件配置:
MongoDB 2.4如下版本:
# 主機地址
spring.data.mongodb.host=
127.0
.
0.1
# 端口
spring.data.mongodb.port=
27017
# 帳號密碼
spring.data.mongodb.username=root
spring.data.mongodb.password=root
# 數據庫
spring.data.mongodb.database=test
|
MongoDB 2.4以上版本:
spring.data.mongodb.uri=mongodb:
//root(userName):root(password)@localhost(ip地址):27017(端口號)/test(collections/數據庫)
|
示例:spring.data.mongodb.uri=mongodb://root:root@127.0.0.1:27017/test
(1)引入jar包依賴環境
<
dependency
>
<
groupId
>org.springframework.boot</
groupId
>
<
artifactId
>spring-boot-starter-mail</
artifactId
>
</
dependency
>
<
dependency
>
<
groupId
>com.sun.mail</
groupId
>
<
artifactId
>javax.mail</
artifactId
>
<
version
>RELEASE</
version
>
</
dependency
>
|
(2) 屬性文件配置
#
163
郵箱
spring.mail.host=smtp.
163
.com
spring.mail.username=xxx
@163
.com
spring.mail.password=xxx
#qq郵箱
#spring.mail.host=smtp.qq.com
#spring.mail.username=xxx
@qq
.com
#spring.mail.password=xxx
spring.mail.
default
-encoding=UTF-
8
#其餘郵箱配置相似
|
11. 經常使用Redis配置
(1) 引入jar包依賴環境
<
dependency
>
<
groupId
>org.springframework.boot</
groupId
>
<
artifactId
>spring-boot-starter-data-redis</
artifactId
>
</
dependency
>
|
(2)application.properties屬性文件配置
# REDIS
# Redis數據庫索引(默認爲0)
spring.redis.database=0
# Redis服務器地址
spring.redis.host=localhost
# Redis服務器鏈接端口
spring.redis.port=6379
# Redis服務器鏈接密碼(默認爲空)
spring.redis.password=
# 鏈接池最大鏈接數(使用負值表示沒有限制) 默認 8
spring.redis.lettuce.pool.max-active=8
# 鏈接池最大阻塞等待時間(使用負值表示沒有限制) 默認 -1
spring.redis.lettuce.pool.max-wait=-1
# 鏈接池中的最大空閒鏈接 默認 8
spring.redis.lettuce.pool.max-idle=8
# 鏈接池中的最小空閒鏈接 默認 0
spring.redis.lettuce.pool.min-idle=0
# 鏈接超時時間(毫秒)
spring.redis.timeout=1000
|
12. 配置Druid數據源
(1) 引入jar依賴環境
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<
dependency
>
<
groupId
>com.alibaba</
groupId
>
<
artifactId
>druid</
artifactId
>
<
version
>1.1.17</
version
>
</
dependency
>
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<
dependency
>
<
groupId
>log4j</
groupId
>
<
artifactId
>log4j</
artifactId
>
<
version
>1.2.17</
version
>
</
dependency
>
|
(2) application.properties屬性文件配置
這裏以MySQL爲例,以下:
# 驅動配置信息
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
spring.datasource.username=root
spring.datasource.password=root
# 鏈接池的配置信息
# 初始化大小,最小,最大
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
# 配置獲取鏈接等待超時的時間
spring.datasource.maxWait=60000
# 配置間隔多久才進行一次檢測,檢測須要關閉的空閒鏈接,單位是毫秒
spring.datasource.timeBetweenEvictionRunsMillis=60000
# 配置一個鏈接在池中最小生存的時間,單位是毫秒
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
# 打開PSCache,而且指定每一個鏈接上PSCache的大小
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
# 配置監控統計攔截的filters,去掉後監控界面sql沒法統計,'wall'用於防火牆
spring.datasource.filters=stat,wall,log4j
# 經過connectProperties屬性來打開mergeSql功能;慢SQL記錄
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
|
(3) 代碼配置
import
com.alibaba.druid.pool.DruidDataSource;
import
com.alibaba.druid.support.http.StatViewServlet;
import
com.alibaba.druid.support.http.WebStatFilter;
import
org.slf4j.Logger;
import
org.slf4j.LoggerFactory;
import
org.springframework.boot.context.properties.ConfigurationProperties;
import
org.springframework.boot.web.servlet.FilterRegistrationBean;
import
org.springframework.boot.web.servlet.ServletRegistrationBean;
import
org.springframework.context.annotation.Bean;
import
org.springframework.context.annotation.Configuration;
import
javax.sql.DataSource;
import
java.util.HashMap;
import
java.util.Map;
/**
* @ClassName: DruidConfiguration
* @Author: liuhefei
* @Description: Druid數據庫配置
* @Date: 2019/6/6 19:57
*/
@Configuration
public
class
DruidConfiguration {
private
static
final
Logger log = LoggerFactory.getLogger(DruidConfiguration.
class
);
@Bean
public
ServletRegistrationBean druidServlet() {
log.info(
"init Druid Servlet Configuration "
);
ServletRegistrationBean servletRegistrationBean =
new
ServletRegistrationBean();
servletRegistrationBean.setServlet(
new
StatViewServlet());
servletRegistrationBean.addUrlMappings(
"/druid/*"
);
Map<String, String> initParameters =
new
HashMap<>();
initParameters.put(
"loginUsername"
,
"admin"
);
// 用戶名
initParameters.put(
"loginPassword"
,
"admin"
);
// 密碼
initParameters.put(
"resetEnable"
,
"false"
);
// 禁用HTML頁面上的「Reset All」功能
initParameters.put(
"allow"
,
""
);
// IP白名單 (沒有配置或者爲空,則容許全部訪問)
//initParameters.put("deny", "192.168.20.1");// IP黑名單 (存在共同時,deny優先於allow)
servletRegistrationBean.setInitParameters(initParameters);
return
servletRegistrationBean;
}
@Bean
public
FilterRegistrationBean filterRegistrationBean() {
FilterRegistrationBean filterRegistrationBean =
new
FilterRegistrationBean();
filterRegistrationBean.setFilter(
new
WebStatFilter());
filterRegistrationBean.addUrlPatterns(
"/*"
);
filterRegistrationBean.addInitParameter(
"exclusions"
,
"*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"
);
return
filterRegistrationBean;
}
@ConfigurationProperties
(prefix =
"spring.datasource"
)
//屬性前綴
@Bean
public
DataSource druid(){
return
new
DruidDataSource();
}
}
|
13. 配置Swagger2接口文檔
(1) 引入jar依賴環境
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<
dependency
>
<
groupId
>io.springfox</
groupId
>
<
artifactId
>springfox-swagger2</
artifactId
>
<
version
>2.9.2</
version
>
</
dependency
>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<
dependency
>
<
groupId
>io.springfox</
groupId
>
<
artifactId
>springfox-swagger-ui</
artifactId
>
<
version
>2.9.2</
version
>
</
dependency
>
|
(2) 代碼配置
import
org.springframework.context.annotation.Bean;
import
org.springframework.context.annotation.Configuration;
import
org.springframework.context.annotation.Profile;
import
springfox.documentation.builders.ApiInfoBuilder;
import
springfox.documentation.builders.PathSelectors;
import
springfox.documentation.builders.RequestHandlerSelectors;
import
springfox.documentation.service.ApiInfo;
import
springfox.documentation.service.Contact;
import
springfox.documentation.spi.DocumentationType;
import
springfox.documentation.spring.web.plugins.Docket;
import
springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* @ClassName: SwaggerConfig
* @Desc: swagger文檔配置
* @Author: liuhefei
* @Date: 2019/6/11 10:29
*/
@Configuration
@EnableSwagger2
@Profile
(value = {
"dev"
,
"test"
})
//指定運行環境(開發,測試)
public
class
SwaggerConfig {
@Bean
public
Docket createRestApi() {
return
new
Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage(
"你項目的包路徑"
))
//此處必須修改
.paths(PathSelectors.any())
.build();
}
private
ApiInfo apiInfo() {
return
new
ApiInfoBuilder().title(
"Api接口接口"
)
.description(
"api接口描述信息"
)
.contact(
new
Contact(
"做者"
,
"url"
,
"email"
))
.termsOfServiceUrl(
"https://swagger.io/swagger-ui/"
)
.version(
"1.0"
)
.build();
}
}
|
14. 配置項目的名稱:
Spring.application.name=項目名稱
|
15. Http編碼相關的配置
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
spring.http.encoding.force=true
|
16. JPA相關的配置
spring.jpa.database=mysql
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
spring.jpa.database=sql_server
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.SQLServer2012Dialect
spring.jpa.hibernate.ddl-auto=none
|
17. logback日誌的配置
(1)在pom.xml文件中引入依賴
<!-- https://mvnrepository.com/artifact/ch.qos.logback/logback-classic -->
<
dependency
>
<
groupId
>ch.qos.logback</
groupId
>
<
artifactId
>logback-classic</
artifactId
>
<
version
>1.2.3</
version
>
<
scope
>test</
scope
>
</
dependency
>
|
(2)在項目的resources目錄下引入logback-spring.xml配置文件便可,內容以下:
方式一:
<?
xml
version
=
"1.0"
encoding
=
"UTF-8"
?>
<
configuration
>
<!-- 日誌根目錄-->
<
springProperty
scope
=
"context"
name
=
"LOG_HOME"
source
=
"logging.path"
defaultValue
=
"/logs/spring-boot-logback"
/>
<!-- 日誌級別 -->
<
springProperty
scope
=
"context"
name
=
"LOG_ROOT_LEVEL"
source
=
"logging.level.root"
defaultValue
=
"DEBUG"
/>
<!-- 標識這個"STDOUT" 將會添加到這個logger -->
<
springProperty
scope
=
"context"
name
=
"STDOUT"
source
=
"log.stdout"
defaultValue
=
"STDOUT"
/>
<!-- 日誌文件名稱-->
<
property
name
=
"LOG_PREFIX"
value
=
"spring-boot-logback"
/>
<!-- 日誌文件編碼-->
<
property
name
=
"LOG_CHARSET"
value
=
"UTF-8"
/>
<!-- 日誌文件路徑+日期-->
<
property
name
=
"LOG_DIR"
value
=
"${LOG_HOME}/%d{yyyyMMdd}"
/>
<!--對日誌進行格式化-->
<
property
name
=
"LOG_MSG"
value="- | [%X{requestUUID}] | [%d{yyyyMMdd HH:mm:ss.SSS}] | [%level] | [${HOSTNAME}] | [%thread] | [%logger{36}] | --> %msg|%n "/>
<!--文件大小,默認10MB-->
<
property
name
=
"MAX_FILE_SIZE"
value
=
"50MB"
/>
<!-- 配置日誌的滾動時間 ,表示只保留最近 10 天的日誌-->
<
property
name
=
"MAX_HISTORY"
value
=
"10"
/>
<!--輸出到控制檯-->
<
appender
name
=
"STDOUT"
class
=
"ch.qos.logback.core.ConsoleAppender"
>
<!-- 輸出的日誌內容格式化-->
<
layout
class
=
"ch.qos.logback.classic.PatternLayout"
>
<
pattern
>${LOG_MSG}</
pattern
>
</
layout
>
</
appender
>
<!--輸出到文件-->
<
appender
name
=
"0"
class
=
"ch.qos.logback.core.rolling.RollingFileAppender"
>
</
appender
>
<!-- 定義 ALL 日誌的輸出方式:-->
<
appender
name
=
"FILE_ALL"
class
=
"ch.qos.logback.core.rolling.RollingFileAppender"
>
<!--日誌文件路徑,日誌文件名稱-->
<
File
>${LOG_HOME}/all_${LOG_PREFIX}.log</
File
>
<!-- 設置滾動策略,當天的日誌大小超過 ${MAX_FILE_SIZE} 文件大小時候,新的內容寫入新的文件, 默認10MB -->
<
rollingPolicy
class
=
"ch.qos.logback.core.rolling.TimeBasedRollingPolicy"
>
<!--日誌文件路徑,新的 ALL 日誌文件名稱,「 i 」 是個變量 -->
<
FileNamePattern
>${LOG_DIR}/all_${LOG_PREFIX}%i.log</
FileNamePattern
>
<!-- 配置日誌的滾動時間 ,表示只保留最近 10 天的日誌-->
<
MaxHistory
>${MAX_HISTORY}</
MaxHistory
>
<!--當天的日誌大小超過 ${MAX_FILE_SIZE} 文件大小時候,新的內容寫入新的文件, 默認10MB-->
<
timeBasedFileNamingAndTriggeringPolicy
class
=
"ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"
>
<
maxFileSize
>${MAX_FILE_SIZE}</
maxFileSize
>
</
timeBasedFileNamingAndTriggeringPolicy
>
</
rollingPolicy
>
<!-- 輸出的日誌內容格式化-->
<
layout
class
=
"ch.qos.logback.classic.PatternLayout"
>
<
pattern
>${LOG_MSG}</
pattern
>
</
layout
>
</
appender
>
<!-- 定義 ERROR 日誌的輸出方式:-->
<
appender
name
=
"FILE_ERROR"
class
=
"ch.qos.logback.core.rolling.RollingFileAppender"
>
<!-- 下面爲配置只輸出error級別的日誌 -->
<
filter
class
=
"ch.qos.logback.classic.filter.LevelFilter"
>
<
level
>ERROR</
level
>
<
OnMismatch
>DENY</
OnMismatch
>
<
OnMatch
>ACCEPT</
OnMatch
>
</
filter
>
<!--日誌文件路徑,日誌文件名稱-->
<
File
>${LOG_HOME}/err_${LOG_PREFIX}.log</
File
>
<!-- 設置滾動策略,當天的日誌大小超過 ${MAX_FILE_SIZE} 文件大小時候,新的內容寫入新的文件, 默認10MB -->
<
rollingPolicy
class
=
"ch.qos.logback.core.rolling.TimeBasedRollingPolicy"
>
<!--日誌文件路徑,新的 ERR 日誌文件名稱,「 i 」 是個變量 -->
<
FileNamePattern
>${LOG_DIR}/err_${LOG_PREFIX}%i.log</
FileNamePattern
>
<!-- 配置日誌的滾動時間 ,表示只保留最近 10 天的日誌-->
<
MaxHistory
>${MAX_HISTORY}</
MaxHistory
>
<!--當天的日誌大小超過 ${MAX_FILE_SIZE} 文件大小時候,新的內容寫入新的文件, 默認10MB-->
<
timeBasedFileNamingAndTriggeringPolicy
class
=
"ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"
>
<
maxFileSize
>${MAX_FILE_SIZE}</
maxFileSize
>
</
timeBasedFileNamingAndTriggeringPolicy
>
</
rollingPolicy
>
<!-- 輸出的日誌內容格式化-->
<
layout
class
=
"ch.qos.logback.classic.PatternLayout"
>
<
Pattern
>${LOG_MSG}</
Pattern
>
</
layout
>
</
appender
>
<!-- 配置以配置包下的全部類的日誌的打印,級別是 ERROR-->
<
logger
name
=
"com.lhf.springboot"
level
=
"ERROR"
/>
<!-- ${LOG_ROOT_LEVEL} 日誌級別 -->
<
root
level
=
"${LOG_ROOT_LEVEL}"
>
<!-- 標識這個"${STDOUT}"將會添加到這個logger -->
<
appender-ref
ref
=
"${STDOUT}"
/>
<!-- FILE_ALL 日誌輸出添加到 logger -->
<
appender-ref
ref
=
"FILE_ALL"
/>
<!-- FILE_ERROR 日誌輸出添加到 logger -->
<
appender-ref
ref
=
"FILE_ERROR"
/>
</
root
>
</
configuration
>
|
方式二:
<?
xml
version
=
"1.0"
encoding
=
"UTF-8"
?>
<
configuration
>
<!--定義日誌文件的存儲地址 勿在 LogBack的配置中使用相對路徑 -->
<
property
name
=
"LOG_HOME"
value
=
"/tmp/log"
/>
<!-- 控制檯輸出 -->
<
appender
name
=
"STDOUT"
class
=
"ch.qos.logback.core.ConsoleAppender"
>
<
encoder
class
=
"ch.qos.logback.classic.encoder.PatternLayoutEncoder"
>
<
pattern
>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{30} - %msg%n</
pattern
>
</
encoder
>
</
appender
>
<!-- 按照天天生成日誌文件 -->
<
appender
name
=
"FILE"
class
=
"ch.qos.logback.core.rolling.RollingFileAppender"
>
<
rollingPolicy
class
=
"ch.qos.logback.core.rolling.TimeBasedRollingPolicy"
>
<
FileNamePattern
>${LOG_HOME}/logs/smsismp.log.%d{yyyy-MM-dd}.log</
FileNamePattern
>
<!--日誌文件保留天數 -->
<
MaxHistory
>30</
MaxHistory
>
</
rollingPolicy
>
<
encoder
class
=
"ch.qos.logback.classic.encoder.PatternLayoutEncoder"
>
<!--格式化輸出:%d表示日期,%thread表示線程名,%-5level:級別從左顯示5個字符寬度%msg:日誌消息,%n是換行符 -->
<
pattern
>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{30} - %msg%n</
pattern
>
</
encoder
>
<!--日誌文件最大的大小 -->
<
triggeringPolicy
class
=
"ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"
>
<
MaxFileSize
>10MB</
MaxFileSize
>
</
triggeringPolicy
>
</
appender
>
<!-- 日誌輸出級別 -->
<
root
level
=
"INFO"
>
<
appender-ref
ref
=
"STDOUT"
/>
<
appender-ref
ref
=
"FILE"
/>
</
root
>
<!-- 定義各個包的詳細路徑,繼承root的值 -->
<
logger
name
=
"com.lhf.springboot"
level
=
"INFO"
/>
<!-- 此值由 application.properties的spring.profiles.active=dev指定-->
<
springProfile
name
=
"dev"
>
<!--定義日誌文件的存儲地址 勿在 LogBack 的配置中使用相對路徑 -->
<
property
name
=
"LOG_HOME"
value
=
"/tmp/log"
/>
<
logger
name
=
"com.lhf.springboot"
level
=
"DEBUG"
/>
</
springProfile
>
<
springProfile
name
=
"prod"
>
<!--定義日誌文件的存儲地址 勿在 LogBack 的配置中使用相對路徑 -->
<
property
name
=
"LOG_HOME"
value
=
"/home"
/>
<
logger
name
=
"com.lhf.springboot"
level
=
"INFO"
/>
</
springProfile
>
</
configuration
>
|
18. log4j2日誌配置
(1)在pom.xml文件中引入依賴jar包,以下:
<
dependency
>
<!-- 引入log4j2依賴 -->
<
groupId
>org.springframework.boot</
groupId
>
<
artifactId
>spring-boot-starter-log4j2</
artifactId
>
</
dependency
>
|
或者
<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
<
dependency
>
<
groupId
>org.apache.logging.log4j</
groupId
>
<
artifactId
>log4j-core</
artifactId
>
<
version
>2.12.0</
version
>
</
dependency
>
|
(2)在項目的resources目錄下引入log4j2.xml配置文件,文件內容以下:
<?
xml
version
=
"1.0"
encoding
=
"UTF-8"
?>
<!--Configuration後面的status,這個用於設置log4j2自身內部的信息輸出,能夠不設置,當設置成trace時,你會看到log4j2內部各類詳細輸出-->
<!--monitorInterval:Log4j可以自動檢測修改配置 文件和從新配置自己,設置間隔秒數-->
<
configuration
monitorInterval
=
"5"
>
<!--日誌級別以及優先級排序: OFF > FATAL > ERROR > WARN > INFO > DEBUG > TRACE > ALL -->
<!--變量配置-->
<
Properties
>
<!-- 格式化輸出:%date表示日期,%thread表示線程名,%-5level:級別從左顯示5個字符寬度 %msg:日誌消息,%n是換行符-->
<!-- %logger{36} 表示 Logger 名字最長36個字符 -->
<
property
name
=
"LOG_PATTERN"
value
=
"%date{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n"
/>
<!-- 定義日誌存儲的路徑,不要配置相對路徑
<property name="FILE_PATH" value="更換爲你的日誌路徑" />
<property name="FILE_NAME" value="更換爲你的項目名" />
-->
<
property
name
=
"FILE_PATH"
value
=
"E:\code\log"
/>
<
property
name
=
"FILE_NAME"
value
=
"spring-boot-log4j2"
/>
</
Properties
>
<
appenders
>
<
console
name
=
"Console"
target
=
"SYSTEM_OUT"
>
<!--輸出日誌的格式-->
<
PatternLayout
pattern
=
"${LOG_PATTERN}"
/>
<!--控制檯只輸出level及其以上級別的信息(onMatch),其餘的直接拒絕(onMismatch)-->
<
ThresholdFilter
level
=
"info"
onMatch
=
"ACCEPT"
onMismatch
=
"DENY"
/>
</
console
>
<!--文件會打印出全部信息,這個log每次運行程序會自動清空,由append屬性決定,適合臨時測試用-->
<
File
name
=
"Filelog"
fileName
=
"${FILE_PATH}/test.log"
append
=
"false"
>
<
PatternLayout
pattern
=
"${LOG_PATTERN}"
/>
</
File
>
<!-- 這個會打印出全部的info及如下級別的信息,每次大小超過size,則這size大小的日誌會自動存入按年份-月份創建的文件夾下面並進行壓縮,做爲存檔-->
<
RollingFile
name
=
"RollingFileInfo"
fileName
=
"${FILE_PATH}/info.log"
filePattern
=
"${FILE_PATH}/${FILE_NAME}-INFO-%d{yyyy-MM-dd}_%i.log.gz"
>
<!--控制檯只輸出level及以上級別的信息(onMatch),其餘的直接拒絕(onMismatch)-->
<
ThresholdFilter
level
=
"info"
onMatch
=
"ACCEPT"
onMismatch
=
"DENY"
/>
<
PatternLayout
pattern
=
"${LOG_PATTERN}"
/>
<
Policies
>
<!--interval屬性用來指定多久滾動一次,默認是1 hour-->
<
TimeBasedTriggeringPolicy
interval
=
"1"
/>
<
SizeBasedTriggeringPolicy
size
=
"10MB"
/>
</
Policies
>
<!-- DefaultRolloverStrategy屬性如不設置,則默認爲最多同一文件夾下7個文件開始覆蓋-->
<
DefaultRolloverStrategy
max
=
"15"
/>
</
RollingFile
>
<!-- 這個會打印出全部的warn及如下級別的信息,每次大小超過size,則這size大小的日誌會自動存入按年份-月份創建的文件夾下面並進行壓縮,做爲存檔-->
<
RollingFile
name
=
"RollingFileWarn"
fileName
=
"${FILE_PATH}/warn.log"
filePattern
=
"${FILE_PATH}/${FILE_NAME}-WARN-%d{yyyy-MM-dd}_%i.log.gz"
>
<!--控制檯只輸出level及以上級別的信息(onMatch),其餘的直接拒絕(onMismatch)-->
<
ThresholdFilter
level
=
"warn"
onMatch
=
"ACCEPT"
onMismatch
=
"DENY"
/>
<
PatternLayout
pattern
=
"${LOG_PATTERN}"
/>
<
Policies
>
<!--interval屬性用來指定多久滾動一次,默認是1 hour-->
<
TimeBasedTriggeringPolicy
interval
=
"1"
/>
<
SizeBasedTriggeringPolicy
size
=
"10MB"
/>
</
Policies
>
<!-- DefaultRolloverStrategy屬性如不設置,則默認爲最多同一文件夾下7個文件開始覆蓋-->
<
DefaultRolloverStrategy
max
=
"15"
/>
</
RollingFile
>
<!-- 這個會打印出全部的error及如下級別的信息,每次大小超過size,則這size大小的日誌會自動存入按年份-月份創建的文件夾下面並進行壓縮,做爲存檔-->
<
RollingFile
name
=
"RollingFileError"
fileName
=
"${FILE_PATH}/error.log"
filePattern
=
"${FILE_PATH}/${FILE_NAME}-ERROR-%d{yyyy-MM-dd}_%i.log.gz"
>
<!--控制檯只輸出level及以上級別的信息(onMatch),其餘的直接拒絕(onMismatch)-->
<
ThresholdFilter
level
=
"error"
onMatch
=
"ACCEPT"
onMismatch
=
"DENY"
/>
<
PatternLayout
pattern
=
"${LOG_PATTERN}"
/>
<
Policies
>
<!--interval屬性用來指定多久滾動一次,默認是1 hour-->
<
TimeBasedTriggeringPolicy
interval
=
"1"
/>
<
SizeBasedTriggeringPolicy
size
=
"10MB"
/>
</
Policies
>
<!-- DefaultRolloverStrategy屬性如不設置,則默認爲最多同一文件夾下7個文件開始覆蓋-->
<
DefaultRolloverStrategy
max
=
"15"
/>
</
RollingFile
>
</
appenders
>
<!--Logger節點用來單獨指定日誌的形式,好比要爲指定包下的class指定不一樣的日誌級別等。-->
<!--而後定義loggers,只有定義了logger並引入的appender,appender纔會生效-->
<
loggers
>
<!--過濾掉spring和mybatis的一些無用的DEBUG信息-->
<
logger
name
=
"org.mybatis"
level
=
"info"
additivity
=
"false"
>
<
AppenderRef
ref
=
"Console"
/>
</
logger
>
<!--監控系統信息-->
<!--如果additivity設爲false,則 子Logger 只會在本身的appender裏輸出,而不會在 父Logger 的appender裏輸出。-->
<
Logger
name
=
"org.springframework"
level
=
"info"
additivity
=
"false"
>
<
AppenderRef
ref
=
"Console"
/>
</
Logger
>
<
root
level
=
"info"
>
<
appender-ref
ref
=
"Console"
/>
<
appender-ref
ref
=
"Filelog"
/>
<
appender-ref
ref
=
"RollingFileInfo"
/>
<
appender-ref
ref
=
"RollingFileWarn"
/>
<
appender-ref
ref
=
"RollingFileError"
/>
</
root
>
</
loggers
>
</
configuration
>
|
19. 在屬性文件中設置上傳文件的大小限制
1
2
3
|
# 設置上傳文件的大小限制
spring.servlet.multipart.max-file-size=100MB
spring.servlet.multipart.max-request-size=100MB
|
20. 設置開啓Debug模式
1
|
application.debug.enabled=true
|
21. 設置訪問URL前綴
server.servlet.context-path=/xxl-job-admin
|
22. 幾種數據源配置類型(以MySQL爲例)
1. tomcat-jdbc
引入依賴jar包:
<
dependency
>
<
groupId
>org.apache.tomcat</
groupId
>
<
artifactId
>tomcat-jdbc</
artifactId
>
<
version
>9.0.24</
version
>
</
dependency
>
|
屬性文件配置:
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?Unicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.type=org.apache.tomcat.jdbc.pool.DataSource
spring.datasource.tomcat.max-wait=10000
spring.datasource.tomcat.max-active=30
spring.datasource.tomcat.test-on-borrow=true
spring.datasource.tomcat.validation-query=SELECT 1
spring.datasource.tomcat.validation-interval=30000
|
2. spring-boot-starter-jdbc
引入依賴jar包
<
dependency
>
<
groupId
>org.springframework.boot</
groupId
>
<
artifactId
>spring-boot-starter-jdbc</
artifactId
>
</
dependency
>
|
屬性文件配置:
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.hikari.username=root
spring.datasource.hikari.password=root
spring.datasource.hikari.jdbc-url=jdbc:mysql://127.0.0.1:3306/test?autoReconnect=true&characterEncoding=UTF-8&allowMultiQueries=true&useSSL=false
spring.datasource.hikari.minimum-idle=5
spring.datasource.hikari.maximum-pool-size=15
spring.datasource.hikari.auto-commit=true
spring.datasource.hikari.idle-timeout=30002
spring.datasource.hikari.pool-name=DatebookHikariCP
spring.datasource.hikari.max-lifetime=500000
spring.datasource.hikari.connection-timeout=30001
spring.datasource.hikari.connection-test-query=SELECT 1
spring.datasource.hikari.validation-timeout=5000
|
3. druid
引入依賴jar包:
<
dependency
>
<
groupId
>com.alibaba</
groupId
>
<
artifactId
>druid</
artifactId
>
<
version
>1.1.20</
version
>
</
dependency
>
|
屬性文件配置:
# 驅動配置信息
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/lhf_springboot1?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
spring.datasource.username=root
spring.datasource.password=root
# 鏈接池的配置信息
# 初始化大小,最小,最大
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
# 配置獲取鏈接等待超時的時間
spring.datasource.maxWait=60000
# 配置間隔多久才進行一次檢測,檢測須要關閉的空閒鏈接,單位是毫秒
spring.datasource.timeBetweenEvictionRunsMillis=60000
# 配置一個鏈接在池中最小生存的時間,單位是毫秒
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
# 打開PSCache,而且指定每一個鏈接上PSCache的大小
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
# 配置監控統計攔截的filters,去掉後監控界面sql沒法統計,'wall'用於防火牆
spring.datasource.filters=stat,wall,log4j
# 經過connectProperties屬性來打開mergeSql功能;慢SQL記錄
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
|
最後可關注公衆號,一塊兒學習,天天會分享乾貨,還有學習視頻領取!