在微服务中,如何使用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);
相关推荐
zandy10115 小时前
Agentic BI 架构实战:当AI Agent接管数据建模、指标计算与可视化全链路
人工智能·架构
薪火铺子7 小时前
微服务认证方案对比与选型
微服务·云原生·架构
运维全栈笔记8 小时前
K8S部署Redis高可用全攻略:1主2从3哨兵架构实战
redis·docker·云原生·容器·架构·kubernetes·bootstrap
AI攻城狮9 小时前
AI Agent 从上线到删库跑路始末
云原生
weixin_4462608510 小时前
城市智能化的底层基石:基于腾讯地图服务生态的移动定位与导航架构指引
大数据·人工智能·架构
@#¥&~是乱码鱼啦12 小时前
Spring分层架构:Controller、Service、Mapper数据链路,IOC的真实工作意义
java·spring·架构
vortex512 小时前
SafeLine 雷池WAF 真实体验,谈谈架构与原理
架构
该昵称用户已存在13 小时前
MyEMS 开源能源管理系统:模块化架构赋能精细化能源管控
架构·开源·能源
Ulyanov13 小时前
《现代 Python 桌面应用架构实战:PySide6 + QML 从入门到工程化》 开发环境搭建与工具链极简主义 —— 拒绝臃肿,构建工业级基座
开发语言·python·qt·ui·架构·系统仿真
郭龙_Jack13 小时前
Kubernetes 架构一张图讲透
架构