12.Spring-Cloud-Feign初探

   在微服务架构中客户端负载均衡和断路器保护,作为基础工具类框架广泛的应用在各个微服务的实现中,不仅包括我们自身的业务服务类,也包括一些基础设施类微服务,那么是否有更高层次的封装来整合这两个基础工具以简化开发。

    Feign是Netflix开发的声明式、模板化的HTTP客户端,Netflix Feign整合了Spring Cloud Ribbon与Spring Cloud Hystrix,除了提供这两者强大功能之外,它还提供了一种声明式的web服务端定义方式。

   在Spring Cloud中使用Feign非常简单,只需创建一个接口,并在接口上添加一个注解代码就完成了。Feign支持多种注解,如Fegin自带注解或者JAX-RS注解等。

   Spring Cloud对Feign进行了增强,使用Feign支持了Spring MVC注解,并整合了Ribbon和Eureka,从而上Feign的使用更加方便。

    注册中心

      注册中心之前的博文已经实现,不在过多强调
   

服务提供者    

 

修改controller     

 


   
   
   
   
  1.       /**
  2. * 不接收参数
  3. * @return
  4. */
  5. @RequestMapping(value = "/hello1", method = RequestMethod.GET)
  6. public String hello() {
  7. return "hello spring cloud";
  8. }
  9. /**
  10. * 接收单个参数
  11. * @param name
  12. * @return
  13. */
  14. @RequestMapping(value = "/hello2", method = RequestMethod.GET)
  15. public String hello1( @RequestParam String name) {
  16. return  "hello "+name;
  17. }
  18. /**
  19. * 参数用对象封装,请求为Post请求
  20. * @param user
  21. * @return
  22. */
  23. @RequestMapping(value = "/hello3", method = RequestMethod.POST)
  24. public String hello1( @RequestBody User user) {
  25. return  "hello "+user.getUsername()+ " "+user.getPhone();
  26. }


修改entity


   
   
   
   
  1. package com.niugang.controller.entity;
  2. import java.io.Serializable; 
  3. /**
  4.  * 用户实体
  5.  * 
  6.  * @author niugang
  7.  *
  8.  */
  9. public class User implements Serializable {
  10. private static final long serialVersionUID = 1L;
  11. private Integer id;
  12. private String username;
  13. private String phone;
  14. private int  randNum;
  15. //
  16. public User() {
  17. super();
  18. }
  19. public User(Integer id, String username, String phone) {
  20. super();
  21. this.id = id;
  22. this.username = username;
  23. this.phone = phone;
  24. }
  25. public Integer getId() {
  26. return id;
  27. }
  28. public void setId(Integer id) {
  29. this.id = id;
  30. }
  31. public String getUsername() {
  32. return username;
  33. }
  34. public void setUsername(String username) {
  35. this.username = username;
  36. }
  37. public String getPhone() {
  38. return phone;
  39. }
  40. public void setPhone(String phone) {
  41. this.phone = phone;
  42. }
  43. public int getRandNum() {
  44. return randNum;
  45. }
  46. public void setRandNum(int randNum) {
  47. this.randNum = randNum;
  48. }
  49. }


      pom.xml
    服务消费者(Feign版)

     


   
   
   
   
  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2. xsi:schemaLocation= "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  3. <modelVersion>4.0.0 modelVersion>
  4. <groupId>902.spring-cloud-feign-consumer groupId>
  5. <artifactId>feign-consumer artifactId>
  6. <packaging>jar packaging>
  7. <version>0.0.1-SNAPSHOT version>
  8. <name>spring-cloud Maven Webapp name>
  9. <url>http://maven.apache.org url>
  10. <parent>
  11. <groupId>org.springframework.boot groupId>
  12. <artifactId>spring-boot-starter-parent artifactId>
  13. <version>1.5.2.RELEASE version>
  14. <relativePath />
  15. parent>
  16. <properties>
  17. <project.build.sourceEncoding>UTF-8 project.build.sourceEncoding>
  18. <project.reporting.outputEncoding>UTF-8 project.reporting.outputEncoding>
  19. <java.version>1.8 java.version>
  20. <spring-cloud.version>Dalston.RELEASE spring-cloud.version>
  21. properties>
  22. <dependencies>
  23. <dependency>
  24. <groupId>org.springframework.boot groupId>
  25. <artifactId>spring-boot-starter-web artifactId>
  26. dependency>
  27. <dependency>
  28. <groupId>org.springframework.cloud groupId>
  29. <artifactId>spring-cloud-starter artifactId>
  30. dependency>
  31. <dependency>
  32. <groupId>org.springframework.cloud groupId>
  33. <artifactId>spring-cloud-starter-eureka artifactId>
  34. dependency>
  35. <dependency>
  36. <groupId>org.springframework.boot groupId>
  37. <artifactId>spring-boot-starter-test artifactId>
  38. <scope>test scope>
  39. dependency>
  40. <dependency>
  41. <groupId>org.springframework.cloud groupId>
  42. <artifactId>spring-cloud-starter-feign artifactId>
  43. dependency>
  44.           dependencies>
  45. <dependencyManagement>
  46. <dependencies>
  47. <dependency>
  48. <groupId>org.springframework.cloud groupId>
  49. <artifactId>spring-cloud-dependencies artifactId>
  50. <version>${spring-cloud.version} version>
  51. <type>pom type>
  52. <scope>import scope>
  53. dependency>
  54. dependencies>
  55. dependencyManagement>
  56. <build>
  57. <plugins>
  58. <plugin>
  59. <groupId>org.springframework.boot groupId>
  60. <artifactId>spring-boot-maven-plugin artifactId>
  61. plugin>
  62. plugins>
  63. build>
  64. project>


启动类


   
   
   
   
  1. package com.niugang;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
  5. import org.springframework.cloud.netflix.feign.EnableFeignClients;
  6. /**
  7.  * feign版消费者
  8.  * 
  9.  * @author niugang
  10.  *
  11.  */
  12. @SpringBootApplication
  13. @EnableDiscoveryClient
  14. //扫描声明它们是feign客户端的接口(通过@FeignClient)
  15. @EnableFeignClients
  16. public class Application {
  17. public static void main(String[] args) {
  18. SpringApplication.run(Application.class, args);
  19. }
  20. }

      

配置


   
   
   
   
  1. #指定微服务的名称后续在调用的时候只需要使用该名称就可以进行服务的访问
  2. spring.application.name=feign-consumer
  3. server.port= 9001
  4. #注册中心地址
  5. eureka.client.serviceUrl.defaultZone=http: //testhost:8000/eureka/


entity 

   实体类配置和上面服务提供者一样    

  controller


   
   
   
   
  1. package com.niugang.controller;
  2. import org.slf4j.Logger;
  3. import org.springframework.beans.factory. annotation.Autowired;
  4. import org.springframework.web.bind. annotation.PathVariable;
  5. import org.springframework.web.bind. annotation.RequestMapping;
  6. import org.springframework.web.bind. annotation.RequestMethod;
  7. import org.springframework.web.bind. annotation.RestController;
  8. import com.niugang.entity.User;
  9. import com.niugang.service.ServiceProvide;
  10. @RestController
  11. public class ComputeController {
  12. private final Logger logger = org.slf4j.LoggerFactory.getLogger(ComputeController. class);
  13. @Autowired
  14. private ServiceProvide serviceProvide;
  15.     /**
  16.      * 无参数调用
  17.      * @return
  18.      */
  19. @RequestMapping(value = "/feign-consumer", method = RequestMethod.GET)
  20. public String feign() {
  21. logger.info( "start invoke sevice provide");
  22. return serviceProvide.hello1();
  23. }
  24.     
  25. @RequestMapping(value = "/feign-consumer1/{name}", method = RequestMethod.GET)
  26. public String feign1( @PathVariable String name) {
  27. logger.info( "start invoke sevice provide");
  28. return serviceProvide.hello2(name);
  29. }
  30. @RequestMapping(value = "/feign-consumer2/{username}/{phone}", method = RequestMethod.GET)
  31. public String feign2( @PathVariable String username, @PathVariable String phone) {
  32. logger.info( "start invoke sevice provide");
  33. User user = new User();
  34. user.setUsername(username);
  35. user.setPhone(phone);
  36. return serviceProvide.hello3(user);
  37. }
  38. }


调用服务接口类   


   
   
   
   
  1. package com.niugang.service;
  2. import org.springframework.cloud.netflix.feign.FeignClient;
  3. import org.springframework.web.bind. annotation.RequestBody;
  4. import org.springframework.web.bind. annotation.RequestMapping;
  5. import org.springframework.web.bind. annotation.RequestMethod;
  6. import org.springframework.web.bind. annotation.RequestParam;
  7. import com.niugang.entity.User;
  8. /**
  9.  * 定义服务绑定接口
  10.  * @author Administrator
  11.  *
  12.  */
  13. //声明调用的服务
  14. @FeignClient(value="service-provide",fallback=ServiceProvideFallback.class)
  15. public interface ServiceProvide {
  16. /**
  17. * 调用服务的路径,不传参数
  18. * @return
  19. */
  20.     @RequestMapping(value="/hello1",method = RequestMethod.GET)
  21. String  hello1();
  22.     /**
  23.      * 
  24.      * 传递一个参数
  25.      */
  26.     @RequestMapping(value="/hello2",method = RequestMethod.GET)
  27.     //@RequestParam里面一定要写参数名,否则读取不到
  28.   String  hello2( @RequestParam("name") String name);
  29.     /**
  30.      * 传递参数对象,这个需要Post请求
  31.      * @return
  32.      */
  33.     @RequestMapping(value="/hello3",method = RequestMethod.POST)
  34.   String  hello3( @RequestBody User user);
  35. }


 调用降级类

Spring Cloud Fegin在定义服务客户端的时候与Spring Cloud Ribbon有很大的差别,HystrixCommand定义被封装起来了。不能在像Spring Cloud Hystrix那样,通过@HystrixCommand注解的fallback参数那样来定义服务的降级。 Spring Cloud Fegin提供了一种更方便的做法具体如下:

 服务降级逻辑的实现只需要为Feign客户端的定义接口编写一个具体的接口实现类


   
   
   
   
  1. package com.niugang.fallback;
  2. import org.springframework.stereotype.Component;
  3. import com.niugang.entity.User;
  4. import com.niugang.service.ServiceProvide;
  5. /**
  6.  * 
  7.  * 服务降级
  8.  * @author niugang
  9.  *
  10.  */
  11. @Component
  12. public class ServiceProvideFallback implements ServiceProvide {
  13. @Override
  14. public String hello1() {
  15. return "服务器内部异常1";
  16. }
  17. @Override
  18. public String hello2(String name) {
  19. return "服务器内部异常2";
  20. }
  21. @Override
  22. public String hello3(User user) {
  23. return "服务器内部异常3";
  24. }
  25. }

测试

 

   启动注册中心,启动服务提供者,启动服务调用者

输入:http://localhost:9001/feign-consumer

输入:http://localhost:9001/feign-consumer1/zhangsan

输入:http://localhost:9001/feign-consumer2/zhangsan/15094031789

你可能感兴趣的:(java,springcloud)