【Spring Cloud】基于Feign实现微服务调用

欢迎来到阿Q社区
https://bbs.csdn.net/topics/617897123

什么是Feign

Feign 是 Spring Cloud 提供的一个声明式的伪Http客户端,它使得调用远程服务就像调用本地服务一样简单,只需要创建一个接口并添加一个注解即可。

Nacos 很好的兼容了 Feign,Feign 默认集成了 Ribbon,所以在 Nacos 下使用 Fegin 默认就实现了负载均衡的效果。

Feign的使用

加入Fegin的依赖

<!--fegin组件-->
<dependency>
   <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

在主类上添加Fegin的注解

@SpringBootApplication
@EnableDiscoveryClient
//开启Fegin
@EnableFeignClients
public class OrderApplication {}

使用Feign

创建一个service,并使用Fegin实现微服务调用

//声明调用的提供者的name
@FeignClient("shop-product")
public interface ProductService {

    //指定调用提供者的哪个方法
    //@FeignClient + @GetMapping就是一个完整的请求路径 
    // http://shop-product/product/{pid}
    @GetMapping(value = "/product/{pid}")
    ShopProduct findByPid(@PathVariable("pid") Long pid);
}

修改代码

修改 controller 代码,并启动验证

@Autowired
private ProductService productService;

@GetMapping("/{pid}")
public ShopOrder order(@PathVariable("pid") Long pid) {
	log.info("客户下单,这时候要调用商品微服务查询商品信息。。。");
	//通过fegin调用商品微服务
	ShopProduct product = productService.findByPid(pid);
	log.info("商品信息,查询结果:" + JSON.toJSONString(product));

	log.info("当前用户信息为自己,假设我们设置为1");
	ShopOrder shopOrder = new ShopOrder();
	shopOrder.setUid(1L);
	shopOrder.setUsername("公众号:阿Q说代码");
	shopOrder.setPid(product.getId());
	shopOrder.setPname(product.getPname());
	orderService.save(shopOrder);
	return shopOrder;
}

重启微服务

重启order微服务,查看效果
在这里插入图片描述

总结

到这儿,我们基于 Feign实现微服务调用就结束了。下一篇将为大家带来 Sentinel 微服务容错的文章,敬请期待吧!

后续的文章,我们将继续完善我们的微服务系统,集成更多的Alibaba组件。想要了解更多JAVA后端知识,请点击文末名片与我交流吧。留下您的一键三连,让我们在这个寒冷的东西互相温暖吧!

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阿Q说代码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值