Master OpenFeign: From Basics to Advanced Timeout, Logging, and Resilience

This tutorial walks you through OpenFeign in Spring Cloud, explaining its purpose, differences from Feign, setup steps, various parameter passing methods, timeout handling, logging enhancement, HTTP client replacement, GZIP compression, and circuit‑breaker integration with Sentinel, all illustrated with code snippets and diagrams.

Su San Talks Tech
Su San Talks Tech
Su San Talks Tech
Master OpenFeign: From Basics to Advanced Timeout, Logging, and Resilience

1. Introduction

Previously we introduced Nacos, the "soul ferry" of Spring Cloud, and now we turn to a service‑calling component: OpenFeign, a powerful successor to Ribbon and Feign.

2. What is Feign?

Feign simplifies Java HTTP clients. It integrates Ribbon and RestTemplate to provide load‑balanced HTTP calls, allowing developers to define an interface with annotations instead of manually using RestTemplate.

3. What is OpenFeign?

OpenFeign builds on Feign by supporting Spring MVC annotations such as @RequestMapping. Its @FeignClient can parse @RequestMapping on interfaces and generate dynamic proxy implementations that perform load balancing.

Official documentation: https://docs.spring.io/spring-cloud-openfeign/docs/2.2.10.BUILD-SNAPSHOT/reference/html

4. Differences Between Feign and OpenFeign

Feign is a lightweight RESTful HTTP client with built‑in Ribbon for client‑side load balancing. OpenFeign adds support for Spring MVC annotations, enabling @FeignClient to interpret @RequestMapping and create proxy classes that handle load balancing.

5. Environment Preparation

The Spring Cloud version, JDK, and project setup are the same as the previous Nacos article. Nacos replaces Eureka as the registration and configuration center.

Register services with Nacos: a producer service Produce and a consumer service Consumer .

6. Create Service Provider

Create the provider module openFeign-provider9005 and register it in Nacos.

server:
  port: 9005
spring:
  application:
    name: openFeign-provider
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848
management:
  endpoints:
    web:
      exposure:
        include: '*'

Note: The spring.application.name value is used by OpenFeign interfaces.

7. Create Service Consumer

1. Add Dependencies

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

2. Enable OpenFeign

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

3. Define OpenFeign Interface

@FeignClient(value = "openFeign-provider")
public interface OpenFeignService {
}
The value attribute specifies the service name registered in Nacos.

4. Add a Controller for Testing

@RestController
@RequestMapping("/openfeign")
public class OpenFeignController {
    // test methods go here
}

At this point the basic OpenFeign microservice is set up.

8. Parameter Passing in OpenFeign

OpenFeign supports several ways to pass parameters:

1. JSON Body

@RestController
@RequestMapping("/openfeign/provider")
public class OpenFeignProviderController {
    @PostMapping("/order2")
    public Order createOrder2(@RequestBody Order order) {
        return order;
    }
}
@FeignClient(value = "openFeign-provider")
public interface OpenFeignService {
    @PostMapping("/openfeign/provider/order2")
    Order createOrder2(@RequestBody Order order);
}

2. POJO Form (using @SpringQueryMap)

@RestController
@RequestMapping("/openfeign/provider")
public class OpenFeignProviderController {
    @PostMapping("/order1")
    public Order createOrder1(Order order) {
        return order;
    }
}
@FeignClient(value = "openFeign-provider")
public interface OpenFeignService {
    @PostMapping("/openfeign/provider/order1")
    Order createOrder1(@SpringQueryMap Order order);
}

3. URL Path Variables (GET)

@RestController
@RequestMapping("/openfeign/provider")
public class OpenFeignProviderController {
    @GetMapping("/test/{id}")
    public String test(@PathVariable("id") Integer id) {
        return "accept one msg id=" + id;
    }
}
@FeignClient(value = "openFeign-provider")
public interface OpenFeignService {
    @GetMapping("/openfeign/provider/test/{id}")
    String get(@PathVariable("id") Integer id);
}

4. Simple Form Parameters (using @RequestParam)

@RestController
@RequestMapping("/openfeign/provider")
public class OpenFeignProviderController {
    @PostMapping("/test2")
    public String test2(String id, String name) {
        return MessageFormat.format("accept on msg id={0}, name={1}", id, name);
    }
}
@FeignClient(value = "openFeign-provider")
public interface OpenFeignService {
    @PostMapping("/openfeign/provider/test2")
    String test(@RequestParam("id") String arg1, @RequestParam("name") String arg2);
}

9. Timeout Handling

OpenFeign inherits Ribbon's default 1‑second connection and read timeouts unless overridden. You can configure timeouts either globally or per service.

1. Configure Ribbon (not recommended)

ribbon:
  ReadTimeout: 5000
  ConnectTimeout: 5000

2. Configure OpenFeign (recommended)

feign:
  client:
    config:
      default:
        connectTimeout: 5000
        readTimeout: 5000
      serviceC:
        connectTimeout: 30000
        readTimeout: 30000
Service‑specific settings override the global defaults.

10. Enabling Log Enhancement

OpenFeign supports four log levels: NONE, BASIC, HEADERS, FULL. Configure a logger bean and set the desired level in application.yml:

logging:
  level:
    cn.myjszl.service: debug

Setting the level to FULL prints request and response bodies.

11. Replacing the Default HTTP Client

By default OpenFeign uses JDK URLConnection. To use Apache HttpClient, add the following dependencies:

<!-- Apache HttpClient replacement -->
<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpclient</artifactId>
</dependency>

<dependency>
  <groupId>io.github.openfeign</groupId>
  <artifactId>feign-httpclient</artifactId>
</dependency>

Enable it in configuration:

feign:
  client:
    httpclient:
      enabled: true

12. Communication Optimization with GZIP

OpenFeign can compress request and response bodies. Enable it as follows:

feign:
  compression:
    request:
      enabled: true
      min-request-size: 10
      mime-types: text/xml,application/xml,application/json
    response:
      enabled: true

13. Circuit‑Breaker and Fallback (Sentinel)

Although Hystrix is supported, Sentinel offers richer features. Add the Sentinel starter dependency, enable it, and provide a fallback class:

<dependency>
  <groupId>com.alibaba.cloud</groupId>
  <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
feign:
  sentinel:
    enabled: true
@FeignClient(value = "openFeign-provider", fallback = OpenFeignFallbackService.class)
public interface OpenFeignService {
    // method definitions
}

When the provider throws an exception, the fallback implementation is invoked, demonstrating graceful degradation.

14. Conclusion

This article provides a step‑by‑step guide for beginners to master OpenFeign, covering basic concepts, parameter passing, timeout configuration, logging, HTTP client replacement, GZIP compression, and Sentinel‑based circuit breaking.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaMicroservicesfeignSpring CloudOpenFeignResilience
Su San Talks Tech
Written by

Su San Talks Tech

Su San, former staff at several leading tech companies, is a top creator on Juejin and a premium creator on CSDN, and runs the free coding practice site www.susan.net.cn.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.