1. Feign简介
-
Feign是Netflix开发的, 的Http客户端
-
Feign可以帮助我们更加便捷,优雅地调用Http API
-
在Spring Cloud中,使用Feign非常简单, 创建一个接口, 并在接口上添加一些注解就好了
2. Feign实例
2-1) 创建Feign接口
添加Feign依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
UserFeignClient.java
@FeignClient(name = "microservice-provider-user")
@RequestMapping(value = "/user")
public interface UserFeignClient {
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public User findById(@PathVariable("id") Long id);
}
2-2) 调用Feign Client
MovieController.java
@RestController
public class MovieController {
@Autowired
private UserFeignClient userFeignClient;
@GetMapping("/user/{id}")
public User findById(@PathVariable Long id) {
return this.userFeignClient.findById(id);
}
}
3. 测试
3-1) 启动eureka
3-2) 启动microservice-provider-user
3-3) 启动microservice-consumer-movie-feign
image.png3-4) 访问服务消费者
image.png本文的github代码地址:
https://github.com/davidgjy/springcloud-learn/tree/master/2_feign
网友评论