下面我們創(chuàng)建提供服務的客戶端,并向服務注冊中心注冊自己岸蜗。本文我們主要介紹服務的注冊與發(fā)現(xiàn)尉咕,所以我們不妨在服務提供方中嘗試著提供一個接口來獲取當前所有的服務信息。
首先璃岳,創(chuàng)建一個基本的Spring Boot應用年缎。命名為eureka-client,在pom.xml中铃慷,加入如下配置:
org.springframework.boot
spring-boot-starter-parent
1.5.4.RELEASE
org.springframework.cloud
spring-cloud-starter-eureka
org.springframework.boot
spring-boot-starter-web
org.springframework.cloud
spring-cloud-dependencies
Dalston.SR1
pom
import
其次单芜,實現(xiàn)/dc請求處理接口,通過DiscoveryClient對象犁柜,在日志中打印出服務實例的相關內容洲鸠。
@RestController
publicclassDcController{
@Autowired
DiscoveryClient discoveryClient;
@GetMapping("/dc")
publicStringdc(){
String services ="Services: "+ discoveryClient.getServices();
System.out.println(services);
returnservices;
}
}
最后在應用主類中通過加上@EnableDiscoveryClient注解,該注解能激活Eureka中的DiscoveryClient實現(xiàn)赁温,這樣才能實現(xiàn)Controller中對服務信息的輸出坛怪。
@EnableDiscoveryClient
@SpringBootApplication
publicclassApplication{
publicstaticvoidmain(String[] args){
newSpringApplicationBuilder(
ComputeServiceApplication.class)
.web(true).run(args);
}
}
我們在完成了服務內容的實現(xiàn)之后,再繼續(xù)對application.properties做一些配置工作股囊,具體如下:
spring.application.name=eureka-client
server.port=2001
eureka.client.serviceUrl.defaultZone=http://localhost:1001/eureka/
通過spring.application.name屬性袜匿,我們可以指定微服務的名稱后續(xù)在調用的時候只需要使用該名稱就可以進行服務的訪問。eureka.client.serviceUrl.defaultZone屬性對應服務注冊中心的配置內容稚疹,指定服務注冊中心的位置居灯。為了在本機上測試區(qū)分服務提供方和服務注冊中心,使用server.port屬性設置不同的端口内狗。
當然怪嫌,我們也可以通過直接訪問eureka-client服務提供的/dc接口來獲取當前的服務清單
1Services: [eureka-client]
其中,方括號中的eureka-client就是通過Spring Cloud定義的DiscoveryClient接口在eureka的實現(xiàn)中獲取到的所有服務清單柳沙。由于Spring Cloud在服務發(fā)現(xiàn)這一層做了非常好的抽象岩灭,所以,對于上面的程序赂鲤,我們可以無縫的從eureka的服務治理體系切換到consul的服務治理體系中區(qū)噪径。
從現(xiàn)在開始,我這邊會將近期研發(fā)的springcloud微服務云架構的搭建過程和精髓記錄下來数初,幫助更多有興趣研發(fā)spring cloud框架的朋友找爱,希望可以幫助更多的好學者。大家來一起探討spring cloud架構的搭建過程及如何運用于企業(yè)項目泡孩。源碼來源