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/





Spring Cloud探路(三)REST 客户端Feign_ci

 成功!