分布式组件-SpringCloud-OpenFeign远程调用教程
注: 承接上文 springboot集成nacos,将微服务模块注册到nacos后,进行微服务模块之间的调用
springboot集成nacos:
https://blog.csdn.net/weixin_44205136/article/details/131093124?spm=1001.2014.3001.5501
1.在互相调用的微服务模块中导入openfeign依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
2.开启@EnableFeignClients 功能
// 开启远程调用功能
@EnableFeignClients(basePackages = "编写远程调用接口的包路径")
// 开启服务注册发现功能
@EnableDiscoveryClient
@MapperScan("a.b.c.dao")
@SpringBootApplication
public class TestOpenFeignApplication {
public static void main(String[] args) {
SpringApplication.run(TestOpenFeignApplication .class, args);
}
}
3.编写接口,进行远程调用
被调用的服务代码
@GetMapping("/member/list")
public R memberCoupons() {
CouponEntity coupon = new CouponEntity();
coupon.setCouponName("满20减10");
return R.ok().put("coupons", Arrays.asList(coupon));
}
远程调用接口
/**
* 这是一个声明式的远程调用
* gulimall-coupon -> 被调用的微服务模块名
*/
@FeignClient("gulimall-coupon")
public interface CouponFeignService {
@GetMapping("/coupon/coupon/member/list")
public R memberCoupons();
}
服务调用者的代码
@Autowired
private CouponFeignService couponFeignService;
@GetMapping("/coupons")
public R testOpenFeign() {
MemberEntity member = new MemberEntity();
member.setNickname("张三");
R memberCouponMap = couponFeignService.memberCoupons();
return R.ok().put("member", member).put("coupons", memberCouponMap.get("coupons"));
}