在微服务中,如何使用feign在各个微服务中进行远程调用

在微服务中,如何使用feign在不同微服务中进行远程调用

在微服务中,如何使用feign在不同微服务中进行远程调用

步骤:

第一步:

引入feign依赖

xml 复制代码
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

这里没有指定版本号是因为...中的spring-cloud指定了版本号,如下

xml 复制代码
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

第二步:在启动类中添加@EnableFeignClients注解

java 复制代码
@EnableFeignClients //开启远程调用
@SpringBootApplication
public class Application {

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

}

第三步:编写远程调用接口。现search服务需要调用product服务下/product/attr/info/{attrId}路径下的方法,该被调用的方法为:

java 复制代码
    @RequestMapping("/product/attr/info/{attrId}")
    public R info(@PathVariable("attrId") Long attrId){

        AttrRespVo respVo = attrService.getAttrInfo(attrId);

        return R.ok().put("attr", respVo);
    }

那么在search服务中编写的接口如下:我们需要保证接口中的方法与product中被调用的方法,方法名可以不同,但是他们的参数返回值类型请求路径要一致。接口方法发送get请求.

java 复制代码
@FeignClient(name = "product",url = "http://localhost:10000")
public interface ProductFeignService {
@GetMapping("/product/attr/info/{attrId}")
    public R attrInfo(@PathVariable("attrId") Long attrId);

}

第四步:在业务中远程调用,如下:

java 复制代码
@Autowired 
ProductFeignService productFeignService;

// 远程调用
Long attrId=1;
R r = productFeignService.attrInfo(attrId);
相关推荐
学渣超1 小时前
从一次早高峰数据库告警说起:你真的理解缓存该如何落地应用吗?
redis·后端·架构
KIDULT°1 小时前
Docker 从 0 入门|吃透容器生态、架构与 Dockerfile 实战
docker·容器·架构
风123456789~1 小时前
【架构专栏】8.2-8.3 系统架构评估、ATAM评估实践
架构
Runwise创新社区2 小时前
Anthropic多智能体架构怎么落地?Lead Agent、共享记忆与并行任务的设计边界
人工智能·架构·多智能体
海宇数据2 小时前
零信任架构实战:基于海宇对外投资历史查询服务构建自动化异动企业筛查网关
运维·人工智能·架构·自动化
Brilliantwxx2 小时前
【STM32】 I2C协议和设备主从( 图解 + 面试题 )
stm32·单片机·嵌入式硬件·架构
QQ_21696290962 小时前
基于微服务架构的店铺管理系统的设计与实现
大数据·spring boot·后端·spring·微服务·小程序·架构
头茬韭菜11 小时前
第 1 篇:「Glass-Box 的骨架」——全景架构与六层数据流水线
架构·agent·semantica
奔跑的架构师13 小时前
[A-50]ARMv9/v8-DVFS系统架构
linux·arm开发·架构·系统架构·arm
闲云自留地13 小时前
动手玩 Nova:Hypervisor、主机聚合、可用分区、虚拟机生命周期实操
运维·架构·openstack