SpringCloud nacos 集成 feign 实例


🎈 作者: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 


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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Linux猿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值