本文介绍Feign调用服务
Feign是一个声明性的Web服务客户端。它使编写Web服务客户端变得更容易。
它具有可插入的注释支持,包括Feign注释和JAX-RS注释。Feign还支持可插拔编码器和解码器。
Feign默认集成了Ribbon
- 在父工程下创建一个项目
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>springcloud-demo</artifactId>
<groupId>demo.cloud</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>feign-consumer</artifactId>
<name>feign-consumer</name>
<dependencies>
<!-- eureka-client依赖 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!-- feign依赖 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>
- 修改application.yml文件
server:
port: 8766
spring:
application:
#服务名称
name: feign-consumer
eureka:
client:
#是否将自己注册到Eureka服务中
register-with-eureka: true
#是否从Eureka服务中获取注册信息
fetch-registry: true
#Eureka注册中心的地址,多个注册中心用,隔开
serviceUrl:
defaultZone: http://localhost:8761/eureka/
- 修改启动程序
@EnableFeignClients注解开启Feign的功能
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class FeignConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(FeignConsumerApplication.class, args);
}
}
- 创建feign接口
@FeignClient(“服务名”)注解指定要调用的服务
@GetMapping(“接口”)注解指定要调用的接口(支持spring mvc中的请求注解)
基本类型传参需要用@RequestParam(“name”)注解,不使用会获取不到参数
get请求传实体类参数需要转换成Map,并且使用@RequestParam注解
post请求传实体类参数需要使用@RequestBody注解
@FeignClient("eureka-service")
public interface TestService {
@GetMapping("/hello")
String hello();
}
- 创建controller
@RestController
public class TestController {
@Autowired
private TestService testService;
@GetMapping("/test")
public String test(){
return testService.hello();
}
}
- 测试接口
浏览器访问http://localhost:8766/testport:8763
port:8764
作者公众号