Spring Cloud構建微服務架構-建立「服務提供方」

下面咱們建立提供服務的客戶端,並向服務註冊中心註冊本身。本文咱們主要介紹服務的註冊與發現,因此咱們不妨在服務提供方中嘗試着提供一個接口來獲取當前全部的服務信息。html

首先,建立一個基本的Spring Boot應用。命名爲eureka-client,在pom.xml中,加入以下配置:java

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Dalston.SR1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

其次,實現/dc請求處理接口,經過DiscoveryClient對象,在日誌中打印出服務實例的相關內容。web

@RestController
public class DcController {
@Autowired
DiscoveryClient discoveryClient;
@GetMapping("/dc")
public String dc() {
String services = "Services: " + discoveryClient.getServices();
System.out.println(services);
return services;
}
}

最後在應用主類中經過加上@EnableDiscoveryClient註解,該註解能激活Eureka中的DiscoveryClient實現,這樣才能實現Controller中對服務信息的輸出。spring

@EnableDiscoveryClient
@SpringBootApplication
public class Application {
public static void main(String[] args) {
new SpringApplicationBuilder(
ComputeServiceApplication.class)
.web(true).run(args);
}
}

咱們在完成了服務內容的實現以後,再繼續對application.properties作一些配置工做,具體以下:架構

spring.application.name=eureka-client
server.port=2001
eureka.client.serviceUrl.defaultZone=http://localhost:1001/eureka/

經過spring.application.name屬性,咱們能夠指定微服務的名稱後續在調用的時候只須要使用該名稱就能夠進行服務的訪問。eureka.client.serviceUrl.defaultZone屬性對應服務註冊中心的配置內容,指定服務註冊中心的位置。爲了在本機上測試區分服務提供方和服務註冊中心,使用server.port屬性設置不一樣的端口。app

固然,咱們也能夠經過直接訪問eureka-client服務提供的/dc接口來獲取當前的服務清單框架

1.Services: [eureka-client]spring-boot

其中,方括號中的eureka-client就是經過Spring Cloud定義的DiscoveryClient接口在eureka的實現中獲取到的全部服務清單。因爲Spring Cloud在服務發現這一層作了很是好的抽象,因此,對於上面的程序,咱們能夠無縫的從eureka的服務治理體系切換到consul的服務治理體系中區。微服務

從如今開始,我這邊會將近期研發的springcloud微服務雲架構的搭建過程和精髓記錄下來,幫助更多有興趣研發spring cloud框架的朋友,但願能夠幫助更多的好學者。你們來一塊兒探討spring cloud架構的搭建過程及如何運用於企業項目。源碼來源測試

相關文章
相關標籤/搜索