• Spring Cloud Alibaba-OpenFign实现服务调用


    一、什么是OpenFeign

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

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

    二、OpenFeign的使用

    1.导入openfeign的依赖

    1. <dependency>
    2. <groupId>org.springframework.cloudgroupId>
    3. <artifactId>spring-cloud-starter-openfeignartifactId>
    4. dependency>

    2.在主启动类上开启OpenFeign注解

    @EnableFeignClients//开启openfeign注解

    3.创建feign的接口

    1. package com.gsh.order.feign;
    2. import com.gsh.util.CommonResult;
    3. import org.springframework.cloud.openfeign.FeignClient;
    4. import org.springframework.web.bind.annotation.GetMapping;
    5. import org.springframework.web.bind.annotation.PathVariable;
    6. @FeignClient(value = "springcloud-product")//被调用的微服务的名称
    7. public interface ProductFeign {
    8. //被调用的方法
    9. @GetMapping("/product/findById/{pid}")
    10. public CommonResult findById(@PathVariable Integer pid);
    11. }

    4.修改controller代码

    (1)注入feign接口

    1. @Autowired
    2. private ProductFeign productFeign;

    (2)使用注入的feign调用接口中的方法

    1. //这里直接使用productFeign调用接口中的方法,和我们原来controller调用service一样啊
    2. CommonResult byId = productFeign.findById(pid);
    3. JSONObject jsonObject=JSONObject.fromObject(byId.getData());
    4. System.out.println(jsonObject);
    5. Product product = (Product) JSONObject.toBean(jsonObject, Product.class);

    5.重启服务即可

  • 相关阅读:
    语雀/markdown文档编写常用快捷键
    前端跨域问题的解决思路
    微服务网关API Geteway
    epoll与非阻塞
    GitHub开源项目精选:用React、TypeScript和Framer Motion复刻MacOS桌面
    Shiro介绍及解析
    【pytorch记录】自动混合精度训练 torch.cuda.amp
    Vue3的7种和Vue2的12种组件通信
    自学 TypeScript 第五天,手把手项目搭建 TS 篇
    sleuth+zipkin持久化和gateway设置跨域
  • 原文地址:https://blog.csdn.net/Have_MonkeyG/article/details/126472028