java
依赖
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>springcloud</artifactId> <groupId>com.qn</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion>
<artifactId>consumer-feign</artifactId>
</project>
|
配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| server: port: 8900 spring: application: name: consumer-order-ribbon eureka: instance: hostname: localhost
lease-expiration-duration-in-seconds: 15
lease-renewal-interval-in-seconds: 5 client: service-url: defaultZone: http://localhost:9999/eureka
|
启动类
1 2 3 4 5 6 7 8 9 10
| @SpringBootApplication
@EnableEurekaClient
@EnableFeignClients public class ConsumerFeignApp { public static void main(String[] args) { SpringApplication.run(ConsumerFeignApp.class,args); } }
|
服务接口
1 2 3 4 5 6 7 8
|
@FeignClient(value ="provider-user") public interface UserService { @GetMapping("/user/{id}") User getUser(@PathVariable Long id); }
|
业务类(数据类同上省略)
1 2 3 4 5 6 7 8 9 10
| @RestController public class OrderController { @Autowired private UserService userService;
@GetMapping("/order/{id}") public User getOrder(@PathVariable Long id){ return userService.getUser(id); } }
|
测试
1
| 启动eureka、同时启动两个提供者、启动Feign客户端,访问地址http://localhost:8900/order/1,可以看到,轮流访问两个提供者服务。说明 Feign 默认是集成了 Ribbon 的轮询方案。
|
Feign 如何结合 Ribbon 切换均衡算法
可以在 application.yml 中指定,如下:
1 2 3
| PROVIDER-USER: ribbon: NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
|
测试均衡算法
重启 Feign 客户端,访问上面那个 url,可以发现随机访问负载策略是生效的。