在微服务中,如何使用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);
相关推荐
喂完待续6 小时前
Apache Hudi:数据湖的实时革命
大数据·数据仓库·分布式·架构·apache·数据库架构
Harvey_D9 小时前
【部署K8S集群】 1、安装前环境准备配置
云原生·容器·kubernetes
曾经的三心草10 小时前
微服务的编程测评系统11-jmeter-redis-竞赛列表
redis·jmeter·微服务
高阳言编程11 小时前
4. 存储体系
架构
Galaxy在掘金11 小时前
从业8年,谈谈我认知的后端架构之路-1
java·架构
天波信息技术分享13 小时前
AI 云电竞游戏盒子:从“盒子”到“云-端-芯”一体化竞技平台的架构实践
人工智能·游戏·架构
k↑15 小时前
微服务之注册中心与ShardingSphere关于分库分表的那些事
数据库·微服务·架构·shardingsphere
Wezzer16 小时前
k8s单master部署
云原生·容器·kubernetes
Tadas-Gao17 小时前
Java设计模式全景解析:从演进历程到创新实践
java·开发语言·微服务·设计模式·云原生·架构·系统架构
斯普信专业组1 天前
Eureka故障处理大汇总
云原生·eureka