1. 程式人生 > >spring cloud: 升級到spring boot 2.x/Finchley.RELEASE遇到的坑

spring cloud: 升級到spring boot 2.x/Finchley.RELEASE遇到的坑

spring boot2.x已經出來好一陣了,而且spring cloud 的最新Release版本Finchley.RELEASE,預設整合的就是spring boot 2.x,這幾天將一箇舊專案嘗試著從低版本升級到 2.x,踩坑無數,記錄一下:

一、gradle的問題

spring boot 2.x 要求gradle版本不能太舊,先把gradle升級到4.6版本,然後編譯,各種問題,到gradle官網上查了下,build.gradle有幾個小地方要調整

1.1 java-libary 的專案

即:純工具包這種公用jar,plugins{}必須放在第1行(有buildscript的除外),類似:

plugins {
    id 'java-library'
}

然後按官網的教程,compile最好換成implementation

dependencies {
    implementation(
            ...
    )
}

1.2 常規java專案(指帶容器能獨立執行的專案)

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.

編譯時,可以加引數:--warning-mode=none 禁止掉,即類似:

gradle build --warning-mode=none -x test

二、依賴jar包版本的問題

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',

這二項必須指定版本號,否則編譯不過。(應該最新的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裡無法通過配置關閉,只能寫程式碼調整:

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都允許訪問(如果是暴露在外網的服務,請慎用) 

六、各類actuator監控endpoint的路徑變化

spring boot 2.x 裡,actuator的endpoint預設路徑變成/actuator開頭,如果要使用以前的風格,放在/根下,可以在applicatino.yml裡參考下面的配置:

management:
  ...
  endpoints:
    web:
      base-path: /
      exposure:
        include: "*"

 另外/health節點,預設情況下,只能輸出很少的資訊,詳細資訊,需要通過配置開啟

management:
  ...
  endpoint:
    health:
      show-details: always
  ...

七、${spring.cloud.client.ipAddress} 無法識別

spring cloud 2.x裡,${spring.cloud.client.ipAddress} 這個寫法不識別,一啟動就會報錯,嘗試了多次,無意發現,把A改成小寫,居然可以了:

spring:
 ...
  application:
    name: sr-menu-service:${spring.cloud.client.ipaddress}

感覺這應該是個bug,新版本里估計會修復。

八、MetricWriter、SystemPublicMetrics類找不到的問題

spring boot 2.x裡metrics預設換成了micrometer,原來的MetricWriter之類的全乾掉了,詳情參考官網文件

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佔用的記憶體(包括heap + noheap),如果只想看heap區(即:堆上的記憶體),可以用

http://localhost:8001/metrics/jvm.memory.used?tag=area:heap

同時在grafana裡也能看到效果:

檢視原圖

注:目前statsd裡的字首無法修改,程式碼寫死的statsd

如果一臺機器上部署多個spring cloud 微服務,grafana裡就分不出來了(個人估計以後會改進)。

另外,如果希望通過程式碼獲取這些metrics裡具體指標值,可以參考下面的程式碼:

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過時的問題

WebMvcConfigurerAdapter這個類在最新的spring boot裡已經被標識為過時,正常用法參考以下:

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("測試服務")
                .contact(new Contact("菩提樹下的楊過", "http://yjmyzz.cnblogs.com/", "[email protected]"))
                .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