Cloud Native 19 min read

Master OpenFeign: From Basics to Advanced Configurations in Spring Cloud

This comprehensive tutorial walks you through OpenFeign—its relationship to Feign, environment setup, service provider and consumer creation, various parameter passing methods, timeout handling, logging, HTTP client replacement, GZIP compression, and Sentinel-based circuit breaking—providing practical code examples and configuration snippets for Spring Cloud microservices.

Su San Talks Tech
Su San Talks Tech
Su San Talks Tech
Master OpenFeign: From Basics to Advanced Configurations in Spring Cloud

1. What is Feign?

Feign is a lightweight Java HTTP client that simplifies RESTful service calls and integrates Ribbon for client‑side load balancing, allowing developers to define interfaces with annotations instead of manually using RestTemplate.

2. What is OpenFeign?

OpenFeign builds on Feign within Spring Cloud and adds support for Spring MVC annotations such as @RequestMapping, enabling interfaces annotated with @FeignClient to be parsed and implemented dynamically with load‑balancing capabilities.

3. Differences between Feign and OpenFeign

Feign provides a basic REST client with built‑in Ribbon, while OpenFeign extends Feign by supporting Spring MVC annotations, allowing seamless integration with Spring’s request mapping and parameter handling.

4. Environment preparation

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

5. Create service provider

Define a Spring Boot application named openFeign-provider9005 and register it in Nacos. Example YAML configuration:

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 when invoking the service.

6. Create service consumer

Create a new module openFeign-consumer9006 and add the required dependencies:

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

Enable OpenFeign

Add @EnableFeignClients to the main application class:

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

Create OpenFeign interface

Define an interface annotated with @FeignClient:

@FeignClient(value = "openFeign-provider")
public interface OpenFeignService {
    // define methods here
}

Create a controller for testing

Implement a simple controller to invoke the OpenFeign client:

@RestController
@RequestMapping("/openfeign")
public class OpenFeignController {
    // inject OpenFeignService and use it
}

7. Parameter passing in OpenFeign

Four common ways to pass parameters:

JSON data using @RequestBody on the provider side and optionally on the client side.

POJO form using @SpringQueryMap on the client interface to map object fields to query parameters.

URL path variables with @PathVariable for RESTful GET requests.

Query parameters using @RequestParam where the value attribute must match the provider’s parameter name.

JSON example

@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);
}

POJO form example

@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);
}

Path variable example

@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);
}

Query parameter example

@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 id, @RequestParam("name") String name);
}

8. Timeout handling

OpenFeign’s default timeouts are 10 s (connect) and 60 s (read). However, because OpenFeign integrates Ribbon, Ribbon’s defaults (1 s for both) may override them, causing unexpected timeouts.

You can configure timeouts either on Ribbon or directly on OpenFeign:

Ribbon timeout (not recommended)

ribbon:
  ReadTimeout: 5000
  ConnectTimeout: 5000

OpenFeign timeout (recommended)

feign:
  client:
    config:
      default:
        connectTimeout: 5000
        readTimeout: 5000
      serviceC:
        connectTimeout: 30000
        readTimeout: 30000

Service‑specific configurations override the global defaults.

9. Enabling logging

OpenFeign supports four log levels: NONE, BASIC, HEADERS, and FULL. To enable a level, define a logger bean and set the package’s logging level in application.yml:

logging:
  level:
    cn.myjszl.service: debug

10. Replacing the default HTTP client

Feign uses JDK URLConnection by default. To switch to Apache HttpClient, add the following dependencies and enable the client:

<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpclient</artifactId>
</dependency>
<dependency>
  <groupId>io.github.openfeign</groupId>
  <artifactId>feign-httpclient</artifactId>
</dependency>
feign:
  client:
    httpclient:
      enabled: true

After enabling, the underlying client used in feign.SynchronousMethodHandler#executeAndDecode() will be ApacheHttpClient.

11. GZIP compression

OpenFeign can compress request bodies and decompress responses using GZIP. Enable it in application.yml:

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

When enabled, the client adds Accept-Encoding: gzip,deflate to requests and processes Content-Encoding: gzip responses.

12. Circuit breaking with Sentinel

Add the Sentinel starter dependency and enable Sentinel for Feign:

<dependency>
  <groupId>com.alibaba.cloud</groupId>
  <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
feign:
  sentinel:
    enabled: true

Implement a fallback class that implements the same interface and reference it with the fallback attribute in @FeignClient:

@FeignClient(value = "openFeign-provider", fallback = OpenFeignFallbackService.class)
public interface OpenFeignService {
    // methods
}

13. Summary

The article provides a step‑by‑step guide for beginners to use OpenFeign in Spring Cloud, covering setup, parameter passing, timeout configuration, logging, HTTP client replacement, GZIP compression, and Sentinel‑based circuit breaking, with complete code examples and configuration snippets.

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 CloudOpenFeignCircuit Breaking
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.