遗留问题:前文中使用RestTemplate实现REST API调用时,会有拼接参数问题,如果参数过多会显得非常的不优雅,如下:
ribbonRestTemplate.getForObject("http://microservice-provider-user/"+id, User.class);
这时候就需要一种更加便捷、优雅地调用HTTP API的方式——Feign!
1、Feign简介
Feign是Netflix开发的声明式、模板化的HTTP客户端。创建一些接口,在接口上添加要请求服务的注解,指向供应方服务及其对应接口。
2、消费者整合Feign
2.1、pom文件中添加Feign依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
2.2、创建Feign接口,并添加@FeignClient注解
@FeignClient(name = "microservice-provider-user")
public interface UserFeignClient{
@RequestMapping(value="/{id}", method = RequestMethod.GET)
public User findById(@PathVariable("id") Long id);
}
以上注解会配合Eureka和Ribbon实现负载均衡,如果想指向具体某一个服务可以用一下配置
@FeignClient(name = "microservice-provider-user", url = "http://localhost:8000/")
2.3、调用Feign接口
@Autowired
private UserFeignClient userFeignClient;
public User findById(Long id){
return userFeignClient.findById(id);
}
2.4、启动类上添加@EnableFeignClient注解
@EnableDiscoveryClient
@SpringBootApplication
@EnableFeignClient
public class ConsumerMovieApplication{
public static void main(String[] args){
SpringApplication.run(ConsumerMovieApplication.class, args);
}
}
(以上内容已经够正常使用)
2.5、自定义Feign配置
2.6、手动创建Feign
2.7、Feign对继承的支持
2.8、Feign对压缩的支持
2.9、Feign的日志
2.10、使用Feign构造多参的请求
2.10.1、GET请求多参
方法一:
@FeignClient(name = "microservice-provider-user")
public interface UserFeignClient{
@RequestMapping(value="/getUser", method = RequestMethod.GET)
public User find1(@PathVariable("id") Long id,
@PathVariable("username") String username);
}
方法二:
@FeignClient(name = "microservice-provider-user")
public interface UserFeignClient{
@RequestMapping(value="/getUser", method = RequestMethod.GET)
public User find2(@RequestParam Map<String, Object> map);
}
2.10.2、POST请求多参
@FeignClient(name = "microservice-provider-user")
public interface UserFeignClient{
@RequestMapping(value="/getUser", method = RequestMethod.POST)
public User post(@RequestBody User user);
}