Spring Cloud構(gòu)建微服務(wù)架構(gòu)-創(chuàng)建“服務(wù)提供方”

下面我們創(chuàng)建提供服務(wù)的客戶端,并向服務(wù)注冊中心注冊自己。本文我們主要介紹服務(wù)的注冊與發(fā)現(xiàn),所以我們不妨在服務(wù)提供方中嘗試著提供一個(gè)接口來獲取當(dāng)前所有的服務(wù)信息。

首先,創(chuàng)建一個(gè)基本的Spring Boot應(yīng)用。命名為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>

其次,實(shí)現(xiàn)/dc請求處理接口,通過DiscoveryClient對象,在日志中打印出服務(wù)實(shí)例的相關(guān)內(nèi)容。

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

最后在應(yīng)用主類中通過加上@EnableDiscoveryClient注解,該注解能激活Eureka中的DiscoveryClient實(shí)現(xiàn),這樣才能實(shí)現(xiàn)Controller中對服務(wù)信息的輸出。

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

我們在完成了服務(wù)內(nèi)容的實(shí)現(xiàn)之后,再繼續(xù)對application.properties做一些配置工作,具體如下:

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

通過spring.application.name屬性,我們可以指定微服務(wù)的名稱后續(xù)在調(diào)用的時(shí)候只需要使用該名稱就可以進(jìn)行服務(wù)的訪問。eureka.client.serviceUrl.defaultZone屬性對應(yīng)服務(wù)注冊中心的配置內(nèi)容,指定服務(wù)注冊中心的位置。為了在本機(jī)上測試區(qū)分服務(wù)提供方和服務(wù)注冊中心,使用server.port屬性設(shè)置不同的端口。

當(dāng)然,我們也可以通過直接訪問eureka-client服務(wù)提供的/dc接口來獲取當(dāng)前的服務(wù)清單

中,方括號中的eureka-client就是通過Spring Cloud定義的DiscoveryClient接口在eureka的實(shí)現(xiàn)中獲取到的所有服務(wù)清單。由于Spring Cloud在服務(wù)發(fā)現(xiàn)這一層做了非常好的抽象,所以,對于上面的程序,我們可以無縫的從eureka的服務(wù)治理體系切換到consul的服務(wù)治理體系中區(qū)。

image.png

從現(xiàn)在開始,我這邊會將近期研發(fā)的springcloud微服務(wù)云架構(gòu)的搭建過程和精髓記錄下來,幫助更多有興趣研發(fā)spring cloud框架的朋友,希望可以幫助更多的好學(xué)者。大家來一起探討spring cloud架構(gòu)的搭建過程及如何運(yùn)用于企業(yè)項(xiàng)目。

完整項(xiàng)目的源碼來源 技術(shù)支持1791743380

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容