(部分内容来自于:https://springcloud.cn/,以及周立的教程:http://edu.51cto.com/course/course_id-7348.html)
Feign是一个声明式的WebService客户端。使用Feign能让编写WebService客户端更加简单,它的使用方法是定义一个接口,然后在接口上添加注解,同时也支持JAX-RS标准的注解。Feign也支持可插拔式的编码器和解码器。SpringCloud对Feign进行了封装,使其支持SpringMVC标准注解和HttpMessageConverters。Feign可以与Eureka和Ribbon组合使用以支持负载均衡。
如何使用Feign?
添加Feign的依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
在入口类上添加@EnableFeignClients注解
项目的目录结构:
Maven依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
UserClient.java
@FeignClient("user-server")
public interface UserClient {
@RequestMapping(value="/getByUserId/{userId}", method=RequestMethod.GET)
public String getByUserId(@PathVariable("userId") String userId);
}
UserController.java
@RestController
public class UserController {
@Autowired
private UserClient userClient;
@RequestMapping(value="/getByUserId/{userId}", method=RequestMethod.GET)
public String getByUserId(@PathVariable("userId") String userId){
return userClient.getByUserId(userId);
}
}
application.properties
#\u4FEE\u6539Tomcat\u7AEF\u53E3\u53F7
server.port=8001
#服务注册中心的配置内容,指定服务注册中心的位置
eureka.client.serviceUrl.defaultZone=http://192.168.1.12:8761/eureka/
spring.application.name=user-client
StoreClient.java
@FeignClient("stores")
public interface StoreClient {
@RequestMapping(method = RequestMethod.GET, value = "/stores")
List<Store> getStores();
@RequestMapping(method = RequestMethod.POST, value = "/stores/{storeId}", consumes = "application/json")
Store update(@PathVariable("storeId") Long storeId, Store store);
}
@FeignClient注解中的stores属性可以是一个任意字符串,如果与Eureka组合使用,则stores应为Eureka中的服务名,Feign用它来创建一个Ribbon负载均衡器。也可以通过url属性来指定一个地址,可以是完整的URL,也可以是一个主机名。标注了@FeignClient注解的接口,在ApplicationContext中的Bean实例名是这个接口的全限定名,同时这个Bean还有一个别名,为Bean名+FeignClient。
覆盖Feign的默认配置
SpringCloud对Feign的封装中一个核心的概念就是客户端要有一个名字。每个客户端随时可以向远程服务发起请求,并且每个服务都可以像使用@FeignClient注解一样指定一个名字。SpringCloud会将所有的@FeignClient组合在一起创建一个新的ApplicationContext,并使用FeignClinetsConfiguration对Clients进行配置。配置中包括编码器、解码器和一个feign.Contract。
SpringCloud允许你通过configuration属性完全控制Feign的配置信息,这些配置比FeignClientsConfiguration优先级要高: