在微服务中,如何使用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);
相关推荐
songjxin8 小时前
离线部署kubernetes v1.34.3
云原生·容器·kubernetes
Loo国昌9 小时前
Vue 3 前端工程化:架构、核心原理与生产实践
前端·vue.js·架构
tap.AI9 小时前
RAG系列(一) 架构基础与原理
人工智能·架构
The Open Group9 小时前
架构:不仅仅是建模,而是一种思维
架构
阿里云云原生10 小时前
Android App 崩溃排查实战:如何利用 RUM 完整数据与符号化技术定位问题?
android·阿里云·云原生·rum
Solar202511 小时前
TOB企业智能获客新范式:基于数据驱动与AI的销售线索挖掘与孵化架构实践
人工智能·架构
熊出没12 小时前
Kubernetes 实操命令大全
云原生·容器·kubernetes
阿里云云原生12 小时前
深度解析云监控 2.0 日志审计:统一采集、实体建模与告警溯源能力
阿里云·云原生·云监控·可观测
winfield82112 小时前
关于工程实践的面试问题
微服务·面试