上一篇介紹了註冊中心,這一篇介紹如何把服務註冊到註冊中心。
一、創建服務提供者
我們依然使用上一篇的項目,在其中創建一個spring boot模塊,填好必要的信息,依賴需要選擇Spring Web和Eureka Discovery Client,創建完成後主要的依賴如下:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
</dependencies>
二、添加配置
在application.properties文件中添加以下配置
server.port=8770
spring.application.name=service-provider
eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/
三、提供服務
爲了方便,我們直接在啓動類添加一個提供服務的方法
@SpringBootApplication
@EnableEurekaClient
@RestController
public class ServiceProviderApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceProviderApplication.class, args);
}
@RequestMapping("/callServiceProvider")
public String callServiceProvider(@RequestParam("uid") String uid) {
return "用戶" + uid + "調用了此服務";
}
}
通過@EnableEurekaClient開啓服務註冊,而其他的寫法和在spring boot中添加一個api接口是一樣的,因爲spring cloud就是使用REST的方式對外提供服務的。
四、啓動
4.1、單節點註冊中心
先啓動單節點的註冊中心(使用的配置文件是application.properties),再啓動服務提供者,都啓動成功後,在瀏覽器訪問http://localhost:8761/,可以看到,在註冊中心已經有一個服務提供者了,而名稱就是在配置文件中spring.application.name的值
4.2、註冊中心集羣
如果使用註冊中心集羣,那麼就把eureka.client.serviceUrl.defaultZone的值改爲http://eureka-1:8761/eureka/,然後分別啓動上一篇中提到的Eureka集羣的三個節點,再啓動服務提供者,這時訪問http://eureka-1:8761/
這時可以看到SERVICE-PROVIDER服務已經在其中,再訪問http://eureka-2:8762/或者http://eureka-3:8763/還是可以看到SERVICE-PROVIDER服務,這是因爲當一個服務註冊到註冊中心集羣的任意一個節點,這個節點都會把這個消息發送給其它節點,這樣當有服務消費者要來註冊中心尋找服務的時候,無論是在哪個註冊中心節點都能保證找到服務,這也是集羣的意義所在。
五、總結
以上就是服務註冊的過程,在實際中,服務提供者不可能只有一個,這時註冊的方法還是一樣的,當註冊了多個服務提供者,同樣可以在註冊中心的後臺看到所有註冊了的服務。
下一篇將介紹服務的消費。
源碼已經上傳到github:https://github.com/spareyaya/spring-cloud-demo/tree/master/chapter2
如果你想了解更多java相關的知識,可以訪問我的個人博客:http://notebook.techhuman.cn/
也歡迎你關注我的公衆號獲得文章推送