下面我們創(chuàng)建提供服務的客戶端,并向服務注冊中心注冊自己。本文我們主要介紹服務的注冊與發(fā)現(xiàn),所以我們不妨在服務提供方中嘗試著提供一個接口來獲取當前所有的服務信息。
首先哗脖,創(chuàng)建一個基本的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 />
</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>
其次丘损,實現(xiàn)/dc請求處理接口,通過DiscoveryClient對象工扎,在日志中打印出服務實例的相關(guān)內(nèi)容徘钥。
<pre>
@RestController
public class DcController {
@Autowired
DiscoveryClient discoveryClient;
@GetMapping("/dc")
public String dc() {
String services = "Services: " + discoveryClient.getServices();
System.out.println(services);
return services;
}
}</pre>
最后在應用主類中通過加上@EnableDiscoveryClient注解,該注解能激活Eureka中的DiscoveryClient實現(xiàn)肢娘,這樣才能實現(xiàn)Controller中對服務信息的輸出呈础。
<pre>
@EnableDiscoveryClient
@SpringBootApplication
public class Application {
public static void main(String[] args) {
new SpringApplicationBuilder(Application.class).web(true).run(args);
}
}
</pre>
我們在完成了服務內(nèi)容的實現(xiàn)之后,再繼續(xù)對application.properties做一些配置工作橱健,具體如下:
<pre>
spring.application.name=eureka-client
server.port=2001
eureka.client.serviceUrl.defaultZone=http://localhost:1001/eureka/
</pre>
通過spring.application.name
屬性而钞,我們可以指定微服務的名稱后續(xù)在調(diào)用的時候只需要使用該名稱就可以進行服務的訪問。eureka.client.serviceUrl.defaultZone
屬性對應服務注冊中心的配置內(nèi)容拘荡,指定服務注冊中心的位置臼节。為了在本機上測試區(qū)分服務提供方和服務注冊中心,使用server.port
屬性設(shè)置不同的端口珊皿。
啟動該工程后网缝,再次訪問:http://localhost:1001/◇ǎ可以如下圖內(nèi)容粉臊,我們定義的服務被成功注冊了。
當然驶兜,我們也可以通過直接訪問eureka-client
服務提供的/dc
接口來獲取當前的服務清單扼仲,只需要訪問:http://localhost:2001/dc,我們可以得到如下輸出返回:
<pre>
Services: [eureka-client]
</pre>
其中抄淑,方括號中的eureka-client就是通過Spring Cloud定義的DiscoveryClient接口在eureka的實現(xiàn)中獲取到的所有服務清單屠凶。由于Spring Cloud在服務發(fā)現(xiàn)這一層做了非常好的抽象,所以肆资,對于上面的程序矗愧,我們可以無縫的從eureka的服務治理體系切換到consul的服務治理體系中區(qū)。
到此迅耘,服務的注冊中心已經(jīng)建好贱枣,請關(guān)注下篇:SpringCloud:服務的消費者eureka-consumer
參考資料:Spring Cloud基礎(chǔ)教程监署,謝謝DIDI大神