Using OpenFeign in Spring Cloud: Setup, Configuration, and Advanced Features
This tutorial explains what OpenFeign is, how it differs from Feign, walks through environment preparation, service provider and consumer creation, various parameter passing methods, timeout handling, logging, HTTP client replacement, GZIP compression, and circuit‑breaker integration, providing a comprehensive guide for Spring Cloud microservice developers.
1. Introduction
Previously we introduced Nacos, the soul‑shuttle of Spring Cloud, which is powerful and easy to deploy. This article focuses on a service‑calling component: OpenFeign, an evolution of 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 and adds support for Spring MVC annotations such as @RequestMapping. The @FeignClient annotation can parse these mappings and generate a dynamic proxy that performs load‑balanced service calls.
Official documentation: https://docs.spring.io/spring-cloud-openfeign/docs/2.2.10.BUILD-SNAPSHOT/reference/html
4. Differences Between Feign and OpenFeign
Feign
OpenFeign
Lightweight RESTful HTTP client with built‑in Ribbon for load balancing.
Extends Feign to support Spring MVC annotations; @FeignClient parses @RequestMapping and creates a proxy with load balancing.
5. Environment Preparation
The Spring Cloud version, JDK, and project setup are the same as the previous Nacos article.
The registration center switches from Eureka to Nacos.
Project structure is shown in the diagram below.
Registration center uses Nacos with a microservice provider ( Produce ) and consumer ( Consumer ).
6. Create Service Provider
Create the module openFeign-provider9005 and register it in Nacos with the following 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 is used by OpenFeign interfaces.
7. Create Service Consumer
Create module openFeign-consumer9006 and follow these steps.
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 {
}Note: The value attribute specifies the service name registered in Nacos.
4) Add a Controller for Testing
@RestController
@RequestMapping("/openfeign")
public class OpenFeignController {
// test methods will be added here
}8. Parameter Passing in OpenFeign
Four common ways are demonstrated:
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
@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 Variable
@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) Form Parameters
@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);
}9. Timeout Handling
OpenFeign defaults to 10 s connection timeout and 60 s read timeout, but Ribbon (which OpenFeign integrates) overrides them with 1 s defaults. Two solutions:
Configure OpenFeign timeout via feign.client.config.
Configure Ribbon timeout (not recommended).
1) Ribbon Timeout
ribbon:
ReadTimeout: 5000
ConnectTimeout: 50002) OpenFeign Timeout (recommended)
feign:
client:
config:
default:
connectTimeout: 5000
readTimeout: 5000
serviceC:
connectTimeout: 30000
readTimeout: 30000Note: Service‑specific configuration overrides the global one.
10. Enabling Log Enhancement
Feign log levels: NONE, BASIC, HEADERS, FULL. To enable, create a configuration class that sets the logger, and configure the desired package or interface in application.yml:
logging:
level:
cn.myjszl.service: debug11. Replacing the Default HTTP Client
By default Feign uses JDK URLConnection. To replace it, add the Apache HttpClient (or OkHttp) dependencies and enable it:
<!-- Apache HttpClient dependency -->
<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: true12. Communication Optimization (GZIP)
GZIP can reduce payload size by over 70 %. Enable request/response compression in OpenFeign:
feign:
compression:
request:
enabled: true
min-request-size: 10
mime-types: text/xml,application/xml,application/json
response:
enabled: true13. Circuit‑Breaker and Fallback
OpenFeign supports Hystrix by default, but Sentinel is preferred. Add Sentinel dependency, enable it, and provide a fallback class:
feign:
sentinel:
enabled: true @FeignClient(value = "openFeign-provider", fallback = OpenFeignFallbackService.class)
public interface OpenFeignService {}14. Conclusion
This article provides a step‑by‑step guide for beginners to use OpenFeign in Spring Cloud, covering basic usage, parameter passing, timeout configuration, logging, HTTP client replacement, GZIP compression, and circuit‑breaker integration.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Code Ape Tech Column
Former Ant Group P8 engineer, pure technologist, sharing full‑stack Java, job interview and career advice through a column. Site: java-family.cn
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
