OpenFeign远程调用

一、引入open-feign

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

二、在被调用的微服务的Controller编写一个测试方法。(gulimall-coupon 优惠卷服务)

@RequestMapping("/coupon/coupon/member/list")
public R memberCoupons(){ 
    CouponEntity couponEntity = new CouponEntity();
    couponEntity.setCouponName("买一送一");
    System.out.println("测试OpenFeign远程调用服务");
    return R.ok().put("coupons",couponEntity);
}

三、在需要调用其他微服务的微服务里编写一个接口,告诉SpringCloud这个接口需要调用远程服务,声明接口的每一个方法都是调用哪个远程服务的哪个请求。(gulimall-member 会员服务)

1.先新建一个包专门用于存放远程调用接口。
/src/main/java/com/atguigu/gulimall/member/feign

2.接口上需加@FeignClient(“gulimall-coupon”)注解,表示这个接口属于一个远程客户端,并且表明这是哪个微服务的远程调用。
(注意,接口内的方法路径必须是远程调用方法的全路径)

package com.atguigu.gulimall.member.feign;

import com.atguigu.common.utils.R;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;

@FeignClient("gulimall-coupon")
public interface CouponFeignService {
    @RequestMapping("/coupon/coupon/member/list")
    public R memberCoupons();
}

四、开启远程调用功能(主启动类)

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

在这里插入图片描述
五、测试OpenFeign远程调用服务
1.在会员服务里的Controller编写一个测试方法。

@Autowired
CouponFeignService couponFeignService;

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

2.同时启动会员服务和优惠券服务,访问http://localhost:8000/member/member/test
过程:这个路径的方法里调用了CouponFeignService 里面的memberCoupons方法,这个方法是一个FeignClient 是一个声明式远程调用到优惠券服务里的memberCoupons方法。
(如果被调用的远程服务没有开启或是掉线了,再进行远程调用,就会出现连接超时异常)
在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值