Feign是一個宣告式的Web服務客戶端,讓撰寫Web服務客戶端變得非常容易,只需 創建一個介面并在介面上添加注解即可,
OpenFeign 是Spring Cloud 在Feign 的基礎上支持了SpringMVC 的注解,如@RequestMapping等,OpenFeign 的@FeignClient 可以決議SpringMVC的@RequestMapping注解下的介面,并通過動態代理的方式產生實作類,實作類中做負載均衡并呼叫其他服務,
Feign自帶負載均衡配置項,
-
首先向注冊中心注冊微服務 cloud-payment-service
測驗類@GetMapping("/get/{id}") public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id) { Payment payment = paymentService.getPaymentById(id); log.info("*** 查詢結果:" + payment); if (payment != null) { return new CommonResult<Payment>(200, "查詢成功,server.port = "+serverPort, payment); } else { return new CommonResult<Payment>(444, ",沒有對應記錄,id=" + id, null); } } -
注冊消費微服務,使用服務呼叫 OpenFeign
主程式@SpringBootApplication @EnableEurekaClient //激活feign @EnableFeignClients public class OrderFeignApplication81 { public static void main(String[] args) { SpringApplication.run(OrderFeignApplication81.class,args); } }service層
@Component //指定微服務,Feign自帶負載均衡配置項 @FeignClient(value = "CLOUD-PAYMENT-SERVICE") public interface PaymentFeignService { //這個路徑對應指定的微服務的路徑 @GetMapping("payment/get/{id}") public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id); }這個介面上方的路徑對應指定的微服務CLOUD-PAYMENT-SERVICE下的路徑,
測驗類controller
@RestController @Slf4j public class OrderFeignController { @Resource private PaymentFeignService paymentFeignService; //呼叫service層介面 @GetMapping("/consumer/payment/get/{id}") public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id){ log.info("***consumer-feign-order id="+id); return paymentFeignService.getPaymentById(id); }
本質就是服務消費者的service層介面直接映射服務提供者的介面
介面使用了注解@FeignClient,則客戶端會針對這個介面創建一個動態代理,呼叫該介面,實質就是呼叫Feign客戶端創建的動態代理,
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/263427.html
標籤:其他
上一篇:時間繼電器
