声明式客户端接口
只需要定义一个抽象的接口,就可以通过接口调用远程服务,不需要写具体调用代码.
例如调用后台商品服务,接口可以这样定义
@FeignClient(name="item-service")
public interface ItemFeignClient {
@GetMapping("/{orderId}")
JsonResult<List<Item>> getItems(@PathVarible String orderId);
}
- 通过注解,配置以下三点:
- 服务id - 确定调用哪个远程服务
- 路径 - 调用一个服务的哪个路径
- 参数 - 向这个路径提交什么参数数据
微服务应用中国,ribbon和hystrix总是同时出现,feign整合了两者,并提供了声明式消费者客户端
- 用feign代替了 hystrix+ribbon
入门案例
1.新建项目并导入坐标
2. 添加公共配置类坐标
3. yml配置
spring:
application:
name: feign
server:
port: 3001
eureka:
client:
service-url:
defaultZone: http://eureka1:2001/eureka, http://eureka2:2002/eureka
4. 主程序添加注解
@EnableDiscoveryClient
(开启eureka)和 @EnableFeignClients
(开启 feign)
@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
public class Sp09FeignApplication {
public static void main(String[] args) {
SpringApplication.run(Sp09FeignApplication.class, args);
}
}
feign声明式客户端
feign 利用了我们熟悉的 spring mvc 注解来对接口方法进行设置,降低了我们的学习成本。
通过这些设置,feign可以拼接后台服务的访问路径和提交的参数
例如:
@GetMapping("/{userId}/score")
JsonResult addScore(@PathVariable Integer userId,