使用openfeign作为微服务之间的相互调用

1 例如当前有微服务a和b,微服务a和b现在都成功注册到服务注册中心nacos,目前需要实现服务a需要调用服务b的需求,实现步骤如下:

服务a引入openfeign的依赖:

<dependency>

<groupId>org.springframework.cloud</groupId>

<artifactId>spring-cloud-starter-openfeign</artifactId>

</dependency>

例如服务b中有个服务如下,a想调用这个服务:

@RequestMapping("/memeber/list")

    public R couponOfMember(){

        CouponEntity entity=new CouponEntity();

        entity.setCouponName("满一百减十元");

        return R.ok().put("coupon",new CouponEntity());

    }

在微服务a中编写一个接口,告诉springcloud这个接口需要调用远程服务

@FeignClient(name ="b" )

public interface CouponFeign {

    @RequestMapping("/shopcoupon/coupon/memeber/list")

    public R couponOfMember();

}

name ="b":b就是微服务b的名字,

  @RequestMapping("/shopcoupon/coupon/memeber/list")请求的地址必须和需要调用的服务的地址一样

接下来在主程序入口使用注解@EnableFeignClients(basePackages ="com.fengbao.shop.shopmember.feign")开启远程服务的调用:

@SpringBootApplication

@MapperScan("com.fengbao.shop.shopmember.dao")

@EnableDiscoveryClient

@EnableFeignClients(basePackages = "com.fengbao.shop.shopmember.feign")

public class ShopMemberApplication {

public static void main(String[] args) {

SpringApplication.run(ShopMemberApplication.class, args);

}

}

最后比如我们需要在服务a的某个controller中需要调用这个服务按如下添加:

@Autowired

private CouponFeign couponFeign;

然后就可以使用couponFeign来调用方法了

posted @ 2021-08-16 22:17  白羽轻飘  阅读(894)  评论(0编辑  收藏  举报