FeignClient相关

来源:互联网 发布:网络视频广告数据分析 编辑:程序博客网 时间:2024/06/01 16:17

使用FeignClient实现简单的Restful调用,FeignClient只是对于Client的访问封装。不需要对服务端做出修改。

使用前提:

 springboot 

实现步骤:

Step 1. 加入jar以来,使用maven,加入如下以来:


    <dependency>
          <groupId>org.springframework.cloud</groupId>
          <artifactId>spring-cloud-starter-feign</artifactId>
          <version>${spring.cloud.version}</version>
      </dependency>
      <dependency>
          <groupId>org.springframework.cloud</groupId>
          <artifactId>spring-cloud-netflix-core</artifactId>
          <version>${spring.cloud.version}</version>

     </dependency>

//下面依赖可选,因为使用spring boot,指定容器类型

   <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-core</artifactId>
            <version>8.5.20</version>
            <scope>test</scope>
      </dependency>


Step 2: 客户端application.yml中指定服务端配置

application.yml配置,服务名称定义:
    服务端名称在application.yml中定义,格式如下:
  servername:
    ribbon:
   listOfServers: localhost:22222
//  需要指定超时,否则会出现超时错误
  hystrix:
    command:
   default:
     execution:
    timeout:
      enabled: false

Step 3: 加入注解:
   客户端接口实现注解
 @FeignClient("指向的服务端名称"); 服务端名称在application.yml中定义
 
Application启动类注解:
  @EnableFeignClients, 例如下:扫描包范围
  @EnableFeignClients(basePackages = ("com.joe.fan.api.feignclient"))
     
    服务端接口实现类注解:
  @RestController
  @Service
  @RequestMapping
    被调用接口实现类方法注解:
    @RequestMapping(value="/{id}", method= RequestMethod.GET)
   
    被调用接口实现类方法入参注解:
  @RequestBody 服务接口实现,需要加入注解,例:
  public String sendMessage (@RequestBody MsgSendRequest request)



原创粉丝点击