什么是Feign
Feign是一个声明式的伪Http客户端,它使得写Http客户端变得更简单。使用Feign,只需要创建一个接口并注解。它具有可插拔的注解特性,可使用Feign 注解和JAX-RS注解。Feign支持可插拔的编码器和解码器。Feign默认集成了Ribbon,并和Eureka结合,默认实现了负载均衡的效果。
简而言之:
- Feign 采用的是基于接口的注解
- Feign 整合了ribbon
创建一个服务消费者Feign
新建一个Spring Boot项目,并添加组件Eureka-discovery,Web和Feign
同样的,在启动类上添加注解@EnableDiscoveryClient
和@EnableFeignClients
开启Feign的功能
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class ServiceFeignApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceFeignApplication.class, args);
}
}
application.yml配置
server:
port: 8765
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
spring:
application:
name: service-feign
写一个Service和Controller
@RestController
public class HelloController {
@Autowired
HelloService helloService;
@GetMapping("/hello")
public String sayHello(String name){
return helloService.sayHelloFromClient(name);
}
}
@FeignClient(value = "service-hello")
public interface HelloService {
@GetMapping("/index")
String sayHelloFromClient(@RequestParam("name") String name);
}
验证
实际上这里feign和ribbon基本都差不多,只是feign相当于在ribbon上做了一层封装
验证结果也和ribbon一样,8762和8763交替显示