springboot整合springcloud之feign

服务调用之OpenFeign

一、项目操作

1.引入依赖

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

2.明确分工

明确谁作为服务的消费者,谁作为服务的提供者,这里场景是用户和优惠券,用户作为优惠券的消费者,厂家作为优惠券的提供者。

3.提供者提供具体的服务方法

@RequestMapping("/member/list")
public R membercoupons(){
          
   
    CouponEntity couponEntity = new CouponEntity();
    couponEntity.setCouponName("满100减10");
    return R.ok().put("coupons",Arrays.asList(couponEntity));
}

4.消费者注册申请服务的接口

1是配置文件里的application-name,也就是服务的名字。 2是刚才定义的服务者方法的前两行,直接复制过来。

5.消费者使用接口调用提供者的服务

@Autowired
CounponFeignService counponFeignService;
@RequestMapping("/coupons")
public R test(){
          
   
    MemberEntity memberEntity = new MemberEntity();
    memberEntity.setNickname("张三");
    R membercoupons = counponFeignService.membercoupons();
    return R.ok().put("member",memberEntity)
            .put("coupons",membercoupons.get("coupons"));
}

6.消费者添加注解

@EnableFeignClients(basePackages = "com.atguigu.gulimall.member.feign")

后面是接口类的包名全类名。注解大概不加也行,那就得加@service到接口上注入到IOC容器。

二、检验

三、对比dubbo

dubbo:接口是共有的,在项目公有子模块里。提供者继承接口,提供实现类。消费者直接注入接口,调用就可以了。提供者的配置文件里记录提供服务的接口,一个服务可以多个接口提供(负载均衡)。一个接口当然也可以有多个实现类,可以手工选择。

经验分享 程序员 微信小程序 职场和发展