Manuale utente di OpenFeign
Bilanciamento del carico
Integrazione con Spring Cloud LoadBalancer
OpenFeign si integra per impostazione predefinita con Spring Cloud LoadBalancer, fornendo funzionalità di bilanciamento del carico lato client.
@FeignClient(name = "user-service")
public interface UserService {
@GetMapping("/users/{id}")
User getUser(@PathVariable("id") Long id);
}
Configura le istanze del servizio in application.yml:
spring:
cloud:
discovery:
client:
simple:
instances:
user-service:
- uri: http://localhost:8081
- uri: http://localhost:8082
- uri: http://localhost:8083
Strategia di bilanciamento del carico personalizzata
@Configuration
public class LoadBalancerConfig {
@Bean
public ServiceInstanceListSupplier serviceInstanceListSupplier(
ConfigurableApplicationContext context) {
return ServiceInstanceListSupplier.builder()
.withDiscoveryClient()
.withCaching()
.build(context);
}
}
Trasformazione di una richiesta HTTP con bilanciamento del carico
@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());
}
};
}
Supporto del circuit breaker
Integrazione con Spring Cloud CircuitBreaker
Abilita il supporto del circuit breaker:
spring:
cloud:
openfeign:
circuitbreaker:
enabled: true
Fallback del circuit breaker
@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 con informazioni sull'eccezione
@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");
}
};
}
}
Nome personalizzato del circuit breaker
@Configuration
public class CircuitBreakerConfig {
@Bean
public CircuitBreakerNameResolver circuitBreakerNameResolver() {
return (String feignClientName, Target<?> target, Method method) ->
feignClientName + "_" + method.getName();
}
}
Logging
Configura il livello di log
@Configuration
public class FeignLoggingConfig {
@Bean
Logger.Level feignLoggerLevel() {
return Logger.Level.FULL;
}
}
Oppure tramite file di configurazione:
logging:
level:
com.example.clients.UserService: DEBUG
spring:
cloud:
openfeign:
client:
config:
user-service:
logger-level: full
Filtro dei log personalizzato
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
}
}
Compressione di richiesta/risposta
Abilita la compressione
spring:
cloud:
openfeign:
compression:
request:
enabled: true
mime-types: text/xml,application/xml,application/json
min-request-size: 2048
response:
enabled: true
Note importanti
- Quando si utilizza OkHttpClient, la compressione è disabilitata se sono presenti gli header
content-encodingoaccept-encoding - La compressione si applica solo ai tipi MIME specificati
- La dimensione della richiesta deve superare
min-request-sizeper essere compressa
Supporto OAuth2
Abilita OAuth2
spring:
cloud:
openfeign:
oauth2:
enabled: true
client-registration-id: my-client
Configurazione delle dipendenze
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
Configurazione del client OAuth2
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
Supporto della cache
Abilita la cache
@SpringBootApplication
@EnableCaching
@EnableFeignClients
public class Application {
// ...
}
Usa la cache nel client Feign
@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);
}
Disabilita la cache
spring:
cloud:
openfeign:
cache:
enabled: false
Supporto asincrono
Supporto di CompletableFuture
@FeignClient(name = "async-service")
public interface AsyncService {
@GetMapping("/data/{id}")
CompletableFuture<Data> getDataAsync(@PathVariable String id);
}
Configura il client asincrono
@Configuration
public class AsyncFeignConfig {
@Bean
public AsyncClient asyncClient() {
return new AsyncClient.Default();
}
}
Esempio di utilizzo
@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);
}
});
}
}
Supporto dell'ereditarietà
Definizione dell'interfaccia di base
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);
}
Implementazione concreta del servizio
@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);
}
Mappatura dei parametri di query
Uso di @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);
}
QueryMapEncoder personalizzato
@Configuration
public class FeignConfig {
@Bean
public QueryMapEncoder queryMapEncoder() {
return new BeanQueryMapEncoder(); // Use Java Bean properties
// Or return new CustomQueryMapEncoder(); // Custom implementation
}
}
Supporto HATEOAS
Abilita HATEOAS
Aggiungi la dipendenza:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-hateoas</artifactId>
</dependency>
Usa i modelli HATEOAS
@FeignClient(name = "hateoas-service")
public interface HateoasService {
@GetMapping("/resources")
CollectionModel<Resource> getResources();
@GetMapping("/resources/{id}")
EntityModel<Resource> getResource(@PathVariable String id);
}
Supporto dell'ambito di refresh
Abilita il supporto del refresh
spring:
cloud:
openfeign:
client:
refresh-enabled: true
Configurazione del refresh
Esegui il refresh tramite l'endpoint Actuator:
POST /actuator/refresh
Note importanti
- Non annotare l'interfaccia
@FeignClientcon@RefreshScope - La funzionalità di refresh è disabilitata per impostazione predefinita, richiede un'attivazione esplicita
- Supporta il refresh della configurazione di connect timeout, read timeout e URL
Supporto AOT e Native Image
Requisiti di configurazione
spring:
cloud:
refresh:
enabled: false
openfeign:
client:
refresh-enabled: false
lazy-attributes-resolution: false
Compila la Native Image
Assicurati della corretta configurazione in fase di build e sovrascrivi l'URL in fase di esecuzione tramite proprietà di sistema:
-Dspring.cloud.openfeign.client.config.[clientId].url=[url]
Queste funzionalità avanzate rendono OpenFeign non solo un semplice client HTTP, ma una soluzione completa di comunicazione tra microservizi in grado di soddisfare i vari requisiti delle applicazioni enterprise.
