Spring cloud — Feign
@author 无忧少年
@createTime 2019-11-03
声明式服务Feign实例
我们知道,当我们要调用一个服务时,需要知道服务名和api地址,这样才能进行服务调用,服务少时,这样写觉得没有什么问题,但当服务一多,接口参数很多时,上面的写法就显得不够优雅了。所以,接下来,来说说一种更好更优雅的调用服务的方式:Feign。
Feign
是Netflix
开发的声明式、模块化的HTTP客户端。Feign
可帮助我们更好更快的便捷、优雅地调用HTTP API
。
在Spring Cloud
中,使用Feign
非常简单——创建一个接口,并在接口上添加一些注解。Feign
支持多种注释,例如Feign自带的注解或者JAX-RS注解等
Spring Cloud对Feign进行了增强,使Feign支持了Spring MVC注解,并整合了Ribbon和 Eureka,从而让Feign 的使用更加方便。只需要通过创建接口并用注解来配置它既可完成对Web服务接口的绑定。
Feign 实例
创建一个新工程项目
- 加入
feign
依赖
<!-- feign -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!-- eureka客户端依赖 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!-- rest api -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
- 配置文件
server.port=1004
spring.application.name=server-feign
eureka.client.serviceUrl.defaultZone=http://localhost:2000/eureka/
eureka.instance.prefer-ip-address=true
eureka.instance.instance-id=${spring.cloud.client.ip-address}:${server.port}
- 创建启动类,加入注解
@EnableFeignClients
,开启feign
支持。
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class FeignApplication {
private static Log log = LogFactory.getLog("FeignApplication.java");
public static void main(String[] args) {
SpringApplication.run(FeignApplication.class, args);
log.info("-----------------FeignApplication启动成功---------------------");
}
@Bean
@LoadBalanced
public RestTemplate restTemplat() {
return new RestTemplate();
}
}
- 创建一个接口类
IHelloClient
,加入注解@FeignClient
来指定这个接口所要调用的服务名称。
@FeignClient(name = "server-provide")
public interface IHelloClientService {
@RequestMapping(value = "/eurekaServer/HelloWorld", method = RequestMethod.GET)
String hello();
}
4.创建一个demo控制层,引入此接口类。
/**
* Feign 方式-示例
* @author lisiwen
*/
@RestController
public class FeignController {
private static Log log= LogFactory.getLog("FeignController.java");
@Autowired
IHelloClientService helloClientService;
@GetMapping("/feign")
public String hello() {
log.info("使用feign调用服务");
return helloClientService.hello();
}
}
5.启动应用,访问: http://localhost:1004/feign
使用起来非常简单,就像是调用本地的接口似的。
Feign继承特性
Feign
支持继承,但不支持多继承。使用继承,可将一些公共操作分组到一些父类接口中,从而简化Feign的开发。
注意事项
在使用Feign
时,会碰见一些问题,为了避免不必要的错误,以下这些需要额外注意下。
- GET请求多个参数时,需要使用@RequestParam
- GET请求参数为实体时,会自动转换成POST请求
- POST请求使用@RequestBody注解参数
- 不建议直接将@RequestMapping注解在类上,直接写在方法上