Gọi HTTP sang service khác trong Spring Boot 4.1.2 có hai lựa chọn chính: interface @HttpExchange của Framework 7, hoặc Spring Cloud OpenFeign 5.0.4. Bài cũ chọn OpenFeign như mặc định mà không nói cách thứ nhất tồn tại. Năm 2026 thứ tự đã đảo: OpenFeign vẫn chạy tốt, nhưng tài liệu Spring khuyến nghị HTTP Service Clients cho code mới. Bài này đặt hai cách cạnh nhau trên cùng endpoint để bạn chọn theo nhu cầu.
Mục lục
Cập nhật 2026
- Stack hiện tại: Boot 4.1.2, Framework 7.0.10, Spring Cloud 2025.1.4. OpenFeign trong train này là 5.0.4 (feign-core 13.6.1, feign-form-spring 13.6.1), nền Java 25 LTS.
- OpenFeign feature-complete: chỉ nhận bugfix và PR nhỏ; tài liệu khuyến nghị chuyển sang HTTP Service Clients. Nó không deprecated và vẫn được maintain.
- RestTemplate đã deprecated ở Framework 7.
RestClientlà client nền cho cả HTTP interface lẫn code gọi tay. - Prefix là
spring.cloud.openfeign.*. Keyfeign.client.config.*trong bài cũ không còn bind. Retryer mặc định làNEVER_RETRY, không phải retry 5 lần.
OpenFeign làm gì bên dưới
Bạn khai báo một interface, Feign tạo proxy động cho nó lúc khởi động. Mỗi phương thức được dịch thành request HTTP dựa trên annotation Spring MVC và kiểu tham số; dựng URL, serialize body, đọc response đều nằm trong proxy, còn code nghiệp vụ chỉ thấy một bean.
Khác biệt so với RestClient viết tay không phải là “khai báo” — HTTP interface cũng khai báo — mà là bộ mở rộng tích hợp sẵn: load balancing theo tên service, ErrorDecoder, interceptor, fallback, circuit breaker, encoder cho form.
Feign là client blocking, được thiết kế cho luồng servlet hoặc virtual thread, không cho event loop WebFlux. Gọi nó trong chain reactive sẽ chặn thread của Netty; triệu chứng là latency tăng dần dưới tải, không phải lỗi rõ ràng.
Bật Feign trong dự án
Khai báo BOM spring-cloud-dependencies 2025.1.4 trong <dependencyManagement> với scope import, rồi thêm starter; dependency không cần số phiên bản.
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
Starter load balancer (spring-cloud-starter-loadbalancer) là optional trong POM của OpenFeign: muốn gọi service theo tên với nhiều instance thì phải thêm tay, nếu không tên service không phân giải được.
// File: src/main/java/com/example/order/OrderApplication.java
package com.example.order;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication
@EnableFeignClients
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class, args);
}
}
Trong dự án nhiều module, đừng để scan mặc định quét cả classpath. Chỉ định @EnableFeignClients(basePackages = "com.example.order.clients") hoặc clients = ProductClient.class để biết chính xác client nào được đăng ký.
@FeignClient: bốn thuộc tính bạn thực sự dùng
name là tên logic, đồng thời là service id khi có discovery. Nó bắt buộc kể cả khi bạn đặt url. url ghim địa chỉ và tắt load balancing; path thêm prefix cho mọi phương thức; configuration áp cấu hình riêng cho client này.
// File: src/main/java/com/example/order/clients/ProductClient.java
package com.example.order.clients;
import com.example.order.dto.Product;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
@FeignClient(
name = "product-service",
path = "/api",
configuration = ProductClientConfig.class
)
public interface ProductClient {
@GetMapping("/products/{id}")
Product getById(@PathVariable("id") Long id);
@PostMapping("/products")
Product create(@RequestBody Product product);
}
Đường dẫn cuối cùng là /api/products/{id}: prefix path cộng đường dẫn trên phương thức. Giữ path trong một nơi duy nhất thay vì lặp /api ở từng method.
Hai client cùng service nhưng khác cấu hình thì dùng contextId; nếu không, bean cấu hình đè lên nhau theo thứ tự khó đoán. Các thuộc tính fallback, fallbackFactory, primary, dismiss404 xuất hiện ở phần sau.
Mapping tham số và kiểu trả về
Feign đọc annotation Spring MVC: @GetMapping, @PostMapping, @PathVariable, @RequestParam, @RequestBody, @RequestHeader. Không có annotation riêng của Feign cho việc này, nên interface trông như controller bị đảo chiều.
Luôn ghi tên trong @PathVariable("id"): nếu biên dịch không bật -parameters, Feign không lấy được tên tham số và request đi sai đường dẫn. Response 204 không có body thì khai báo void hoặc ResponseEntity<Void>, đừng khai báo DTO.
Timeout, retry và logging
Đây là phần bài cũ sai nhiều nhất: key nằm dưới spring.cloud.openfeign, không phải feign. Cấu hình default áp cho mọi client; block theo tên client đè lên default.
# File: src/main/resources/application.yml
spring:
cloud:
openfeign:
client:
config:
default:
connectTimeout: 2000
readTimeout: 5000
loggerLevel: basic
product-service:
connectTimeout: 1000
readTimeout: 3000
logging:
level:
com.example.order.clients.ProductClient: DEBUG
connectTimeout và readTimeout tính bằng millisecond. Nếu không đặt, thời gian chờ do HTTP client bên dưới quyết định và có thể dài tới mức thread bị treo khi service đích “sống nhưng không trả lời”. Circuit breaker không thay thế timeout: nó chỉ đếm lỗi sau khi lời gọi đã thoát.
Log của Feign chỉ hoạt động khi logger của interface ở mức DEBUG; loggerLevel quyết định nội dung. Bốn mức: NONE (mặc định), BASIC (method, URL, status, thời gian), HEADERS (thêm header), FULL (thêm body). Ở production, BASIC là đủ; FULL ghi token, dữ liệu khách hàng và làm log phình nhanh.
Về retry: FeignClientsConfiguration đăng ký Retryer.NEVER_RETRY làm mặc định, nên Feign không tự gửi lại khi gặp lỗi IO. Nếu thêm Retryer hoặc bật retry ở Resilience4j/LoadBalancer, POST có thể được gửi nhiều lần — chỉ retry khi thao tác idempotent hoặc có idempotency key.
Xử lý lỗi với ErrorDecoder
Mặc định, response 4xx/5xx biến thành FeignException. ErrorDecoder cho bạn đổi lỗi giao thức thành exception nghiệp vụ, nhưng phải giữ status và body gốc.
// File: src/main/java/com/example/order/clients/ProductErrorDecoder.java
package com.example.order.clients;
import feign.FeignException;
import feign.Response;
import feign.codec.ErrorDecoder;
public class ProductErrorDecoder implements ErrorDecoder {
@Override
public Exception decode(String methodKey, Response response) {
if (response.status() == 404) {
return new ProductNotFoundException("Không tìm thấy sản phẩm");
}
return FeignException.errorStatus(methodKey, response);
}
}
Không bao giờ trả null từ decode: Feign sẽ ném NullPointerException ở chỗ khác. Cũng đừng nuốt 5xx thành object rỗng — circuit breaker cần thấy lỗi để đếm, còn bạn cần log để điều tra. Với endpoint mà 404 là kết quả hợp lệ, đặt dismiss404 = true trên @FeignClient.
Request và response interceptor
Interceptor là chỗ đúng để lan truyền correlation id, token, tenant. Nó chạy trên mọi phương thức của client được gắn cấu hình.
// File: src/main/java/com/example/order/clients/ProductClientConfig.java
package com.example.order.clients;
import feign.RequestInterceptor;
import feign.codec.ErrorDecoder;
import org.springframework.context.annotation.Bean;
class ProductClientConfig {
@Bean
ErrorDecoder productErrorDecoder() {
return new ProductErrorDecoder();
}
@Bean
RequestInterceptor requestIdInterceptor() {
return template -> template.header("X-Request-Id", java.util.UUID.randomUUID().toString());
}
}
Để class này không có @Configuration: nếu bị component scan, các bean trên áp cho mọi Feign client, kể cả client không liên quan.
Phía response có ResponseInterceptor (feign.ResponseInterceptor), cấu hình bằng spring.cloud.openfeign.client.config.<name>.responseInterceptor. Dùng nó để đọc header tracing; đừng dùng để “sửa” body lỗi — việc đó thuộc ErrorDecoder.
Discovery và load balancing
Khi chỉ có name, Feign tạo một Spring Cloud LoadBalancer client mang tên đó. Ứng dụng là Eureka client thì địa chỉ lấy từ registry; nếu không, SimpleDiscoveryClient lấy từ cấu hình tĩnh. Nhiều instance thì request chia theo chiến lược của LoadBalancer, mặc định round-robin.
url tắt toàn bộ cơ chế này. Dùng nó cho local test là hợp lý, nhưng đưa vào production nghĩa là bạn tự ghim IP và tự chịu trách nhiệm khi instance đổi chỗ. Có thể đặt URL theo môi trường bằng spring.cloud.openfeign.client.config.product-service.url; annotation url sẽ đè lên property.
Đừng viết lb://product-service trong @FeignClient: tiền tố đó dành cho RestClient/Gateway, còn Feign nhận tên service trần và tự bọc LoadBalancer.
Circuit breaker và fallback
Thêm Spring Cloud Circuit Breaker với Resilience4j, rồi bật tích hợp ở phía Feign:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-circuitbreaker-resilience4j</artifactId>
</dependency>
spring:
cloud:
openfeign:
circuitbreaker:
enabled: true
resilience4j:
circuitbreaker:
configs:
default:
slidingWindowSize: 10
failureRateThreshold: 50
waitDurationInOpenState: 10s
permittedNumberOfCallsInHalfOpenState: 3
Khi bật, mọi phương thức của client được bọc trong circuit breaker. Tên instance mặc định là <interface>#<method>(<kiểu tham số>), ví dụ ProductClient#getById(Long). Muốn cấu hình theo tên client thay vì theo method thì bật spring.cloud.openfeign.circuitbreaker.group.enabled=true.
// File: src/main/java/com/example/order/clients/ProductClientFallback.java
package com.example.order.clients;
import com.example.order.dto.Product;
import org.springframework.stereotype.Component;
import java.math.BigDecimal;
@Component
public class ProductClientFallback implements ProductClient {
@Override
public Product getById(Long id) {
return new Product(id, "Tạm thời không có dữ liệu", BigDecimal.ZERO);
}
@Override
public Product create(Product product) {
throw new IllegalStateException("product-service unavailable");
}
}
Gắn bằng @FeignClient(name = "product-service", fallback = ProductClientFallback.class, ...). Fallback phải là Spring bean, nên @Component là bắt buộc. Cần biết nguyên nhân thì dùng fallbackFactory, class implement FallbackFactory nhận Throwable.
Cẩn thận với fallback trả dữ liệu giả cho thao tác ghi: một object “thành công” giả khiến caller tưởng đơn hàng đã tạo. Fallback chỉ nên che thao tác đọc hoặc trả lỗi rõ ràng cho thao tác ghi.
Upload file với multipart
// Thêm vào interface ProductClient
@PostMapping(value = "/products/{id}/image", consumes = "multipart/form-data")
void uploadImage(@PathVariable("id") Long id,
@RequestPart("file") org.springframework.web.multipart.MultipartFile file);
Starter 5.0.4 đã kéo feign-form-spring 13.6.1 (compile scope), nên SpringFormEncoder có mặt trên classpath. Nếu MultipartFile vẫn bị encode sai, đăng ký một bean Encoder trong cấu hình của client:
// Thêm vào ProductClientConfig
@Bean
Encoder feignFormEncoder() {
return new feign.form.spring.SpringFormEncoder();
}
Đặt consumes đúng; thiếu nó, Feign gửi JSON và server trả 415. Với file lớn, nhớ đặt readTimeout riêng cho client này thay vì dùng 5 giây của default.
Cùng endpoint với @HttpExchange
Đây là cách Framework 7 và Boot 4.1 coi là mặc định. Cùng endpoint /api/products/{id}, không cần starter Cloud:
// File: src/main/java/com/example/order/clients/ProductApi.java
package com.example.order.clients;
import com.example.order.dto.Product;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.service.annotation.GetExchange;
import org.springframework.web.service.annotation.HttpExchange;
import org.springframework.web.service.annotation.PostExchange;
@HttpExchange("/api/products")
public interface ProductApi {
@GetExchange("/{id}")
Product getById(@PathVariable Long id);
@PostExchange
Product create(@RequestBody Product product);
}
Boot có thể đăng ký theo nhóm bằng @ImportHttpServices(group = "product", types = ProductApi.class), rồi đặt spring.http.serviceclient.product.base-url. Nếu muốn kiểm soát hoàn toàn, tự tạo proxy:
// File: src/main/java/com/example/order/config/ProductApiConfig.java
package com.example.order.config;
import com.example.order.clients.ProductApi;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestClient;
import org.springframework.web.client.support.RestClientAdapter;
import org.springframework.web.service.invoker.HttpServiceProxyFactory;
@Configuration
class ProductApiConfig {
@Bean
ProductApi productApi(RestClient.Builder builder) {
RestClient restClient = builder.baseUrl("http://localhost:8081").build();
return HttpServiceProxyFactory
.builderFor(RestClientAdapter.create(restClient))
.build()
.createClient(ProductApi.class);
}
}
Timeout không nằm trên interface. Nó thuộc về RestClient/request factory bên dưới, nên hãy cấu hình ở builder dùng chung. Với discovery, đặt base URL thành lb://product-service qua property của group (cần LoadBalancer trên classpath); nếu để http://product-service, LoadBalancer không được áp dụng và bạn sẽ gặp lỗi DNS.
| Việc cần làm | Spring Cloud OpenFeign | @HttpExchange + RestClient |
|---|---|---|
| Khai báo endpoint | @FeignClient + @GetMapping |
@HttpExchange + @GetExchange |
| Kích hoạt | @EnableFeignClients |
@ImportHttpServices hoặc bean proxy factory |
| Base URL, discovery | name qua LoadBalancer; url để ghim |
spring.http.serviceclient.<group>.base-url, dùng lb:// khi cần LB |
| Timeout | connectTimeout, readTimeout |
Trên RestClient/request factory |
| Xử lý lỗi | ErrorDecoder, FeignException |
defaultStatusHandler, RestClientResponseException |
| Header | RequestInterceptor |
ClientHttpRequestInterceptor hoặc default header |
| Circuit breaker, fallback | Tích hợp sẵn qua property + fallback |
Tự bọc bằng Resilience4j/@CircuitBreaker |
| Multipart | @RequestPart + form encoder |
MultipartFile + RestClient body |
Lợi thế lớn nhất của @HttpExchange không nằm trong bảng: cùng interface dùng được cho client và @RestController, nên DTO và annotation chỉ tồn tại một bản. Với OpenFeign, interface client và DTO phải giữ riêng — chính chỗ đó sinh ra lệch contract.
Pitfall thường gặp
- Ghim
urlvào production. Hostname đổi theo môi trường; dùngname+ discovery, hoặc đưa URL vào config theo profile. - Không đặt timeout. Service đích treo sẽ giữ thread vô thời hạn; đặt cả connect lẫn read, riêng cho client upload.
- Retry POST không idempotent. Mặc định Feign không retry, nhưng khi bật retry ở Resilience4j/LoadBalancer, request tạo đơn có thể gửi hai lần. Dùng idempotency key hoặc chỉ retry GET.
- ErrorDecoder nuốt lỗi. Trả
nullhoặc map 5xx thành object rỗng làm circuit breaker không đếm được, caller không biết đã thất bại. - Log
FULLở production. Body chứa token và dữ liệu cá nhân, volume tăng theo payload; giữBASIC. - Gọi Feign trên event loop. Trong WebFlux, một call blocking làm nghẽn connection; dùng
WebClienthoặc offload sang executor riêng. - DTO copy ở mỗi service. Hai bản
Productlệch field chỉ lộ khi runtime; tách module API dùng chung hoặc dùng@HttpExchangecho cả hai phía. - Cấu hình client bị component scan. Class có
@Configurationtrong package được quét sẽ áp cho mọi Feign client.
Chọn cách nào
- Mặc định cho code mới:
@HttpExchange+RestClient. Ít dependency, chia sẻ interface với controller, và là hướng Spring đầu tư tiếp. - Chọn OpenFeign khi: cần
ErrorDecoder,RequestInterceptor, fallback theo client, hoặc hệ thống đã chuẩn hóa Feign. Đây là lý do hợp lệ để giữ. - Đừng chọn nó vì tính năng mới: dự án feature-complete, chỉ nhận bugfix.
- Cần load balancing: dùng HTTP interface + Spring Cloud LoadBalancer, hoặc để Gateway làm việc đó.
Hướng 2027: OpenFeign tiếp tục nhận bugfix trong các train hiện hành và không có lộ trình tính năng mới. Trong khi đó HTTP service clients còn đang mở rộng (nhóm client, API versioning), nên chi phí chuyển đổi sẽ thấp hơn nếu bạn bắt đầu bằng @HttpExchange ngay từ service mới.
Checklist trước khi merge
- Client dùng
name, không hard-codeurlngoài local profile. connectTimeoutvàreadTimeoutđã đặt cho cảdefaultlẫn client upload.- POST/PUT không bị retry trừ khi có idempotency key.
ErrorDecodermap đúng 4xx/5xx và không trảnull.- Log production ở
BASIC; không bậtFULLtoàn cục. - Cấu hình client không bị component scan; fallback chỉ che thao tác đọc.
Đọc tiếp trong series
- Spring Cloud là gì? Microservices với Spring cơ bản — tổng thể các module.
- Xử lý thất bại với Circuit Breaker trong Spring Cloud — ngưỡng, half-open, fallback.
- Spring Cloud Gateway: cổng API của bạn đi vào hoạt động — xác thực biên.
- Lộ trình Spring Boot 2026 — thứ tự học.



