Declarative REST Client: Feign
Feign is a declarative web service client. It makes writing web service clients easier.
如上是Spring Cloud文檔中對於Feign的定義,結合之前的兩篇博文,在這里我們就可以吧Feign簡單的理解為用戶(前端)可以直接接觸到的REST接口提供者。在Feign中,我們可以方便的訪問和使用意已經在Erueka服務器中注冊過的服務了。
1、建立maven工程,配置pom.xml文件
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Camden.SR6</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
2、建立包及啟動類
@Configuration
@ComponentScan
@EnableAutoConfiguration
@EnableEurekaClient
@EnableFeignClients
@SpringBootApplication
public class FeignApplication {
public static void main(String[] args) {
SpringApplication.run(FeignApplication.class, args);
}
}
3、建立接口類,用來調用之前文章中CLIENT-SERVICE1服務的方法hello()
@FeignClient("CLIENT-SERVICE1")
public interface IHello {
@RequestMapping(value = "/hello",method = RequestMethod.GET)
String getHello();
}
其中@FeignClient中指定需要調用的微服務的名稱,@RequestMapping中指定訪問微服務響應接口的路徑,如之前微服務的hello方法是通過"/hello"路徑訪問,那么這里需要配置一致
4、新建Controller類,為前端提供REST接口
@RestController
public class HelloController {
@Autowired
private IHello iHello;
@RequestMapping(value = "gethello",method = RequestMethod.GET)
public String getHello(){
return iHello.getHello();
}
}
5、配置Feign的配置文件,指定Erureka服務器注冊地址和訪問端口application.yml
server:
port: 8081
eureka:
client:
serviceUrl:
defaultZone: http://localhost:1000/eureka/

成功!