Spring Cloud Config as Client

首先引入spring-cloud-starter-config和dependencyManagement,全文POM如下:

<?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>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.4.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.sc</groupId>
	<artifactId>config-client</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>config-client</name>
	<description>Demo project for Spring Boot of Spring Cloud Config Client</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-config</artifactId>
			<version>2.0.2.RELEASE</version>
		</dependency>
	</dependencies>

	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>org.springframework.cloud</groupId>
				<artifactId>spring-cloud-dependencies</artifactId>
				<version>Finchley.SR2</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

在resources目錄下新建bootstrap.properties文件,裏面寫入上一篇文章config-server的信息:

#對應git倉庫目錄下的配置文件應用名稱
spring.cloud.config.name=didispace

#對應git倉庫目錄下的配置文件profile名稱
spring.cloud.config.profile=prod

#對應git倉庫目錄下的branch
spring.cloud.config.label=config-label-test
#spring.cloud.config.label=master

#對應config-server的url
spring.cloud.config.uri=http://localhost:7001/

同時,application.properties註明啓動端口,以及應用名稱

server.port=7002
spring.application.name=config-client

新建ConfigController,通過@Value("${form}")獲取配置"form"的值,或者通過注入org.springframework.core.env.Environment獲取"form"的值

package com.sc.configclient.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RefreshScope
@RestController
public class ConfigController {

    @Value("${from}")
    private String from;

    @GetMapping("/fromValue")
    public String from() {
        return this.from + "\n";
    }

    @Autowired
    private Environment environment;

    @GetMapping("/fromEnv")
    public String fromEnv() {
        return environment.getProperty("from", "undefined") + "\n";
    }
}

運行後,會顯示:

  • Fetching config from server at : http://localhost:7001/
  • Located environment: name=didispace, profiles=[prod], label=config-label-test, version=96e64f4e57c93739a5f92fa361830e60a92e620f, state=null
  • Located property source: CompositePropertySource {name='configService', propertySources=[MapPropertySource {name='configClient'}, MapPropertySource {name='https://github.com/stringhuang/SpringCloud-Learning.git/spring_cloud_in_action/config-repo/didispace-prod.properties'}, MapPropertySource {name='https://github.com/stringhuang/SpringCloud-Learning.git/spring_cloud_in_action/config-repo/didispace.properties'}]}

調用結果顯示:

RdeMacBook-Pro:config-client r$ curl http://127.0.0.1:7002/fromEnv
git-prod-2.0
RdeMacBook-Pro:config-client r$ curl http://127.0.0.1:7002/fromValue
git-prod-2.0
RdeMacBook-Pro:config-client r$ 

注意,Controller中的修飾符org.springframework.cloud.context.config.annotation.RefreshScope,是當配置屬性不存在時抑制拋出異常。

比如,去掉註解@RefreshScope,獲取配置“nonExist“,程序啓動的時候會報錯如下:Could not resolve placeholder 'nonExist' in value "${nonExist}"

//@RefreshScope
@RestController
public class ConfigController {

    @Value("${nonExist}")
    private String nonExist;

    @GetMapping("/nonExist")
    public String nonExist() {
        return this.nonExist + "\n";
    }
}

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'configController': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'nonExist' in value "${nonExist}"

把註解@RefreshScope加回去,程序可以正常啓動,但是程序運行時會報錯:Could not resolve placeholder 'nonExist' in value \"${nonExist}\"

RdeMacBook-Pro:config-client r$ curl http://127.0.0.1:7002/fromValue
{"timestamp":"2019-04-08T16:55:23.330+0000","status":500,"error":"Internal Server Error","message":"Error creating bean with name 'scopedTarget.configController': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'nonExist' in value \"${nonExist}\"","path":"/fromValue"}RdeMacBook-Pro:config-client r$ curl http://127.0.0.1:7002/fromEnv
{"timestamp":"2019-04-08T16:55:39.046+0000","status":500,"error":"Internal Server Error","message":"Error creating bean with name 'scopedTarget.configController': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'nonExist' in value \"${nonExist}\"","path":"/fromEnv"}RdeMacBook-Pro:config-client r$ curl http://127.0.0.1:7002/nonExist
{"timestamp":"2019-04-08T16:55:43.749+0000","status":500,"error":"Internal Server Error","message":"Error creating bean with name 'scopedTarget.configController': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'nonExist' in value \"${nonExist}\"","path":"/nonExist"}RdeMacBook-Pro:config-client r$ 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章