Feign在RestTemplate的基础上对其封装,由它来帮助我们定义和实现依赖服务接口的定义。Spring Cloud Feign基于Netflix Feign 实现的,整理Spring Cloud Ribbon 与 Spring Cloud Hystrix,并且实现了声明式的Web服务客户端定义方式。
创建子项目
1.在前面的demo中,创建一个新的模块,命名为 eureka-feign-client。将porm.xml改成如下配置:

修改application.yml的配置,代码如图:

然后在启动类加入注解@EnableFeignClients

实现简单Feign Client
新建一个EurekaClientFeign接口,并加上注解@FeignClient 声明该接口为Feign Client,参数value为远程调用client的服务名,编写一个方法sayHiFromClientEureka,该方法通过Feign来调用eureka-client服务“hi”接口,代码如下:

在service层中注入EurekaClientFeign的Bean,通过该bean调用sayHiFromClientEureka(),代码如下:

在controller下创建一个HiController,加入@RestController注解,写一个方法调用远程服务器,具体如图:

启动eureka-server实例,端口为8761,启动eureka-client两个实例,端口分别为8762和8763,再启动eureka-feign-client,端口为8765.
访问:http://127.0.0.1:8761如图:

访问 http://127.0.0.1:8762/hi?name=ggg

访问 http://127.0.0.1:8763/hi?name=ggg

轮询访问 /http://127.0.0.1:8765/hi?name=ggg,可以看到结果为上面两个结果的循环。
由此可见,feign已经可以实现负载均衡了。
网友评论