介绍
Feign是一个公开的Web服务客户端。它使编写Web服务客户机更容易。用Feign创建接口和注释。它具有可拔插的注释支持,包括Feign的注释和JAX-RS注释。Feign还支持热插拔编码器和解码器。Spring Cloud添加注释的支持和使用Spring MVC的Spring Web默认使用相同的httpmessageconverters。springCloud集成了Ribbon和Eureka提供负载平衡的HTTP客户端使用Feign
简单使用(Spring mvc的注解)
- 启动类添加@EnableFeignClients注解
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class MovieFeignApplication {
public static void main(String[] args) {
SpringApplication.run(MovieFeignApplication.class, args);
}
}
- 创建Client,是用Spring mvc注解
//user-provider是服务提供者user的applicationName
@FeignClient("user-provider")
public interface UserClient {
@RequestMapping(value = "/getUser/{id}", method = RequestMethod.GET)
User getUser(@PathVariable(value = "id") Integer id);
@RequestMapping(value = "/changeUser", method = RequestMethod.POST)
User changeUser(@RequestBody User user);
}
这里需要注意一下:
- RequestMapping不能使用GetMapping代替;
》2. @PathVariable中必须给出明确的value值;
- 调用
@RestController
public class MovieController {
@Autowired
private UserClient userClient;
@GetMapping("/movie/{id}")
public User getUser(@PathVariable Integer id) {
return userClient.getUser(id);
}
@GetMapping(value = "/changeUser")
public User chanageUser(User user) {
return userClient.changeUser(user);
}
}
使用Feign的注解
- 添加Configration类
@Configuration
public class FooConfigration {
@Bean
public Contract feignContract() {
return new feign.Contract.Default();
}
}
- 修改 Client类
@FeignClient(name = "user-provider", configuration = FooConfigration.class)
public interface UserClient {
// @RequestMapping(value = "/getUser/{id}", method = RequestMethod.GET)
// User getUser(@PathVariable(value = "id") Integer id);
// @RequestMapping(value = "/changeUser", method = RequestMethod.POST)
// User changeUser(@RequestBody User user);
@RequestLine("GET /getUser/{id}")
User getUser(@Param("id") Integer id);
}
- 修改@FeignClient(name = "user-provider", configuration = FooConfigration.class);
- 使用Fegin的注解 @RequestLine("GET /getUser/{id}")
- 使用Fegin 的注解@Param
网友评论