微服务中的负载均衡简单实现

时间:2022-07-26
本文章向大家介绍微服务中的负载均衡简单实现,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

一、使用 RestTemplate 实现

在消费者微服务中,首先导入 RestTemplate 并设置该类。

使用 @LoadBalanced 注解赋予 RestTemplate 负载均衡的能力。

@Configuration
public class ApplicationContextConfig {

    /**
     *  LoadBalanced 赋予负载均衡的能力
     */
    @Bean
    @LoadBalanced
    public RestTemplate getRestTemplate() {
        return new RestTemplate();
    }
}

然后在控制器中指明要访问的微服务名字,例如这里是 CLOUD-PAYMENT-SERVICE

@RestController
@Slf4j
public class OrderController {

    private static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";

    @Resource
    private RestTemplate restTemplate;

    @GetMapping("/consumer/payment/create")
    public CommonResult create(Payment payment) {
        return restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, CommonResult.class);
    }

    @GetMapping("/consumer/payment/get/{id}")
    public CommonResult getPayment(@PathVariable("id") Long id) {
        return restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
    }
}

这样就能实现负载均衡了,因为引入 spring-cloud-starter-netflix-eureka-client 的时候就已经引入了 ribbon 了。

二、使用 OpenFeign 实现

首先我们需要在微服务项目的主启动类上加一个 @EnableFeignClients 注解,此时不用加 EnableEurekaClient 注解了:

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

然后定义一个接口 OrderFeignService,用于向服务的提供方发送请求,使用 @FeignClient("CLOUD-PAYMENT-SERVICE") 注解指定微服务名称。

@Component
@FeignClient("CLOUD-PAYMENT-SERVICE")
public interface OrderFeignService {

    /**
     * 完成 Feign 包装的调用
     * @param id
     * @return
     */
    @GetMapping("/payment/get/{id}")
    CommonResult getPayment(@PathVariable("id") Long id);
}

然后在控制器中向外界暴露一个接口即可。

@RestController
@Slf4j
public class OrderFeignController {
    @Resource
    private OrderFeignService orderFeignService;

    @GetMapping("/consumer/payment/get/{id}")
    public CommonResult getPayment(@PathVariable("id") Long id) {
        return orderFeignService.getPayment(id);
    }
}