Spring Cloud構建微服務架構-建立“服務提供者”

來源:互聯網
上載者:User

標籤:spring   Spring Cloud   Spring Boot   config   

下面我們建立提供服務的用戶端,並向服務註冊中心註冊自己。本文我們主要介紹服務的註冊與發現,所以我們不妨在服務提供者中嘗試著提供一個介面來擷取當前所有的服務資訊。

首先,建立一個基本的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介面來擷取當前的服務資訊清單
Services: [eureka-client]
其中,方括弧中的eureka-client就是通過Spring Cloud定義的DiscoveryClient介面在eureka的實現中擷取到的所有服務資訊清單。由於Spring Cloud在服務發現這一層做了非常好的抽象,所以,對於上面的程式,我們可以無縫的從eureka的服務治理體系切換到consul的服務治理體系中區。

從現在開始,我這邊會將近期研發的springcloud微服務雲架構的搭建過程和精髓記錄下來,協助更多有興趣研發spring cloud架構的朋友,希望可以協助更多的好學者。大家來一起探討spring cloud架構的搭建過程及如何運用於企業專案。

Spring Cloud構建微服務架構-建立“服務提供者”

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.