服务调用——Ribbon、LoadBalance和OpenFeign
生活随笔
收集整理的這篇文章主要介紹了
服务调用——Ribbon、LoadBalance和OpenFeign
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Ribbon、LoadBalance
消費端在使用restTemplate調用服務端時,對于負載均衡有兩種實現方式。
- 使用Ngnix來完成負載均衡,此時,需要在Nginx上進行服務端的相關配置,可以認為Nginx是跟服務端捆綁在一起的。
- 使用Ribbon來完成負載均衡,此時Ribbon是與消費端捆綁在一起的。
總結:如果想把負載均衡放在客戶端,使用Ribbon;如果想把負載均衡放在服務端,則使用Nginx。
Ribbon + LoadBalance
Ribbon依賴已經包含在Eureka依賴當中,不需要導入額外的依賴,直接與Eureka配套使用即可。使用的方法也非常簡單。使用注解@LoadBalanced即可賦予RestTemplate負載均衡的能力。
@Configuration public class ApplicationContextConfig {@Bean@LoadBalancedpublic RestTemplate getRestTemplate(){return new RestTemplate();} }然后在調用服務時,寫上微服務的名稱即可( public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";)
@RestController @Slf4j public class OrderController {public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";@Resourceprivate RestTemplate restTemplate;@GetMapping(value = "/consumer/payment/get/{id}")public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id) {return restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);} }默認使用的是輪詢負載均衡策略。
一共有以下幾種輪詢策略:
OpenFeign
OpenFeign相較于Ribbon更加輕便了,都不需要手動調用RestTemplate。
需要的依賴:
配置:
server.port=80 eureka.client.register-with-eureka=false #集群版 eureka.client.service-url.defaultZone=http://eureka7001.com:7001/eureka/, http://eureka7002.com:7002/eureka/ #單機版 eureka.client.service-url.defaultZone=http://eureka7001.com:7001/eureka/ # 根據自己的情況選擇用哪個主啟動類:
@SpringBootApplication @EnableFeignClients public class OrderFeignMain80 {public static void main(String[] args) {SpringApplication.run(OrderFeignMain80.class, args);} }需要加上注釋EnableFeignClients
Controller層demo:
Service層Demo:
@Component @FeignClient(value = "CLOUD-PAYMENT-SERVICE") public interface PaymentFeignService {@GetMapping(value = "/payment/get/{id}")public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id);@GetMapping(value = "/payment/feign/timeout")public String paymentFeignTimeout(); }這里記得要加@FeignClient注解,value為微服務的名稱。通過微服務名稱 + 路徑來調用接口。
總結
以上是生活随笔為你收集整理的服务调用——Ribbon、LoadBalance和OpenFeign的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LoadBalance负载均衡
- 下一篇: 细说 Nginx: 负载均衡 Load