OpenFeign User Manual
Load Balancing
Spring Cloud LoadBalancer Integration
OpenFeign integrates with Spring Cloud LoadBalancer by default, providing client-side load balancing functionality.
@FeignClient(name = "user-service")
public interface UserService {
@GetMapping("/users/{id}")
User getUser(@PathVariable("id") Long id);
}
Configure service instances in application.yml:
spring:
cloud:
discovery:
client:
simple:
instances:
user-service:
- uri: http://localhost:8081
- uri: http://localhost:8082
- uri: http://localhost:8083
Custom Load Balancing Strategy
@Configuration
public class LoadBalancerConfig {
@Bean
public ServiceInstanceListSupplier serviceInstanceListSupplier(
ConfigurableApplicationContext context) {
return ServiceInstanceListSupplier.builder()
.withDiscoveryClient()
.withCaching()
.build(context);
}
}
Transform Load Balanced HTTP Request
@Bean
public LoadBalancerFeignRequestTransformer transformer() {
return new LoadBalancerFeignRequestTransformer() {
@Override
public Request transformRequest(Request request, ServiceInstance instance) {
Map<String, Collection<String>> headers = new HashMap<>(request.headers());
headers.put("X-ServiceId", Collections.singletonList(instance.getServiceId()));
headers.put("X-InstanceId", Collections.singletonList(instance.getInstanceId()));
return Request.create(request.httpMethod(), request.url(), headers,
request.body(), request.charset(), request.requestTemplate());
}
};
}
Circuit Breaker Support
Spring Cloud CircuitBreaker Integration
Enable circuit breaker support:
spring:
cloud:
openfeign:
circuitbreaker:
enabled: true
Circuit Breaker Fallback
@FeignClient(name = "user-service", fallback = UserServiceFallback.class)
public interface UserService {
@GetMapping("/users/{id}")
User getUser(@PathVariable("id") Long id);
}
@Component
public class UserServiceFallback implements UserService {
@Override
public User getUser(Long id) {
// Return default user or throw specific exception
return new User(id, "Default User");
}
}
Fallback Factory with Exception Information
@FeignClient(name = "user-service", fallbackFactory = UserServiceFallbackFactory.class)
public interface UserService {
@GetMapping("/users/{id}")
User getUser(@PathVariable("id") Long id);
}
@Component
public class UserServiceFallbackFactory implements FallbackFactory<UserService> {
@Override
public UserService create(Throwable cause) {
return new UserService() {
@Override
public User getUser(Long id) {
// Can access the exception that triggered fallback
log.error("UserService fallback triggered", cause);
return new User(id, "Fallback User");
}
};
}
}
Custom Circuit Breaker Name
@Configuration
public class CircuitBreakerConfig {
@Bean
public CircuitBreakerNameResolver circuitBreakerNameResolver() {
return (String feignClientName, Target<?> target, Method method) ->
feignClientName + "_" + method.getName();
}
}
Logging
Configure Log Level
@Configuration
public class FeignLoggingConfig {
@Bean
Logger.Level feignLoggerLevel() {
return Logger.Level.FULL;
}
}
Or through configuration file:
logging:
level:
com.example.clients.UserService: DEBUG
spring:
cloud:
openfeign:
client:
config:
user-service:
logger-level: full
Custom Log Filtering
public class CustomLogger extends Logger {
@Override
protected void logRequest(String configKey, Level logLevel, Request request) {
// Filter sensitive information
if (!shouldLogRequestHeader(request)) {
// Custom logging logic
}
}
@Override
protected Response logAndRebufferResponse(String configKey, Level logLevel,
Response response, long elapsedTime) throws IOException {
// Filter sensitive response information
if (!shouldLogResponseHeader(response)) {
// Custom logging logic
}
return super.logAndRebufferResponse(configKey, logLevel, response, elapsedTime);
}
private boolean shouldLogRequestHeader(Request request) {
// Filter Authorization header and other sensitive information
return !request.headers().containsKey("Authorization");
}
private boolean shouldLogResponseHeader(Response response) {
return true; // Or filter as needed
}
}
Request/Response Compression
Enable Compression
spring:
cloud:
openfeign:
compression:
request:
enabled: true
mime-types: text/xml,application/xml,application/json
min-request-size: 2048
response:
enabled: true
Important Notes
- When using OkHttpClient, compression is disabled if
content-encodingoraccept-encodingheaders are present - Compression only applies to specified MIME types
- Request size must exceed
min-request-sizeto be compressed
OAuth2 Support
Enable OAuth2
spring:
cloud:
openfeign:
oauth2:
enabled: true
client-registration-id: my-client
Dependency Configuration
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
OAuth2 Client Configuration
spring:
security:
oauth2:
client:
registration:
my-client:
client-id: your-client-id
client-secret: your-client-secret
authorization-grant-type: client_credentials
scope: read,write
provider:
my-provider:
token-uri: https://auth-server.com/oauth/token
Caching Support
Enable Caching
@SpringBootApplication
@EnableCaching
@EnableFeignClients
public class Application {
// ...
}
Use Caching in Feign Client
@FeignClient(name = "data-service")
public interface DataService {
@GetMapping("/data/{key}")
@Cacheable(cacheNames = "data-cache", key = "#key")
Data getData(@PathVariable String key);
@PostMapping("/data")
@CachePut(cacheNames = "data-cache", key = "#data.key")
Data updateData(@RequestBody Data data);
@DeleteMapping("/data/{key}")
@CacheEvict(cacheNames = "data-cache", key = "#key")
void deleteData(@PathVariable String key);
}
Disable Caching
spring:
cloud:
openfeign:
cache:
enabled: false
Async Support
CompletableFuture Support
@FeignClient(name = "async-service")
public interface AsyncService {
@GetMapping("/data/{id}")
CompletableFuture<Data> getDataAsync(@PathVariable String id);
}
Configure Async Client
@Configuration
public class AsyncFeignConfig {
@Bean
public AsyncClient asyncClient() {
return new AsyncClient.Default();
}
}
Usage Example
@Service
public class AsyncProcessingService {
private final AsyncService asyncService;
public AsyncProcessingService(AsyncService asyncService) {
this.asyncService = asyncService;
}
public void processData() {
CompletableFuture<Data> future1 = asyncService.getDataAsync("1");
CompletableFuture<Data> future2 = asyncService.getDataAsync("2");
// Process in parallel
CompletableFuture.allOf(future1, future2).thenRun(() -> {
try {
Data data1 = future1.get();
Data data2 = future2.get();
// Process data
} catch (Exception e) {
log.error("Error processing async data", e);
}
});
}
}
Inheritance Support
Base Interface Definition
public interface BaseService<T, ID> {
@GetMapping("/{id}")
T findById(@PathVariable ID id);
@GetMapping
List<T> findAll();
@PostMapping
T save(@RequestBody T entity);
@DeleteMapping("/{id}")
void deleteById(@PathVariable ID id);
}
Concrete Service Implementation
@FeignClient(name = "user-service")
public interface UserService extends BaseService<User, Long> {
@GetMapping("/users/by-email/{email}")
User findByEmail(@PathVariable String email);
}
@FeignClient(name = "order-service")
public interface OrderService extends BaseService<Order, Long> {
@GetMapping("/orders/by-user/{userId}")
List<Order> findByUserId(@PathVariable Long userId);
}
Query Parameter Mapping
Using @SpringQueryMap
public class SearchCriteria {
private String name;
private String status;
private Integer page;
private Integer size;
// getters and setters
}
@FeignClient(name = "search-service")
public interface SearchService {
@GetMapping("/search")
SearchResult search(@SpringQueryMap SearchCriteria criteria);
}
Custom QueryMapEncoder
@Configuration
public class FeignConfig {
@Bean
public QueryMapEncoder queryMapEncoder() {
return new BeanQueryMapEncoder(); // Use Java Bean properties
// Or return new CustomQueryMapEncoder(); // Custom implementation
}
}
HATEOAS Support
Enable HATEOAS
Add dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-hateoas</artifactId>
</dependency>
Use HATEOAS Models
@FeignClient(name = "hateoas-service")
public interface HateoasService {
@GetMapping("/resources")
CollectionModel<Resource> getResources();
@GetMapping("/resources/{id}")
EntityModel<Resource> getResource(@PathVariable String id);
}
Refresh Scope Support
Enable Refresh Support
spring:
cloud:
openfeign:
client:
refresh-enabled: true
Refresh Configuration
Refresh through Actuator endpoint:
POST /actuator/refresh
Important Notes
- Do not annotate
@FeignClientinterface with@RefreshScope - Refresh functionality is disabled by default, needs explicit enablement
- Supports refreshing connect timeout, read timeout, and URL configuration
AOT and Native Image Support
Configuration Requirements
spring:
cloud:
refresh:
enabled: false
openfeign:
client:
refresh-enabled: false
lazy-attributes-resolution: false
Build Native Image
Ensure correct configuration during build time, and override URL at runtime via system properties:
-Dspring.cloud.openfeign.client.config.[clientId].url=[url]
These advanced features make OpenFeign not just a simple HTTP client, but a comprehensive microservice communication solution capable of meeting various enterprise application requirements.
