1.微服务中feign中集成了ribbon和eureka合并使用使用负载均衡
Feign是一个声明式的伪http客户端,它使得写http客户端变得更简单,使用fegin,只需要创建一个接口,并注解,它具有可插拔的注解特性,可使用Feign 注解和JAX-RS注解。Feign支持可插拔的编码器和解码器。Feign默认集成了Ribbon,并和Eureka结合,默认实现了负载均衡的效果。
2.首先建一个微服务工程进行测试。添加feign依赖
<!-- eureka客户端 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!-- feign依赖 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!-- 断路器 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<!-- 服务接口的监控依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!-- 短路器仪表盘或面板的注解 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>
这个可以要也可以不要,这是开启断路器面板的注解,用于查看实时监控数据,
如果用必须在配置文件中
feign.hystrix.enabled=true 添加这个配置,打开断路器
在启动类添加注解 @EnableFeignClients
然后把这个服务也注册到注册中心通过@EnableEurekaClient
3.写一个接口来调用服务
@FeignClient("testService")// 需要调用的服务名
public interface testService{
@RequestMapping(value="/hello",method = RequestMethod.GET)// 要调用的接口名和请求方式
public String hello(@RequestParam("name")String name);// 要调用的接口需要传入的参数
}
4.实现这个接口进行测试
@Autowired
private testService testService;
@RequestMapping("/hello")
public String hello(@RequestParam("name") String name){
return testService.hello(name);
}
然后启动注册中心,启动两个不同端口的testService服务,在启动feign测试服务,通过
localhost:端口号/访问的服务接口名称?接口参数
多次刷新每次调用的服务端口号会不同