Feign是什么
- Feign是一个受到Retrofit,JAXRS-2.0和WebSocket启发的Java到HTTP客户端绑定器。
- Feign的第一个目标是降低将Denominator统一绑定到HTTP API 的复杂性。
- Feign 是一个声明web服务客户端,这使得编写web服务客户端更容易,使用Feign 创建一个接口并对它进行注解,它具有可插拔的注解支持包括Feign注解与JAX-RS注解,Feign还支持可插拔的编码器与解码器。
RestTemplate与Feign对比
如何使用
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId></dependency>
@FeignClient(name = "shop-provider-user")public interface UserFeignClient { @GetMapping("/users/{id}") User findById(@PathVariable("id") Long id);}
@EnableFeignClients@SpringBootApplication//(scanBasePackages = {"com.dream.shop"})public class MovieApplication { @Bean @LoadBalanced public RestTemplate restTemplate() { return new RestTemplate(); } public static void main(String[] args) { SpringApplication.run(MovieApplication.class, args); }}
@RequestMapping("/movies")@RestControllerpublic class MovieController { @Autowired private RestTemplate restTemplate; @Autowired private UserFeignClient userFeignClient; @GetMapping("/usersByFeign/{id}") public User findByIdByFeign(@PathVariable Long id) { return this.userFeignClient.findById(id); } @GetMapping("/users/{id}") public User findById(@PathVariable Long id) { // 这里用到了RestTemplate的占位符能力// User user = this.restTemplate.getForObject("http://localhost:8000/users/{id}", User.class, id); User user = this.restTemplate.getForObject("http://shop-provider-user/users/{id}", User.class, id); // ...电影微服务的业务... return user; }}