OpenFeign在SpringCloud项目中的搭建

1、添加依赖

首先,在项目中的pom.xml中添加feign和springCloud相关依赖:
<dependencies>
    <!-- Spring Cloud OpenFeign -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-openfeign</artifactId>
    </dependency>

    <!-- Spring Boot Web (可选,如果项目需要 HTTP 支持) -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!-- Spring Cloud LoadBalancer (可选,如果使用负载均衡) -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-loadbalancer</artifactId>
    </dependency>
</dependencies>

2、启用Feign客户端

在springBoot启动类上添加@EnableFeignClients注解,启用Feign客户端功能:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;

@SpringBootApplication
@EnableFeignClients // 启用 Feign 客户端
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

3、定义feign客户端接口

通过定义一个接口,使用feign的注解来声明远程调用的方法
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@FeignClient(name = "user-service") // 指定服务名称
public interface UserServiceClient {

    @GetMapping("/users/{id}") // 定义 HTTP 请求
    User getUserById(@PathVariable("id") Long id); // 方法签名
}
说明:
  • @FeignClient(name = "user-service"):指定要调用的服务名称(在注册中心注册的服务名)。
  • @GetMapping:定义 HTTP 请求方法和路径。
  • @PathVariable:绑定路径参数。

4、配置Feign

在application.xml或application.properties中配置Feign的相关属性(feign有默认的配置)
默认配置:
  • 超时时间:默认连接超时和读取超时时间较长(通常为几秒)
  • 日志级别:默认不记录日志(Logger.Level.NONE)
NONE(默认级别):不记录任何日志
BASIC:记录基本的请求和响应信息
HEADERS:记录请求和响应的头部信息
FULL:记录完整的请求和相应信息
  • 负载均衡:默认集成Ribbon或Spring Cloud LoadBalancer,支持负载均衡
  • 编码/解码:默认使用Spring的HttpMessageConverter进行请求和响应的序列化与反序列化
feign:
  client:
    config:
      default: # 全局配置
        connectTimeout: 5000 # 连接超时时间
        readTimeout: 5000    # 读取超时时间
        loggerLevel: basic   # 日志级别(NONE, BASIC, HEADERS, FULL)

也可以通过配置类配置feign的日志输出

import feign.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class FeignConfig {

    @Bean
    Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL; // 设置日志级别为 FULL
    }
}

配置日志输出(在application.xml或application.properties中配置)

application.xml:
logging:
  level:
    com.example.demo.client.UserClient: DEBUG  # 将 Feign 客户端接口的日志级别设置为 DEBUG

application.properties:
logging.level.com.example.demo.client.UserClient=DEBUG

5、降级逻辑:

1、如果需要使用 Hystrix 实现降级逻辑(Spring Cloud 2020 之前版本),还需要添加 Hystrix 依赖:
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
注意:Spring Cloud 2020 及之后版本默认移除了 Hystrix 支持,推荐使用 Resilience4j Sentinel 作为替代方案
2、 在 Spring Boot 启动类上添加 @EnableFeignClients @EnableHystrix 注解
3、定义Feign客户端接口
在Feign客户端接口上 使用@FeignClient注解,并指定fallback或fallbackFActory属性
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;

@FeignClient(name = "user-service", fallback = UserServiceFallback.class)
public interface UserServiceClient {
    @GetMapping("/users/{id}")
    String getUserById(Long id);
}
4、使用fallbackFactory,获取异常信息, 然后在 @FeignClient 中指定 fallbackFactory
import org.springframework.cloud.openfeign.FallbackFactory;
import org.springframework.stereotype.Component;

@Component
public class UserServiceFallbackFactory implements FallbackFactory<UserServiceClient> {
    @Override
    public UserServiceClient create(Throwable cause) {
        return new UserServiceClient() {
            @Override
            public String getUserById(Long id) {
                return "Fallback: User not available due to " + cause.getMessage(); // 降级逻辑
            }
        };
    }
}

6、在控制层或业务层调用feign客户端

正常注入feign客户端实例对象,通过实例对象调用对应的接口服务

 @Autowired
    private UserServiceClient userServiceClient;
补充知识:
Ribbon
Feign默认集成了Ribbon,Ribbon自动生效。
Ribbon是Netflix开源的一个客户端负载均衡器,主要用于在分布式系统中实现服务调用的负载均衡
是Spring Cloud生态中的重要组件之一,通常与Eureka(服务注册与发现)和feign(声明式HTTP客户端)配合使用
负载均衡策略:
RoundRobinRule—轮询策略
RandomRule—随机策略
WeightedResponseTimeRule—权重策略
RetryRule—重试策略
BestAvailableRule—选择并发请求数量最小的实例
Spring Cloud LoadBalancer
是spring Cloud官方提供的负载均衡器,支持响应式编程,能够和spring Cloud Gateway和Spring WebFlux更好的集成
添加依赖
org.springframework.cloud
spring-cloud-starter-loadbalancer

配置spring cloud loadBanlancer

spring:
cloud:
loadbalancer:
retry:
enabled: true # 启用重试机制
HttpMessageConverter
是 Spring 框架中的一个核心接口,用于在 HTTP 请求和响应中转换消息体(即请求体或响应体)的内容。它可以将 Java 对象转换为 HTTP 消息体(如 JSON、XML 等),或者将 HTTP 消息体转换为 Java 对象
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

易安杰

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

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

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

打赏作者

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

抵扣说明:

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

余额充值