服务调用——Ribbon、LoadBalance和OpenFeign
生活随笔
收集整理的這篇文章主要介紹了
服务调用——Ribbon、LoadBalance和OpenFeign
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
Ribbon、LoadBalance
消費(fèi)端在使用restTemplate調(diào)用服務(wù)端時(shí),對(duì)于負(fù)載均衡有兩種實(shí)現(xiàn)方式。
- 使用Ngnix來完成負(fù)載均衡,此時(shí),需要在Nginx上進(jìn)行服務(wù)端的相關(guān)配置,可以認(rèn)為Nginx是跟服務(wù)端捆綁在一起的。
- 使用Ribbon來完成負(fù)載均衡,此時(shí)Ribbon是與消費(fèi)端捆綁在一起的。
總結(jié):如果想把負(fù)載均衡放在客戶端,使用Ribbon;如果想把負(fù)載均衡放在服務(wù)端,則使用Nginx。
Ribbon + LoadBalance
Ribbon依賴已經(jīng)包含在Eureka依賴當(dāng)中,不需要導(dǎo)入額外的依賴,直接與Eureka配套使用即可。使用的方法也非常簡(jiǎn)單。使用注解@LoadBalanced即可賦予RestTemplate負(fù)載均衡的能力。
@Configuration public class ApplicationContextConfig {@Bean@LoadBalancedpublic RestTemplate getRestTemplate(){return new RestTemplate();} }然后在調(diào)用服務(wù)時(shí),寫上微服務(wù)的名稱即可( 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);} }默認(rèn)使用的是輪詢負(fù)載均衡策略。
一共有以下幾種輪詢策略:
OpenFeign
OpenFeign相較于Ribbon更加輕便了,都不需要手動(dòng)調(diào)用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/ #單機(jī)版 eureka.client.service-url.defaultZone=http://eureka7001.com:7001/eureka/ # 根據(jù)自己的情況選擇用哪個(gè)主啟動(dòng)類:
@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為微服務(wù)的名稱。通過微服務(wù)名稱 + 路徑來調(diào)用接口。
總結(jié)
以上是生活随笔為你收集整理的服务调用——Ribbon、LoadBalance和OpenFeign的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LoadBalance负载均衡
- 下一篇: 负载均衡(Load Balance)简介