Spring Cloud 服務端註冊與客戶端調用

上一篇中,我們已經把Spring Cloud的服務註冊中心Eureka搭建起來了,這一章,我們講解如何將服務註冊到Eureka,以及客戶端如何調用服務。

一、註冊服務

首先要再項目中引入Eureka Client,在pom.xml中加入如下配置:

org.springframework.cloudspring-cloud-dependenciesEdgware.SR3pomimportorg.springframework.cloudspring-cloud-starter-netflix-eureka-client

然後再我們的application.properties中配置好Eureka註冊中心的地址,如下:

eureka.client.service-url.defaultZone=http://localhost:8761/eureka/

http://localhost:8761/eureka/是默認地址,你可以進行修改。程序上我們正常開發即可,使用Spring MVC。如下:

@SpringBootApplication@RestController@RequestMapping("demo")public class Application { @RequestMapping("home") public String home() { return "Hello world"; } public static void main(String[] args) { new SpringApplicationBuilder(Application.class).web(true).run(args); }} 

這樣/demo/home就會註冊到Eureka註冊中心。接下來我們要說一說如何調用。

二、使用Feign進行調用,Hystrix熔斷

首先我們將Feign引入到項目中,並將Hystrix一併引入,這樣可以在服務不可用時進行熔斷。在pom.xml中加入如下配置:

 org.springframework.cloud spring-cloud-starter-netflix-hystrix org.springframework.cloud spring-cloud-starter-feign

然後在application.properties中加入

feign.hystrix.enabled=true

將feign的熔斷開啟了。然後在main class中加上註解

@SpringBootApplication@EnableCircuitBreaker@EnableFeignClientspublic class SpringCloudClientApplication {public static void main(String[] args) {SpringApplication.run(SpringCloudClientApplication.class, args);}}

接下來我們編寫Feign的調用接口,ITempService,如下:

@FeignClient(name = "EUREKA-SERVER",fallback = TempService.class)public interface ITempService {@RequestMapping(method = RequestMethod.GET, value = "/demo/home")public String index();}

@FeignClient說明這個接口是一個FeignClient,其中name指向的是服務的名字,在前面的服務中,我們應用的名字叫EUREKA-SERVER,我們這裡將name指向這個服務,fallback是熔斷後執行的類,我們的熔斷執行類為TempService。

@RequestMapping指向EUREKA-SERVER服務中的具體接口,這裡我們指向/demo/home,這樣我們在調用index方法時,就會調用遠程服務的/demo/home。但是如果遠程服務不可用,我們該如何處理呢?這樣就要用到Hystrix熔斷。

我們編寫ITempService接口的實現類TempService,如下:

@Componentpublic class TempService implements ITempService {@Overridepublic String index() {return "index error";}}

這樣,當遠程服務/demo/home不可用時,就會執行index方法,返回“index error”。

最後,我們編寫Controller,完成調用,如下:

@RestController@RequestMapping("feign")public class TempController {@Autowiredprivate ITempService tempService;@RequestMapping("call")public String call(){return tempService.index();}}

這樣我們的服務調用與服務註冊的例子就講解完了,是不是很簡單,有問題,歡迎在評論區溝通。

Spring Cloud 服務端註冊與客戶端調用


分享到:


相關文章: