【Spring Cloud 05】Feign
2021-02-26 15:46:03
## 新建模块
新建一个叫`foo-api`的module
## 添加依赖
在xml中添加如下依赖
```xml
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>
```
## 添加interface
FooClient接口代码如下
```java
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
@FeignClient(name = "FOO-SERVICE")
public interface FooClient {
@GetMapping("/version")
String version();
}
```
接下来,我们关注`调用方`
## 调用方添加依赖
在xml中添加如下依赖
```xml
<dependency>
<groupId>com.example</groupId>
<artifactId>foo-api</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
```
## 启动类中
在启动类中,添加注解
```java
import org.springframework.cloud.openfeign.EnableFeignClients;
@EnableFeignClients()
@SpringBootApplication
public class BarApplication {
public static void main(String[] args) {
SpringApplication.run(BarApplication.class, args);
}
}
```
## API调用
使用FooClient进行API调用
```java
@RestController
public class DemoController {
@Autowired
FooClient fooClient;
@GetMapping("/demo2")
public String demo2() {
String version = fooClient.version();
return "[bar-service] foo.version: " + version;
}
}
```