1. 程式人生 > >史上最簡單的SpringCloud教程 | 第二篇: 服務消費者(rest+ribbon)

史上最簡單的SpringCloud教程 | 第二篇: 服務消費者(rest+ribbon)

image tree 開啟 then rom cat learn 替代 官網

最新Finchley版本:
https://www.fangzhipeng.com/springcloud/2018/08/30/sc-f2-ribbon/
或者
http://blog.csdn.net/forezp/article/details/81040946

在上一篇文章,講了服務的註冊和發現。在微服務架構中,業務都會被拆分成一個獨立的服務,服務與服務的通訊是基於http restful的。Spring cloud有兩種服務調用方式,一種是ribbon+restTemplate,另一種是feign。在這一篇文章首先講解下基於ribbon+rest。

Ribbon is a client side load balancer which gives you a lot of control over the behaviour of HTTP and TCP clients. Feign already uses Ribbon, so if you are using @FeignClient then this section also applies.

-----摘自官網

ribbon是一個負載均衡客戶端,可以很好的控制htt和tcp的一些行為。Feign默認集成了ribbon。

ribbon 已經默認實現了這些配置bean:

  • IClientConfig ribbonClientConfig: DefaultClientConfigImpl

  • IRule ribbonRule: ZoneAvoidanceRule

  • IPing ribbonPing: NoOpPing

  • ServerList ribbonServerList: ConfigurationBasedServerList

  • ServerListFilter ribbonServerListFilter: ZonePreferenceServerListFilter

  • ILoadBalancer ribbonLoadBalancer: ZoneAwareLoadBalancer

這一篇文章基於上一篇文章的工程,啟動eureka-server 工程;啟動service-hi工程,它的端口為8762;將service-hi的配置文件的端口改為8763,並啟動,這時你會發現:service-hi在eureka-server註冊了2個實例,這就相當於一個小的集群。訪問localhost:8761如圖所示:

如何一個工程啟動多個實例,請看這篇文章:https://blog.csdn.net/forezp/article/details/76408139

技術分享圖片

三、建一個服務消費者

重新新建一個spring-boot工程,取名為:service-ribbon;
在它的pom.xml文件分別引入起步依賴spring-cloud-starter-eureka、spring-cloud-starter-ribbon、spring-boot-starter-web,代碼如下:


在工程的配置文件指定服務的註冊中心地址為http://localhost:8761/eureka/,程序名稱為 service-ribbon,程序端口為8764。配置文件application.yml如下:


在工程的啟動類中,通過@EnableDiscoveryClient向服務中心註冊;雅思培訓一般多少錢並且向程序的ioc註入一個bean: restTemplate;並通過@LoadBalanced註解表明這個restRemplate開啟負載均衡的功能。


寫一個測試類HelloService,通過之前註入ioc容器的restTemplate來消費service-hi服務的“/hi”接口,在這裏我們直接用的程序名替代了具體的url地址,在ribbon中它會根據服務名來選擇具體的服務實例,根據服務實例在請求的時候會用具體的url替換掉服務名,代碼如下:


寫一個controller,在controller中用調用HelloService 的方法,代碼如下:


在瀏覽器上多次訪問http://localhost:8764/hi?name=forezp,瀏覽器交替顯示:

hi forezp,i am from port:8762

hi forezp,i am from port:8763

這說明當我們通過調用restTemplate.getForObject(“http://SERVICE-HI/hi?name=”+name,String.class)方法時,已經做了負載均衡,訪問了不同的端口的服務實例。

技術分享圖片

  • 一個服務註冊中心,eureka server,端口為8761
  • service-hi工程跑了兩個實例,端口分別為8762,8763,分別向服務註冊中心註冊
  • sercvice-ribbon端口為8764,向服務註冊中心註冊
  • 當sercvice-ribbon通過restTemplate調用service-hi的hi接口時,因為用ribbon進行了負載均衡,會輪流的調用service-hi:8762和8763 兩個端口的hi接口;

源碼下載:https://github.com/forezp/SpringCloudLearning/tree/master/chapter2

史上最簡單的SpringCloud教程 | 第二篇: 服務消費者(rest+ribbon)