SpringCloud Feign声明式远程调用

 

1. Feign声明式远程调用

1. 简介

Feign是一个声明式的HTTP客户端,它的目的就是让远程调用更加简单。Feign 提供了HTTP请求的模板,通过编写简单的接口和插入注解,就可以定义好HTTP请求的参数、格式、地址等信息。
Feign 整合了Ribbon(负载均衡)和Hystrix(服务熔断),可以让我们不再需要显式地使用这两个组件。
SpripgCloudFeign 在NetflixFeign的基础上扩展了对SpringMVc注解的支持,在其实现下,我们只需创建一个接口并用往解的方式来配置它,即可完成对服务提供方的接口绑定。简化了SpringcloudRibbon 自行封装服务调用客户端的开发量。

2. 使用

2.1 引入依赖

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

2.2 开启feign功能

@EnableFeignClients(basePackages = "com.zx.zxmall.member.feign")

package com.zx.zxmall.member;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;

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

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

}

2.3 声明远程接口

package com.zx.zxmall.member.feign;

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

//这是一个声明式的远程调用
@FeignClient("zxmall-coupon")
public interface CouponFeignService {

    @RequestMapping("/coupon/coupon/member/list")
    public R membercoupons();
}
@RestController
@RequestMapping("member/member")
public class MemberController {
    @Autowired
    private MemberService memberService;

    @Autowired
    CouponFeignService couponFeignService;

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

        R membercoupons = couponFeignService.membercoupons();
        return R.ok().put("member",memberEntity).put("coupons",membercoupons.get("coupons"));
    }
}
@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));
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值