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

来源:互联网 发布:王尼玛有没有开淘宝店 编辑:程序博客网 时间:2024/06/05 04:53

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文件

  1. <parent>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-parent</artifactId>
  4. <version>1.5.2.RELEASE</version>
  5. <relativePath/> <!-- lookup parent from repository -->
  6. </parent>
  7. <properties>
  8. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  9. <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  10. <java.version>1.8</java.version>
  11. </properties>
  12. <dependencies>
  13. <dependency>
  14. <groupId>org.springframework.cloud</groupId>
  15. <artifactId>spring-cloud-starter-feign</artifactId>
  16. </dependency>
  17. <dependency>
  18. <groupId>org.springframework.cloud</groupId>
  19. <artifactId>spring-cloud-starter-eureka</artifactId>
  20. </dependency>
  21. <dependency>
  22. <groupId>org.springframework.boot</groupId>
  23. <artifactId>spring-boot-starter-test</artifactId>
  24. <scope>test</scope>
  25. </dependency>
  26. </dependencies>
  27. <dependencyManagement>
  28. <dependencies>
  29. <dependency>
  30. <groupId>org.springframework.cloud</groupId>
  31. <artifactId>spring-cloud-dependencies</artifactId>
  32. <version>Camden.SR6</version>
  33. <type>pom</type>
  34. <scope>import</scope>
  35. </dependency>
  36. </dependencies>
  37. </dependencyManagement>
  38. <build>
  39. <plugins>
  40. <plugin>
  41. <groupId>org.springframework.boot</groupId>
  42. <artifactId>spring-boot-maven-plugin</artifactId>
  43. </plugin>
  44. </plugins>
  45. </build>

2、建立包及启动类
  1. @Configuration
  2. @ComponentScan
  3. @EnableAutoConfiguration
  4. @EnableEurekaClient
  5. @EnableFeignClients
  6. @SpringBootApplication
  7. public class FeignApplication {
  8. public static void main(String[] args) {
  9. SpringApplication.run(FeignApplication.class, args);
  10. }
  11. }

3、建立接口类,用来调用之前文章中CLIENT-SERVICE1服务的方法hello()
  1. @FeignClient("CLIENT-SERVICE1")
  2. public interface IHello {
  3. @RequestMapping(value = "/hello",method = RequestMethod.GET)
  4. String getHello();
  5. }
其中@FeignClient中指定需要调用的微服务的名称,@RequestMapping中指定访问微服务响应接口的路径,如之前微服务的hello方法是通过"/hello"路径访问,那么这里需要配置一致

4、新建Controller类,为前端提供REST接口
  1. @RestController
  2. public class HelloController {
  3. @Autowired
  4. private IHello iHello;
  5. @RequestMapping(value = "gethello",method = RequestMethod.GET)
  6. public String getHello(){
  7. return iHello.getHello();
  8. }
  9. }

5、配置Feign的配置文件,指定Erureka服务器注册地址和访问端口application.yml
  1. server:
  2. port: 8081
  3. eureka:
  4. client:
  5. serviceUrl:
  6. defaultZone: http://localhost:1000/eureka/

 成功!



null

原创粉丝点击