Feign
简介
在负载均衡篇的示例中使用RestTemplate
实现REST API
调用:
@GetMapping("/user/{id}")
public User findById(@PathVariable Long id) {
return this.restTemplate.getForObject("http://microservice-provider-user/" + id, User.class);
}
如果要请求更多参数的 URL:
http://localhost:8010/search?name=张三&username=account1&age=20.....
如果使用拼接字符串的方式构建 URL:
public User[] findById(String name, String username, Integer age) {
Map<String, Object> paramMap = Maps.newHashMap();
paramMap.put("name", name);
paramMap.put("username", username);
paramMap.put("age", age);
return this.restTemplate.getForObject("http://microservice-provider-user/search?name={name}&username={username}&age={age}", User[].class, paramMap);
}
这样的代码将变得难以维护。
Feign
是Netflix
开发的声明式、模板化的 HTTP 客户端,Feign
可以帮助我们更快捷、优雅地调用 HTTP API。- 在
Spring Cloud
中,使用Feign
非常简单——创建一个接口,并在接口上添加一些注解,代码就完成了。Feign
支持多种注解,例如Feign
自带的注解或者 JAX-RS 注解等。 Spring Cloud
对Feign
进行了增强,使Feign
支持了Spring MVC
注解,并整合了Ribbon
和Eureka
,从而让Feign
的使用更加方便。
为服务消费者整合Feign
启动一个
Eureka
注册中心,启动两个Eureka
服务提供者(传送门);创建服务消费者,在
pom
文件中添加依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
- 创建启动类:
@SpringBootApplication
@EnableFeignClients
public class ConsumerMovieApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerMovieApplication.class, args);
}
}
- 创建
Feign
接口,添加@FeignClient
注解:
@FeignClient(name = "microservice-provider-user")
public interface UserFeignClient {
@GetMapping(value = "/{id}")
public User findById(@PathVariable("id") Long id);
}
@FeignClient
注解用于创建Ribbon
负载均衡器。Ribbon
会把microservice-provider-user
解析成Eureka Server
中注册表中分服务。
- 创建 Controller:
@RestController
public class MovieController {
@Autowired
private UserFeignClient userFeignClient;
@GetMapping("/user/{id}")
public User findById(@PathVariable Long id) {
return this.userFeignClient.findById(id);
}
}
- 启动服务即可。