Spring Cloud负载均衡:使用Feign作客户端负载均衡

有了一篇服务端负载均衡后,再来一篇客户端负载均衡,客户端负载均衡很简单,无需在zuul中做多余配置(本示例不引入zuul),只需要在客户端进行Feign引入和配置即可。

准备工作很简单,实现客户端负载均衡,首先需要Feign组件。

<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

在client启动类中添加EnableFeignClients属性,代码如下:

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class ClientApplication {

    public static void main(String[] args) {
        SpringApplication.run(ClientApplication.class, args);
    }

}

然后编写一个调用,示例代码如下:

@FeignClient(value = "${service.request.name}", fallback = helloHystrix.class)
public interface hello extends BaseService{
    @RequestMapping(method = RequestMethod.GET, value = path + "/index/hello")
    String hello();
}

然后,在eureka中注册相关服务提供者和调用者,如下图所示:

在本地输入调用地址:http://localhost:8004/index/hello,结果如下:

最终在Feign的加持下,实现客户端负载均衡(原理略)
over.

猜你喜欢

转载自www.cnblogs.com/jizhong/p/11438456.html