SpringCloud:Feign实现微服务之间相互请求

上篇文章说了通过RestTemplate实现微服务之间访问,这篇文章将通过Feign实现微服务之间访问。 代码基于RestTemplate实现微服务之间访问基础上进行修改。

🍀Feign简介

Github:github.com/OpenFeign/f...

Feign是Netflix开发的声明式、模板化的HTTP客户端, Feign可以帮助我们更快捷、优雅地实现微服务之间的调用。 1.Feign可帮助我们更加便捷,优雅的调用HTTP API。 2.在SpringCloud中,使用Feign非常简单------创建一个接口,并在接口上添加一些注解,代码就完成了。 3.Feign支持多种注解,例如Feign自带的注解或者JAX-RS注解等。 4.SpringCloud对Feign进行了增强,使Feign支持了SpringMVC注解,并整合了Ribbon和Eureka,从而让Feign的使用更加方便。

🍀Spring Cloud 组件依赖版本

官网文档:github.com/alibaba/spr...

本文参考使用组件依赖如下

🍀Feign实现服务之间访问

创建微服务项目,结构如下图所示

root pom.xml

java 复制代码
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.ber</groupId>
    <artifactId>SpringCloud-Feign</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>pom</packaging>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.12.RELEASE</version>
        <relativePath/>
    </parent>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <java.version>1.8</java.version>
        <spring-boot.version>2.3.12.RELEASE</spring-boot.version>
        <spring-cloud-alibaba.version>2.2.8.RELEASE</spring-cloud-alibaba.version>
        <spring-cloud.version>Hoxton.SR12</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-bootstrap</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>${spring-cloud-alibaba.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <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>

    <modules>
        <!-- 注册中心 -->
        <module>ber-nacos</module>
    </modules>

</project>

ber-nacos pom.xml

java 复制代码
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>SpringCloud-Feign</artifactId>
        <groupId>com.ber</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>ber-nacos</artifactId>
    <packaging>pom</packaging>

    <modules>
        <module>nacos-consumer</module>
        <module>nacos-provider</module>
        <module>nacos-consumer-feign</module>
    </modules>
</project>

☘创建nacos-consumer-feign微服务

nacos-consumer-feign pom.xml

java 复制代码
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>ber-nacos</artifactId>
        <groupId>com.ber</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>nacos-consumer-feign</artifactId>


    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <!-- 负载均衡 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-loadbalancer</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <!-- feign -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
    </dependencies>

</project>

application.properties

java 复制代码
spring.application.name=nacos-consumer-feign

spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848

server.port=8895

feign.hystrix.enabled=true

启动类,注意添加注解@EnableFeignClients、@EnableDiscoveryClient

java 复制代码
package com.ber.nacos.feign;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;

/**
 * @author: ber
 * @date: 2022/6/25 0025 22:43
 * -------------------------------
 * Github:https://github.com/berbai
 * Blog:https://blog.csdn.net/Ber_Bai
 */
@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
public class FeignApplication {
    public static void main(String[] args) {
        SpringApplication.run(FeignApplication.class, args);
    }
}

controller接口,通过/queryMsg/{msgStr}访问provider微服务接口

java 复制代码
package com.ber.nacos.feign.controller;

import com.ber.nacos.feign.service.MsgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author: ber
 * @date: 2022/6/25 0025 22:46
 * -------------------------------
 * Github:https://github.com/berbai
 * Blog:https://blog.csdn.net/Ber_Bai
 */
@RestController
public class MsgController {

    @Autowired
    MsgService msgService;

    /**
     * 获取消息
     *
     * @param msgStr 消息
     * @return
     */
    @GetMapping("/queryMsg/{msgStr}")
    public String getMsg(@PathVariable(value = "msgStr") String msgStr) {
        return msgService.getMsg(msgStr);
    }
}

创建feign client FeignClient 默认集成了 Ribbon,使用@FeignClient注解将MsgService 接口作为 FeignClient ,其属性名称与服务名称nacos-provider对应

java 复制代码
package com.ber.nacos.feign.service;

import com.ber.nacos.feign.service.fallback.MsgServiceFallback;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

/**
 * @author: ber
 * @date: 2022/6/25 0025 22:54
 * -------------------------------
 * Github:https://github.com/berbai
 * Blog:https://blog.csdn.net/Ber_Bai
 */
@Component
@FeignClient(name = "nacos-provider", fallback = MsgServiceFallback.class)
public interface MsgService {

    @GetMapping("/getMsg/{msgStr}")
    String getMsg(@PathVariable("msgStr") String msgStr);
}

Feign的Fallback机制,在网络请求时,可能会出现异常请求,如果还想再异常情况下使系统可用,那么就需要容错处理,执行设置的容错业务代码。 当接口请求不成功时,就会调用MsgServiceFallback类这里的实现

java 复制代码
package com.ber.nacos.feign.service.fallback;

import com.ber.nacos.feign.service.MsgService;
import org.springframework.stereotype.Component;

/**
 * @author: ber
 * @date: 2022/6/25 0025 22:58
 * -------------------------------
 * Github:https://github.com/berbai
 * Blog:https://blog.csdn.net/Ber_Bai
 */
@Component
public class MsgServiceFallback implements MsgService {
    @Override
    public String getMsg(String msgStr) {
        return "请求失败";
    }
}

☘nacos-provider微服务

代码参考上篇文章《RestTemplate实现微服务之间访问》

🍀Feign微服务之间访问测试

启动nacos-consumer-feignnacos-provider,访问http://localhost:8848/nacos,使用 nacos/nacos 登陆后,可以发现服务列表中,两个微服务已经注册,如下图所示。 访问http://localhost:8895/queryMsg/hello,即consumer-feign的接口,可以得到如下图所示的界面

☘Feign容错机制

修改feign client代码如下所示 改为@GetMapping("/getMsg-error/{msgStr}"),即原本的queryMsg会被请求到getMsg-error,而provider并没有提供getMsg-error,此时feign会进入容错机制。

java 复制代码
package com.ber.nacos.feign.service;

import com.ber.nacos.feign.service.fallback.MsgServiceFallback;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

/**
 * @author: ber
 * @date: 2022/6/25 0025 22:54
 * -------------------------------
 * Github:https://github.com/berbai
 * Blog:https://blog.csdn.net/Ber_Bai
 */
@Component
@FeignClient(name = "nacos-provider", fallback = MsgServiceFallback.class)
public interface MsgService {

    @GetMapping("/getMsg-error/{msgStr}")
    String getMsg(@PathVariable("msgStr") String msgStr);
}

再次访问http://localhost:8895/queryMsg/hello,即consumer-feign的接口,可以得到如下图所示的界面

源码已上传github

本文介绍到此,博客仅记录博主学习过程,如存在错误之处,请指教。

相关推荐
fanly115 小时前
Surging AI Agent 完整产品介绍
微服务·microservice
蝎子莱莱爱打怪7 天前
XZLL-IM干货系列 04|Netty 长连接实战:Pipeline 怎么排、心跳怎么跳、连接怎么管
后端·微服务·面试
SamDeepThinking8 天前
Java微服务练习方式
java·后端·微服务
米丘11 天前
微前端之 Web Components 完全指南
微服务·html
霸道流氓气质13 天前
领域驱动设计(DDD)在 Spring Boot 微服务中的实践指南
运维·spring boot·微服务
霸道流氓气质14 天前
Spring Boot 微服务性能优化完全指南
spring boot·微服务·性能优化
地瓜伯伯14 天前
从MESI缓存一致性协议讲透synchronized的底层
java·spring boot·spring·spring cloud·微服务·springcloud
Devin~Y14 天前
大厂 Java 面试实录:从音视频内容社区到 AI RAG 的全链路技术设计
java·spring boot·redis·spring cloud·微服务·kafka·音视频
递归尽头是星辰14 天前
AI 访问数据仓库:从直连到微服务化
数据仓库·人工智能·微服务·dataagent·ai数据治理
就改了14 天前
Windows 环境 SkyWalking 完整实操教程
windows·微服务·skywalking