spring cloud升級(jí)到spring boot 2.x/Finchley.RELEASE遇到的坑
spring boot2.x已經(jīng)出來(lái)好一陣了,而且spring cloud 的最新Release版本Finchley.RELEASE,默認(rèn)集成的就是spring boot 2.x,這幾天將一個(gè)舊項(xiàng)目嘗試著從低版本升級(jí)到 2.x,踩坑無(wú)數(shù),記錄一下:
顯著變化:
- 與 Spring Boot 2.0.x 兼容
- 不支持 Spring Boot 1.5.x
- 最低要求 Java 8
- 新增 Spring Cloud Function 和 Spring Cloud Gateway
一、gradle的問(wèn)題
spring boot 2.x 要求gradle版本不能太舊,先把gradle升級(jí)到4.6版本,然后編譯,各種問(wèn)題,到gradle官網(wǎng)上查了下,build.gradle有幾個(gè)小地方要調(diào)整
1.1 java-libary 的項(xiàng)目
即:純工具包這種公用jar,plugins{}必須放在第1行(有buildscript的除外),類(lèi)似:
plugins {
id 'java-library'
}
然后按官網(wǎng)的教程,compile最好換成implementation
dependencies {
implementation(
...
)
}
1.2 常規(guī)java項(xiàng)目(指帶容器能獨(dú)立運(yùn)行的項(xiàng)目)
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'
}
}<br>...
另外,gradle 高版本編譯時(shí),總會(huì)有一行討厭的提示:
Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0.
編譯時(shí),可以加參數(shù):--warning-mode=none 禁止掉,即類(lèi)似:
gradle build --warning-mode=none -x test
二、依賴(lài)jar包版本的問(wèn)題
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',
這二項(xiàng)必須指定版本號(hào),否則編譯不過(guò)。(應(yīng)該最新的2.x版本的jar包,還沒(méi)上傳到中央倉(cāng)庫(kù),無(wú)法自動(dòng)識(shí)別依賴(lài)),另外pagehelper這個(gè)常用的分頁(yè)組件,也建議按上面的版本來(lái)配置,否則運(yùn)行時(shí),可能會(huì)報(bào)錯(cuò)。
三、log4j/log4j2的問(wèn)題
升級(jí)到spring boot 2.x后,不管是配置log4j還是log4j2,運(yùn)行時(shí)總是報(bào)堆棧溢出的error,換成logback后,啟動(dòng)正常,建議大家盡量采用默認(rèn)的logback,依賴(lài)項(xiàng)的配置參考上面的。
四、DataSourceBuilder類(lèi)找不到的問(wèn)題
spring boot 2.x把這個(gè)類(lèi)換了package,所以找不到了,詳情見(jiàn):
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
同時(shí)修改代碼import新的package: org.springframework.boot.jdbc.DataSourceBuilder
五、安全性的問(wèn)題
spring boot 2.x加強(qiáng)了安全性,不管訪(fǎng)問(wèn)什么rest url,默認(rèn)都要求登錄,在application.yml里無(wú)法通過(guò)配置關(guān)閉,只能寫(xiě)代碼調(diào)整:
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();
}
}
這樣,默認(rèn)所有url都允許訪(fǎng)問(wèn)(如果是暴露在外網(wǎng)的服務(wù),請(qǐng)慎用)
六、各類(lèi)actuator監(jiān)控endpoint的路徑變化
spring boot 2.x 里,actuator的endpoint默認(rèn)路徑變成/actuator開(kāi)頭,如果要使用以前的風(fēng)格,放在/根下,可以在applicatino.yml里參考下面的配置:
management:
...
endpoints:
web:
base-path: /
exposure:
include: "*"
另外/health節(jié)點(diǎn),默認(rèn)情況下,只能輸出很少的信息,詳細(xì)信息,需要通過(guò)配置打開(kāi)
management: ... endpoint: health: show-details: always ...
七、${spring.cloud.client.ipAddress} 無(wú)法識(shí)別
spring cloud 2.x里,${spring.cloud.client.ipAddress} 這個(gè)寫(xiě)法不識(shí)別,一啟動(dòng)就會(huì)報(bào)錯(cuò),嘗試了多次,無(wú)意發(fā)現(xiàn),把A改成小寫(xiě),居然可以了:
spring:
...
application:
name: sr-menu-service:${spring.cloud.client.ipaddress}
感覺(jué)這應(yīng)該是個(gè)bug,新版本里估計(jì)會(huì)修復(fù)。
八、MetricWriter、SystemPublicMetrics類(lèi)找不到的問(wèn)題
spring boot 2.x里metrics默認(rèn)換成了micrometer,原來(lái)的MetricWriter之類(lèi)的全干掉了,詳情參考官網(wǎng)文檔
management:
metrics:
export:
statsd:
host: 10.0.*.*
port: 8125
flavor: etsy
上面的配置是啟用statsd,然后跑起來(lái)就能看到效果,見(jiàn)下圖

但是與spring boot 1.x相比,并不會(huì)直接輸出具體值,要看具體值,可以用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

同時(shí)在grafana里也能看到效果:

注:目前statsd里的前綴無(wú)法修改,代碼寫(xiě)死的statsd

如果一臺(tái)機(jī)器上部署多個(gè)spring cloud 微服務(wù),grafana里就分不出來(lái)了(個(gè)人估計(jì)以后會(huì)改進(jìn))。
另外,如果希望通過(guò)代碼獲取這些metrics里具體指標(biāo)值,可以參考下面的代碼:
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<Statistic, Double> stats = getSamples(meter);
logger.info(String.format(METRIC_MSG_FORMAT, metric, stats.get(Statistic.VALUE).longValue()));
}
private Map<Statistic, Double> getSamples(Meter meter) {
Map<Statistic, Double> samples = new LinkedHashMap<>();
mergeMeasurements(samples, meter);
return samples;
}
private void mergeMeasurements(Map<Statistic, Double> samples, Meter meter) {
meter.measure().forEach((measurement) -> samples.merge(measurement.getStatistic(),
measurement.getValue(), mergeFunction(measurement.getStatistic())));
}
private BiFunction<Double, Double, Double> mergeFunction(Statistic statistic) {
return Statistic.MAX.equals(statistic) ? Double::max : Double::sum;
}
}
九、swagger里WebMvcConfigurerAdapter過(guò)時(shí)的問(wèn)題
WebMvcConfigurerAdapter這個(gè)類(lèi)在最新的spring boot里已經(jīng)被標(biāo)識(shí)為過(guò)時(shí),正常用法參考以下:
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("測(cè)試服務(wù)")
.contact(new Contact("菩提樹(shù)下的楊過(guò)", "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/
https://github.com/pagehelper/pagehelper-spring-boot
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
mybatis-plus用insertBatchSomeColumn方法批量新增指定字段
mybatisPlus底層的新增方法是一條一條的新增的,下面這篇文章主要給大家介紹了關(guān)于mybatis-plus用insertBatchSomeColumn方法批量新增指定字段的相關(guān)資料,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-05-05
spring boot中的條件裝配bean的實(shí)現(xiàn)
這篇文章主要介紹了spring boot中的條件裝配bean的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-12-12
Mybatis結(jié)果集自動(dòng)映射的實(shí)例代碼
在使用Mybatis時(shí),有的時(shí)候我們可以不用定義resultMap,而是直接在<select>語(yǔ)句上指定resultType。這個(gè)時(shí)候其實(shí)就用到了Mybatis的結(jié)果集自動(dòng)映射,下面通過(guò)本文給大家分享Mybatis結(jié)果集自動(dòng)映射的實(shí)例代碼,一起看看吧2017-02-02
MyBatis解決Update動(dòng)態(tài)SQL逗號(hào)的問(wèn)題
這篇文章主要介紹了MyBatis解決Update動(dòng)態(tài)SQL逗號(hào)的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-01-01
詳解Java的內(nèi)置異常以及創(chuàng)建自定義異常子類(lèi)的方法
這篇文章主要介紹了詳解Java的內(nèi)置異常以及創(chuàng)建自定義異常子類(lèi)的方法,是Java入門(mén)學(xué)習(xí)中的基礎(chǔ)知識(shí),需要的朋友可以參考下2015-09-09
MyBatis中的SQL映射文件如何配置參數(shù)映射和使用方法
MyBatis 是一種開(kāi)源的 Java 持久化框架,它可以自動(dòng)將數(shù)據(jù)庫(kù)中的數(shù)據(jù)映射到 Java 對(duì)象中,并且使得 Java 對(duì)象可以非常方便地存儲(chǔ)到數(shù)據(jù)庫(kù)中,本文將介紹 MyBatis 中 SQL 映射文件的參數(shù)映射配置和使用方法,需要的朋友可以參考下2023-07-07
一天時(shí)間用Java寫(xiě)了個(gè)飛機(jī)大戰(zhàn)游戲,朋友直呼高手
前兩天我發(fā)現(xiàn)論壇有兩篇飛機(jī)大戰(zhàn)的文章異常火爆,但都是python寫(xiě)的,竟然不是我大Java,說(shuō)實(shí)話(huà)作為老java選手,我心里是有那么一些失落的,今天特地整理了這篇文章,需要的朋友可以參考下2021-05-05
Spring中的FactoryBean實(shí)現(xiàn)原理詳解
這篇文章主要介紹了Spring中的FactoryBean實(shí)現(xiàn)原理詳解,spring中有兩種類(lèi)型的Bean,一種是普通的JavaBean,另一種就是工廠(chǎng)Bean(FactoryBean),這兩種Bean都受Spring的IoC容器管理,但它們之間卻有一些區(qū)別,需要的朋友可以參考下2024-02-02
一文詳解Spring中ResponseEntity包裝器的使用
在?Spring?中,ResponseEntity?是?HTTP?響應(yīng)的包裝器,這篇文章主要為大家詳細(xì)介紹了ResponseEntity包裝器的使用,感興趣的可以了解一下2025-02-02
SpringSecurity的安全過(guò)濾器鏈功能詳解
本文介紹了如何配置SpringSecurity的安全過(guò)濾器鏈,包括定義URL路徑的訪(fǎng)問(wèn)權(quán)限、用戶(hù)認(rèn)證和授權(quán)配置、自定義CSRF過(guò)濾器等內(nèi)容,通過(guò)這些配置,可以實(shí)現(xiàn)對(duì)不同URL路徑的訪(fǎng)問(wèn)控制以及用戶(hù)的登錄、注銷(xiāo)等功能,感興趣的朋友一起看看吧2025-03-03

