Spring Boot + Spring Cloud 构建微服务系统(三):服务消费和负载(Feign)
Spring Cloud Feign
Spring Cloud Feign是一套基于Netflix Feign實現的聲明式服務調用客戶端。它使得編寫Web服務客戶端變得更加簡單。我們只需要通過創建接口并用注解來配置它既可完成對Web服務接口的綁定。它具備可插拔的注解支持,包括Feign注解、JAX-RS注解。它也支持可插拔的編碼器和解碼器。Spring Cloud Feign還擴展了對Spring MVC注解的支持,同時還整合了Ribbon來提供均衡負載的HTTP客戶端實現。
添加依賴
修改?spring-cloud-consul-consumer 的 pom 文件,添加 feign 依賴。
pom.xml
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-openfeign</artifactId></dependency>修改啟動器
修改啟動器類,添加?@EnableFeignClients?注解開啟掃描Spring Cloud Feign客戶端的功能:
ConsuleConsumerApplication.java
package com.louis.spring.cloud.consul.consumer;import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.context.annotation.Bean; import org.springframework.web.client.RestTemplate;@EnableFeignClients @SpringBootApplication public class ConsuleConsumerApplication {public static void main(String[] args) {SpringApplication.run(ConsuleConsumerApplication.class, args);}@Bean@LoadBalancedpublic RestTemplate restTemplate() {return new RestTemplate();} }添加Feign接口
添加 FeignHelloService 接口, 在類頭添加注解 @FeignClient("service-producer") ,service-producer是要調用的服務名。
添加跟調用目標方法一樣的方法聲明,只需要方法聲明,不需要具體實現,注意跟目標方法定義保持一致。
FeignHelloService.java
package com.louis.spring.cloud.consul.consumer.service;import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.RequestMapping;@FeignClient("service-producer") public interface FeignHelloService {@RequestMapping("/hello")public String hello(); }添加控制器
添加 FeignHelloController 控制器,注入?FeignHelloService,就可以像使用本地方法一樣進行調用了。
FeignHelloController.java
package com.louis.spring.cloud.consul.consumer.controller;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;import com.louis.spring.cloud.consul.consumer.service.FeignHelloService;@RestController public class FeignHelloController {@Autowiredprivate FeignHelloService feignHelloService;@RequestMapping("/feign/call")public String call() {// 像調用本地服務一樣return feignHelloService.hello();} }測試效果
啟動成功之后,訪問?http://localhost:8521/feign/call,發現調用成功,且 hello consul 和? hello consul two 結果隨機出現。
這是因為 Feign 是基于 Ribbon 實現負載均衡的,而我們在上一節中配置了?Ribbon 的負載策略為隨機策略。
?
?
源碼下載
碼云:https://gitee.com/liuge1988/spring-cloud-demo.git
作者:朝雨憶輕塵
出處:https://www.cnblogs.com/xifengxiaoma/?
版權所有,歡迎轉載,轉載請注明原文作者及出處。
轉載于:https://www.cnblogs.com/xifengxiaoma/p/9806291.html
總結
以上是生活随笔為你收集整理的Spring Boot + Spring Cloud 构建微服务系统(三):服务消费和负载(Feign)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: esp32-智能语音-录音(保存于SD卡
- 下一篇: 2018-2019-1 20165221