🎈 作者:Linux猿

🎈 简介:CSDN博客专家🏆,华为云享专家🏆,Linux、C/C++、云计算、物联网、面试、刷题、算法尽管咨询我,关注我,有问题私聊!

🎈 欢迎小伙伴们点赞👍、收藏⭐、留言💬


目录

一、准备工作

1.1 下载代码

1.2 运行代码

二、集成 feign 调用

2.1 添加依赖

2.2 添加接口

2.3 添加调用

三、运行


本篇文章主要介绍在 SpringCloud 集成 nacos 基础上,再集成 feign。

一、准备工作

1.1 下载代码

在之前的文章中我们已经集成了 nacos 和 gateway,本篇文章使用之前的集成代码,再集成 feign 实例,先将之前的代码克隆下来,然后运行测试一下。

$ git clone https://gitee.com/linux-ape/spring-cloud-demo.git

上面是通过 git 工具下载代码,然后切换分支到 gateway 上,如下所示。

$ git checkout -b feignNew remotes/origin/gateway

1.2 运行代码

代码结构如下所示。

图1 代码结构

 通过 IDEA 运行,运行结果如下。

图1 服务 serviceone 运行正常

 

图2 服务 servicetwo 运行正常

 

二、集成 feign 调用

下面开始介绍 feign 的调用,通过服务 ServiceOne 调用 ServiceTwo 内的接口。

2.1 添加依赖

在 ServiceOne 服务 pom.xml 文件中添加 feign 调用依赖。

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>

2.2 添加接口

添加 package feign,添加接口文件 ServiceFeignClient.java,如下所示。

 其中,ServiceFeignClient.java 文件内容如下所示。

package com.example.serviceone.feign;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;


@FeignClient(value="servicetwo")  // servicetwo 调用服务的名称
public interface ServiceFeignClient {
    @GetMapping("/index2")        // 调用服务的路径
    public String ServiceTwo();   // 调用服务的接口
}

2.3 添加调用

在 controller 下的 ServiceOneController.java 中添加调用,文件内容如下。

package com.example.serviceone.controller;

import com.example.serviceone.feign.ServiceOneFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ServiceOneController {
    @GetMapping("/index1")
    public String ServiceOne() {
        return "ServiceOne Service";
    }

    @Autowired
    ServiceOneFeignClient serviceOneFeignClient;

    @GetMapping("/feign")
    public String getServiceTwo() {
        return serviceOneFeignClient.ServiceTwo();
    }
}

在启动类 ServiceOneApplication.java 文件中添加如下注解。

@EnableFeignClients
@EnableDiscoveryClient

三、运行

通过服务 ServiceOne  feign 路径调用,显示调用的是服务 ServiceTwo 内的函数,调用成功!


 

参考链接:

SpringCloud Demo: 微服务实例

33-SpringBoot整合Nacos和Feign演示_哔哩哔哩_bilibili 


🎈 感觉有帮助记得「一键三连支持下哦!有问题可在评论区留言💬,感谢大家的一路支持!🤞猿哥将持续输出「优质文章回馈大家!🤞🌹🌹🌹🌹🌹🌹🤞


Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐