還在用絲襪哥(Swagger)做API文檔?快來看看這款幫你減少百分之九十工作量的開源工具!
1092
2025-04-03
spring boot2.x已經(jīng)出來好一陣了,而且spring cloud 的最新Release版本Finchley.RELEASE,默認集成的就是spring boot 2.x,這幾天將一個舊項目嘗試著從低版本升級到 2.x,踩坑無數(shù),記錄一下:
一、gradle的問題
spring boot 2.x 要求gradle版本不能太舊,先把gradle升級到4.6版本,然后編譯,各種問題,到gradle官網(wǎng)上查了下,build.gradle有幾個小地方要調(diào)整
1.1?java-libary 的項目
即:純工具包這種公用jar,plugins{}必須放在第1行(有buildscript的除外),類似:
1
2
3
plugins {
id?'java-library'
}
然后按官網(wǎng)的教程,compile最好換成implementation
1
2
3
4
5
dependencies {
implementation(
...
)
}
1.2?常規(guī)java項目(指帶容器能獨立運行的項目)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
buildscript {
ext {
springBootVersion =?'2.0.1.RELEASE'
}
repositories {
maven {
url?"http://maven.aliyun.com/nexus/content/groups/public/"
}
...
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin:?'java'
apply plugin:?'org.springframework.boot'
apply plugin:?'io.spring.dependency-Management'
dependencyManagement {
imports {
mavenBom?'org.springframework.cloud:spring-cloud-dependencies:Finchley.RELEASE'
}
}
...
另外,gradle 高版本編譯時,總會有一行討厭的提示:
Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0.
編譯時,可以加參數(shù):--warning-mode=none?禁止掉,即類似:
gradle build --warning-mode=none -x test
二、依賴jar包版本的問題
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
dependencies {
...
implementation(
...
'org.springframework.cloud:spring-cloud-starter-consul-discovery',
'org.springframework.cloud:spring-cloud-starter-consul-config',
'org.springframework.cloud:spring-cloud-starter-bus-kafka',
'org.springframework.cloud:spring-cloud-starter-sleuth',
'org.springframework.cloud:spring-cloud-sleuth-stream:1.3.4.RELEASE',
'org.springframework.cloud:spring-cloud-starter-hystrix:1.4.4.RELEASE',
'org.springframework.cloud:spring-cloud-netflix-hystrix-stream',
'org.springframework.boot:spring-boot-starter-actuator',
'org.springframework.boot:spring-boot-starter-undertow',
'org.springframework.boot:spring-boot-starter-mail',
'org.springframework.boot:spring-boot-starter-jdbc',
'org.springframework.boot:spring-boot-starter-security',
'org.slf4j:slf4j-api:1.7.25',
'ch.qos.logback:logback-core:1.2.3',
'org.thymeleaf:thymeleaf-spring5:3.0.9.RELEASE',
'org.mybatis.spring.boot:mybatis-spring-boot-starter:1.3.1',
'tk.mybatis:mapper-spring-boot-starter:1.2.4',
'com.github.pagehelper:pagehelper-spring-boot-starter:1.2.3'
)
implementation('com.alibaba:druid:1.1.9') {
exclude group:?"com.alibaba", module:?"jconsole"
exclude group:?"com.alibaba", module:?"tools"
}
implementation('org.springframework.boot:spring-boot-starter-web') {
exclude module:?"spring-boot-starter-tomcat"
exclude module:?"spring-boot-starter-jetty"
}
testCompile?'org.springframework.boot:spring-boot-starter-test'
}
其中
'org.springframework.cloud:spring-cloud-sleuth-stream:1.3.4.RELEASE',
'org.springframework.cloud:spring-cloud-starter-hystrix:1.4.4.RELEASE',
這二項必須指定版本號,否則編譯不過。(應(yīng)該最新的2.x版本的jar包,還沒上傳到中央倉庫,無法自動識別依賴),另外pagehelper這個常用的分頁組件,也建議按上面的版本來配置,否則運行時,可能會報錯。
三、log4j/log4j2的問題
升級到spring boot 2.x后,不管是配置log4j還是log4j2,運行時總是報堆棧溢出的error,換成logback后,啟動正常,建議大家盡量采用默認的logback,依賴項的配置參考上面的。
四、DataSourceBuilder類找不到的問題
spring boot 2.x把這個類換了package,所以找不到了,詳情見:
https://stackoverflow.com/questions/50011577/spring-boot-2-0-0-datasourcebuilder-not-found-in-autoconfigure-jar
https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/jdbc/DataSourceBuilder.html
解決辦法就是引用:?org.springframework.boot:spring-boot-starter-jdbc
同時修改代碼import新的package: org.springframework.boot.jdbc.DataSourceBuilder
五、安全性的問題
spring boot 2.x加強了安全性,不管訪問什么rest url,默認都要求登錄,在application.yml里無法通過配置關(guān)閉,只能寫代碼調(diào)整:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import?org.springframework.context.annotation.Configuration;
import?org.springframework.security.config.annotation.web.builders.HttpSecurity;
import?org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import?org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
public?class?SecurityConfiguration?extends?WebSecurityConfigurerAdapter {
@Override
protected?void?configure(HttpSecurity http)?throws?Exception {
http.authorizeRequests()
.anyRequest()
.permitAll()
.and()
.csrf()
.disable();
}
}
這樣,默認所有url都允許訪問(如果是暴露在外網(wǎng)的服務(wù),請慎用)
六、各類actuator監(jiān)控endpoint的路徑變化
spring boot 2.x 里,actuator的endpoint默認路徑變成/actuator開頭,如果要使用以前的風(fēng)格,放在/根下,可以在applicatino.yml里參考下面的配置:
1
2
3
4
5
6
7
management:
...
endpoints:
web:
base-path: /
exposure:
include:?"*"
另外/health節(jié)點,默認情況下,只能輸出很少的信息,詳細信息,需要通過配置打開
1
2
3
4
5
6
management:
...
endpoint:
health:
show-details: always
...
七、${spring.cloud.client.ipAddress} 無法識別
spring cloud 2.x里,${spring.cloud.client.ipAddress} 這個寫法不識別,一啟動就會報錯,嘗試了多次,無意發(fā)現(xiàn),把A改成小寫,居然可以了:
1
2
3
4
spring:
...
application:
name: sr-menu-service:${spring.cloud.client.ipaddress}
感覺這應(yīng)該是個bug,新版本里估計會修復(fù)。
八、MetricWriter、SystemPublicMetrics類找不到的問題
spring boot 2.x里metrics默認換成了micrometer,原來的MetricWriter之類的全干掉了,詳情參考官網(wǎng)文檔
1
2
3
4
5
6
7
management:
metrics:
export:
statsd:
host:?10.0.*.*
port:?8125
flavor: etsy
上面的配置是啟用statsd,然后跑起來就能看到效果,見下圖
但是與spring boot 1.x相比,并不會直接輸出具體值,要看具體值,可以用?http://localhost:8001/metrics/jvm.memory.used
這其中的VALUE中是jvm占用的內(nèi)存(包括heap + noheap),如果只想看heap區(qū)(即:堆上的內(nèi)存),可以用
http://localhost:8001/metrics/jvm.memory.used?tag=area:heap
同時在grafana里也能看到效果:
注:目前statsd里的前綴無法修改,代碼寫死的statsd
如果一臺機器上部署多個spring cloud 微服務(wù),grafana里就分不出來了(個人估計以后會改進)。
另外,如果希望通過代碼獲取這些metrics里具體指標值,可以參考下面的代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import?io.micrometer.core.instrument.Meter;
import?io.micrometer.core.instrument.MeterRegistry;
import?io.micrometer.core.instrument.Statistic;
import?org.junit.Test;
import?org.springframework.beans.factory.annotation.Autowired;
import?java.util.LinkedHashMap;
import?java.util.Map;
import?java.util.function.BiFunction;
public?class?MetricsTest?extends?BaseTest {
private?String METRIC_MSG_FORMAT =?"Metric >> %s = %d";
@Autowired
private?MeterRegistry meterRegistry;
@Test
public?void?testStatsdConfig() {
String metric =?"jvm.memory.used";
Meter meter = meterRegistry.find(metric).meter();
Map
logger.info(String.format(METRIC_MSG_FORMAT, metric, stats.get(Statistic.VALUE).longValue()));
}
private?Map
Map
mergeMeasurements(samples, meter);
return?samples;
}
private?void?mergeMeasurements(Map
meter.measure().forEach((measurement) -> samples.merge(measurement.getStatistic(),
measurement.getValue(), mergeFunction(measurement.getStatistic())));
}
private?BiFunction
return?Statistic.MAX.equals(statistic) ? Double::max : Double::sum;
}
}
九、swagger里WebMvcConfigurerAdapter過時的問題
WebMvcConfigurerAdapter這個類在最新的spring boot里已經(jīng)被標識為過時,正常用法參考以下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import?org.springframework.context.annotation.Bean;
import?org.springframework.context.annotation.Configuration;
import?org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import?org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
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;
/**
* @author yangjunming
* @date 13/10/2017
*/
@Configuration
@EnableSwagger2
public?class?SwaggerConfig?extends?WebMvcConfigurationSupport {
@Override
protected?void?addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
@Bean
public?Docket createRestApi() {
return?new?Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("sr.service.menu.controller"))
.paths(PathSelectors.any())
.build();
}
private?ApiInfo apiInfo() {
return?new?ApiInfoBuilder()
.title("menu-service online api document")
.description("測試服務(wù)")
.contact(new?Contact("菩提樹下的楊過",?"http://yjmyzz.cnblogs.com/",?"yjmyzz@126.com"))
.version("1.0.0")
.build();
}
}
附:一些參考文檔:
https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.0-Migration-Guide
https://spring.io/blog/2017/09/15/security-changes-in-spring-boot-2-0-m4
https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-Security-2.0
https://docs.spring.io/spring-boot/docs/2.0.4.RELEASE/reference/htmlsingle/#production-ready-metrics-getting-started
https://github.com/pagehelper/pagehelper-spring-boot
Spring Cloud
版權(quán)聲明:本文內(nèi)容由網(wǎng)絡(luò)用戶投稿,版權(quán)歸原作者所有,本站不擁有其著作權(quán),亦不承擔(dān)相應(yīng)法律責(zé)任。如果您發(fā)現(xiàn)本站中有涉嫌抄襲或描述失實的內(nèi)容,請聯(lián)系我們jiasou666@gmail.com 處理,核實后本網(wǎng)站將在24小時內(nèi)刪除侵權(quán)內(nèi)容。
版權(quán)聲明:本文內(nèi)容由網(wǎng)絡(luò)用戶投稿,版權(quán)歸原作者所有,本站不擁有其著作權(quán),亦不承擔(dān)相應(yīng)法律責(zé)任。如果您發(fā)現(xiàn)本站中有涉嫌抄襲或描述失實的內(nèi)容,請聯(lián)系我們jiasou666@gmail.com 處理,核實后本網(wǎng)站將在24小時內(nèi)刪除侵權(quán)內(nèi)容。