Feign
Feign是一种声明式、模板化的HTTP客户端,Feigin实现内部服务调用 内部服务调用,即服务都注册在eureka注册中心上,采用Feign进行调用。 Feign是一种声明式、模板化的HTTP客户端。在Spring Cloud中使用Feign, 我们可以做到使用HTTP请求远程服务时能与调用本地方法一样的编码体验,开发者完全感知不到这是远程方法,更感知不到这是个HTTP请求。
1.1 引入maven依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
1.2调用
@FeignClient("platform.user.rest")
public interface UserServiceClient {
@RequestMapping(value = "/users/{id}" , method = RequestMethod.GET)
public String get(@PathVariable("id") String id);
}
通过@FeignClient(“{服务名称}”)注解,实现服务间调用,如果同一个服务有多个实例,那么这种调用方式可以实现服务负载均衡。
1.3 调用外部服务
有多种方式调用,常见的的方式有httpclient。这里主要介绍其他两种方式RestTemplate和Feign。
1.3.1 RestTemplate 调用方式
Spring封装了一套http的调用工具resttemplate。在程序中使用注入RestTemplate 即可调用,如下: @Autowired public RestTemplate restTemplate;
1.3.2 Fegin调用方式
@FeignClient(url="http://ip:port/project")
通过@FeignClient(url=“{url}”)注解,实现外部服务调用。