feign是声明式的web service客户端,它让微服务之间的调用变得更简单了,类似controller调用service。Spring Cloud集成了Ribbon和Eureka,可在使用Feign时提供负载均衡的http客户端。
1.新建springboot子工程作为服务消费者,老规矩先导入相关依赖(ps:springcloud依赖在其父工程已经导入)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
2.在springboot启动类上加上注解@EnableEurekaClient和@EnableFeignClients
3.配置application.yml参数,端口为9091
#端口
server:
port: 9091
#服务名称
spring:
application:
name: feign-consumer
eureka:
client:
service-url:
defaultZone: http://www.aaa.com:10000/eureka,http://www.bbb.com:10001/eureka,http://www.ccc.com:10002/eureka
4.使用feign进行服务调用,先定义一个接口
//应用名称
@FeignClient("provider")
public interface MyFeign {
//RequestMapping和方法名都与提供者那边一致
@RequestMapping("/helloProvider")
String hello();
}
controller:
@RestController
public class FeignConsumerController {
@Autowired
MyFeign myFeign;
@RequestMapping("/helloFeign")
public String helloFeign() {
String result = myFeign.hello();
return result;
}
}
5.分别启动注册中心10000,两个服务提供者8080和8081,以及消费者9091,重复访问http://localhost:9091/helloFeign,发现依然有轮询,这是因为feign的底层集成了ribbon.