open-feign远程调用服务

1、引入open-feign依赖

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

2、编写一个接口,告诉springcloud这个接口需要调用远程接口 申明接口的每一个方法都是调用哪个远程服务的那个请求 说明: ①、“cfgmall-coupon"为提供者注册到注册中心的服务名称 ②、 @RequestMapping(”/coupon/coupon/member/list") public R membercoupons(); 为提供服务的方法的完整签名

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* 这是一个声明式的远程调用
*/
@FeignClient("cfgmall-coupon")
public interface CouponFeignService {
          
   

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

}

3、开启远程调用功能

/**
* 1、想要远程调用别的服务
* 1)、引入open-feign
* 2)、编写一个接口,告诉SpringCloud这个接口需要调用远程服务
*   1、声明接口的每一个方法都是调用哪个远程服务的那个请求
* 3)、开启远程调用功能   (basePackages = "com.cfg.cfgmall.member.feign") 为接口包
*/
@EnableFeignClients(basePackages = "com.cfg.cfgmall.member.feign")
@EnableDiscoveryClient
@SpringBootApplication
public class CfgmallMemberApplication {
          
   

    public static void main(String[] args) {
          
   
        SpringApplication.run(CfgmallMemberApplication.class, args);
    }

}

4、调用

/**
* 会员
*
*/
@RestController
@RequestMapping("member/member")
public class MemberController {
          
   

    @Autowired
    CouponFeignService couponFeignService;

    @RequestMapping("/coupons")
    public R test(){
          
   
        MemberEntity memberEntity = new MemberEntity();
        memberEntity.setNickname("张三");

        R membercoupons = couponFeignService.membercoupons();
        return R.ok().put("member",memberEntity).put("coupons",membercoupons.get("coupons"));
    }
}

5、服务提供方

/**
* 优惠券信息
*/
@RefreshScope
@RestController
@RequestMapping("coupon/coupon")
public class CouponController {
          
   
    @Autowired
    private CouponService couponService;


    @RequestMapping("/member/list")
    public R membercoupons(){
          
   
        CouponEntity couponEntity = new CouponEntity();
        couponEntity.setCouponName("满100减10");
        return R.ok().put("coupons",Arrays.asList(couponEntity));
    }
}
经验分享 程序员 微信小程序 职场和发展