(二)SpringCloud-Alibaba-OpenFeign远程服务调用

使用OpenFeign作为远程服务调用

1. Feign介绍

  通过RestTemplate调用其它服务的API时,所需要的参数须在请求的URL中进行拼接,如果参数少的话或许我们还可以忍受,一旦有多个参数的话,这时拼接请求字符串就会效率低下

  Feign是一个声明式的Web Service客户端,它的目的就是让Web Service调用更加简单。Feign提供了HTTP请求的模板,通过编写简单的接口和插入注解,就可以定义好HTTP请求的参数、格式、地址等信息。

  而Feign则会完全代理HTTP请求,我们只需要像调用方法一样调用它就可以完成服务请求及相关处理。Feign整合了Ribbon负载均衡Hystrix服务熔断,可以让我们不再需要显式地使用这两个组件。

 Feign具有如下特性:

  支持可插拔的HTTP编码器和解码器;
  支持Hystrix和它的Fallback;
  支持Ribbon的负载均衡;
  支持HTTP请求和响应的压缩。
  有点像我们springmvc模式的Controller层的RequestMapping映射。这Feign是用@FeignClient来映射服务的。

2. Feign的使用

实现案例:在会员服务中通过nacos服务注册中心远程调用优惠券服务

 

 

 

 2.1、引入open-feign

<dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

2.2、编写一个接口,告诉springCloud这个接口需要远程调用  


  1)、在优惠券服务中编写如下接口服务:

@RequestMapping("/member/list")
    public R memberCoupons(){
        CouponEntity coupon = new CouponEntity();
        coupon.setCouponName("满1000减200");
        return R.ok().put("coupons",Arrays.asList(coupon));
    }

 

2.3、在会员模块中新建feign文件包,创建CouponFeignService接口:优惠券远程调用服务。

     1)、接口服务使用注解@FeignClient,注解中的值为nacos中微服务的名称,用于服务发现

  2)、声明接口的每一个方法都是调用某个服务的请求

      注意:RequestMapping中的请求路径为该服务的全路径

@FeignClient("ttmall-coupon")
public interface CouponFeignService {

    @RequestMapping("/coupon/coupon/member/list")
    public R memberCoupons();
}

 

 

 

2.4、在会员模块中的启动类开启远程调用功能 @EnableFeignClients

   basePackages中值为feign包的路径

@EnableFeignClients(basePackages="com.agentliu.ttmall.member.feign")

 

 

 

 2.5、在会员模块中编写测试类调用会员服务的远程服务

@Autowired
    CouponFeignService couponFeignService;

    @RequestMapping("/coupons")
    public R getMemberCoupon(){
        MemberEntity  memberEntity = new MemberEntity();
        memberEntity.setUsername("张三");
        R coupon = couponFeignService.memberCoupons();
        return R.ok().put("member",memberEntity).put("coupon",coupon.get("coupons"));
    }

 

 

 

 2.6、启动会员服务、优惠券服务,在浏览器中请求刚才编写的会员测试方法

http://localhost:8000/member/member/coupons

 

 

posted @ 2022-03-25 11:46  LZ1024  阅读(170)  评论(0编辑  收藏  举报