標籤:朋友 ati int ffffff images service stc 不同的 name
下面我們建立提供服務的用戶端,並向服務註冊中心註冊自己。本文我們主要介紹服務的註冊與發現,所以我們不妨在服務提供者中嘗試著提供一個介面來擷取當前所有的服務資訊。
首先,建立一個基本的Spring Boot應用。命名為eureka-client,在pom.xml中,加入如下配置:
<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對象,在日誌中列印出服務執行個體的相關內容。
@RestControllerpublic class DcController {@AutowiredDiscoveryClient discoveryClient;@GetMapping("/dc")public String dc() {String services = "Services: " + discoveryClient.getServices();System.out.println(services);return services;}}
最後在應用主類中通過加上@EnableDiscoveryClient註解,該註解能啟用Eureka中的DiscoveryClient實現,這樣才能實現Controller中對服務資訊的輸出。
@EnableDiscoveryClient@SpringBootApplicationpublic class Application {public static void main(String[] args) {new SpringApplicationBuilder(ComputeServiceApplication.class).web(true).run(args);}}
我們在完成了服務內容的實現之後,再繼續對application.properties做一些配置工作,具體如下:
spring.application.name=eureka-clientserver.port=2001eureka.client.serviceUrl.defaultZone=http://localhost:1001/eureka/
通過spring.application.name屬性,我們可以指定微服務的名稱後續在調用的時候只需要使用該名稱就可以進行服務的訪問。eureka.client.serviceUrl.defaultZone屬性對應服務註冊中心的配置內容,指定服務註冊中心的位置。為了在本機上測試區分服務提供者和服務註冊中心,使用server.port屬性設定不同的連接埠。
當然,我們也可以通過直接存取eureka-client服務提供的/dc介面來擷取當前的服務資訊清單
1
Services: [eureka-client]
其中,方括弧中的eureka-client就是通過Spring Cloud定義的DiscoveryClient介面在eureka的實現中擷取到的所有服務資訊清單。由於Spring Cloud在服務發現這一層做了非常好的抽象,所以,對於上面的程式,我們可以無縫的從eureka的服務治理體系切換到consul的服務治理體系中區。
從現在開始,我這邊會將近期研發的springcloud微服務雲架構的搭建過程和精髓記錄下來,協助更多有興趣研發spring cloud架構的朋友,希望可以協助更多的好學者。大家來一起探討spring cloud架構的搭建過程及如何運用於企業專案。
Spring Cloud構建微服務架構-建立“服務提供者”