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));
}
}