OpenFeign:不依赖 Nacos 独立使用指南

部署运行你感兴趣的模型镜像

OpenFeign 独立使用配置

OpenFeign 本身是一个声明式的 HTTP 客户端,无需依赖 Nacos 等注册中心即可直接使用。核心依赖仅需 Spring Cloud OpenFeign:

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

启用 OpenFeign 功能

在 Spring Boot 主类或配置类上添加 @EnableFeignClients 注解:

@SpringBootApplication
@EnableFeignClients
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

定义 Feign 客户端接口

通过接口直接声明远程调用,使用 @FeignClient 指定目标服务 URL:

@FeignClient(name = "exampleClient", url = "http://api.example.com")
public interface ExampleFeignClient {
    @GetMapping("/items/{id}")
    ResponseEntity<Item> getItem(@PathVariable("id") String id);
    
    @PostMapping("/items")
    ResponseEntity<Void> createItem(@RequestBody Item item);
}

配置超时与重试

application.yml 中配置全局或客户端专属的超时参数:

feign:
  client:
    config:
      default:  # 全局默认配置
        connectTimeout: 5000
        readTimeout: 5000
        loggerLevel: basic
      exampleClient:  # 针对具体客户端的配置
        connectTimeout: 3000
        readTimeout: 3000

自定义拦截器与编解码器

实现 RequestInterceptor 添加请求头等通用逻辑:

public class AuthInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate template) {
        template.header("Authorization", "Bearer token123");
    }
}

通过配置类注册自定义编解码器:

@Bean
public Encoder feignEncoder() {
    return new JacksonEncoder();
}

@Bean
public Decoder feignDecoder() {
    return new JacksonDecoder();
}

日志调试配置

在配置文件中启用详细日志(需配合 logback.xml 设置级别):

logging:
  level:
    com.example.demo.ExampleFeignClient: DEBUG

异常处理策略

自定义错误解码器处理非 2xx 响应:

public class CustomErrorDecoder implements ErrorDecoder {
    @Override
    public Exception decode(String methodKey, Response response) {
        if (response.status() == 404) {
            return new ItemNotFoundException();
        }
        return new FeignException.BadRequest(response.reason());
    }
}

注册到 Feign 配置:

feign:
  client:
    config:
      default:
        errorDecoder: com.example.CustomErrorDecoder

您可能感兴趣的与本文相关的镜像

Seed-Coder-8B-Base

Seed-Coder-8B-Base

文本生成
Seed-Coder

Seed-Coder是一个功能强大、透明、参数高效的 8B 级开源代码模型系列,包括基础变体、指导变体和推理变体,由字节团队开源

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

canjun_wen

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

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

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

打赏作者

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

抵扣说明:

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

余额充值