您好,欢迎来到测品娱乐。
搜索
您的当前位置:首页SpringCloud使用openFeign调用服务

SpringCloud使用openFeign调用服务

来源:测品娱乐

Maven依赖

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
     <version>3.0.3</version>
</dependency>
  • 开启openFeign

创建service接口

添加注解: @FeignClient 有三个参数

接口内部方法与要访问的服务controller方法名以及访问路径保持一致.

通过消费端访问其他服务端服务时,关于参数传递的问题:参数需要使用注解@PathVariable(“id”)进行占位设置.
消费端的参数传入可以任意使用rest风格以及url拼接,但是其他服务端一定要通过PathVariable(“id”)来进行占位设置,否则会产生异常.
如果本服务也是一个被调用服务那么Controller传参就一定要使用rest风格的传参方式,使用注解绑定

  //消费端Controller
  public class DataController {
      @Autowired
      PaymentService paymentService;

      @GetMapping("getSuccess")
      public String getSuccess() {
          String success = paymentService.getSuccess();
          return success;
      }

      @GetMapping("getTimeOut")
      public String getTimeOut() {
          return paymentService.getTimeOut();
      }

      //这种是rest风格参数传递
      @GetMapping("getDemo/{id}")
      public String getDemo(@PathVariable("id") String id){
          return paymentService.getDemo(id);
      }
      //这种是通过url拼接参数
      @GetMapping("getDemo1")
      public String getDemo1(String id){
          return paymentService.getDemo1(id);
      }
  }
//要访问服务端的Controller
@RequestMapping("payment/hystrix")
public class DataController {
    @Resource
    PaymentService paymentService;

   @GetMapping("getSuccess")
    public String getSuccess(){
       String success = paymentService.getSuccess();
       return success;
   }

    @GetMapping("getDemo/{id}")
    public String getDemo(@PathVariable("id") String id){
        String success = paymentService.getDemo(id);
        return success;
    }
    @GetMapping("getDemo1/{id}")
    public String getDemo1(@PathVariable("id") String id){
        String success = paymentService.getDemo(id);
        return success;
    }

    @GetMapping("getTimeOut")
    public String getTimeOut(){
       return paymentService.getTimeOut();
   }
}
//对应的Service
@FeignClient(name = "CLOUD-PROVIDER-HYSTRIX-PAYMENT", path = "/payment/hystrix")
public interface PaymentService {
    @GetMapping("getDemo/{id}")
    public String getDemo(@PathVariable("id") String id);

    @GetMapping("getDemo1/{id}")
    public String getDemo1(@PathVariable("id")String id);

    @GetMapping("getSuccess")
    public String getSuccess();

    @GetMapping("getTimeOut")
    public String getTimeOut();
}

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- cepb.cn 版权所有 湘ICP备2022005869号-7

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务