OpenFeign Gebruikershandleiding
Load balancing
Integratie met Spring Cloud LoadBalancer
OpenFeign integreert standaard met Spring Cloud LoadBalancer en biedt daarmee load balancing aan de clientzijde.
@FeignClient(name = "user-service")
public interface UserService {
@GetMapping("/users/{id}")
User getUser(@PathVariable("id") Long id);
}
Configureer 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
Eigen load-balancingstrategie
@Configuration
public class LoadBalancerConfig {
@Bean
public ServiceInstanceListSupplier serviceInstanceListSupplier(
ConfigurableApplicationContext context) {
return ServiceInstanceListSupplier.builder()
.withDiscoveryClient()
.withCaching()
.build(context);
}
}
Load-balanced HTTP-verzoek transformeren
@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());
}
};
}
Ondersteuning voor circuit breaker
Integratie met Spring Cloud CircuitBreaker
Schakel ondersteuning voor de circuit breaker in:
spring:
cloud:
openfeign:
circuitbreaker:
enabled: true
Fallback van de 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 met uitzonderingsinformatie
@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");
}
};
}
}
Eigen naam voor de circuit breaker
@Configuration
public class CircuitBreakerConfig {
@Bean
public CircuitBreakerNameResolver circuitBreakerNameResolver() {
return (String feignClientName, Target<?> target, Method method) ->
feignClientName + "_" + method.getName();
}
}
Logging
Logniveau instellen
@Configuration
public class FeignLoggingConfig {
@Bean
Logger.Level feignLoggerLevel() {
return Logger.Level.FULL;
}
}
Of via een configuratiebestand:
logging:
level:
com.example.clients.UserService: DEBUG
spring:
cloud:
openfeign:
client:
config:
user-service:
logger-level: full
Eigen logfiltering
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
}
}
Compressie van verzoeken/antwoorden
Compressie inschakelen
spring:
cloud:
openfeign:
compression:
request:
enabled: true
mime-types: text/xml,application/xml,application/json
min-request-size: 2048
response:
enabled: true
Belangrijke opmerkingen
- Bij gebruik van OkHttpClient wordt compressie uitgeschakeld als er headers
content-encodingofaccept-encodingaanwezig zijn - Compressie geldt alleen voor de opgegeven MIME-types
- De verzoeksgrootte moet groter zijn dan
min-request-sizeom gecomprimeerd te worden
OAuth2-ondersteuning
OAuth2 inschakelen
spring:
cloud:
openfeign:
oauth2:
enabled: true
client-registration-id: my-client
Afhankelijkheidsconfiguratie
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
OAuth2-clientconfiguratie
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
Cacheondersteuning
Caching inschakelen
@SpringBootApplication
@EnableCaching
@EnableFeignClients
public class Application {
// ...
}
Caching gebruiken in een 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);
}
Caching uitschakelen
spring:
cloud:
openfeign:
cache:
enabled: false
Asynchrone ondersteuning
CompletableFuture-ondersteuning
@FeignClient(name = "async-service")
public interface AsyncService {
@GetMapping("/data/{id}")
CompletableFuture<Data> getDataAsync(@PathVariable String id);
}
Asynchrone client configureren
@Configuration
public class AsyncFeignConfig {
@Bean
public AsyncClient asyncClient() {
return new AsyncClient.Default();
}
}
Gebruiksexample
@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);
}
});
}
}
Ondersteuning voor overerving
Definitie van de basisinterface
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-implementatie
@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);
}
Mapping van queryparameters
@SpringQueryMap gebruiken
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);
}
Eigen QueryMapEncoder
@Configuration
public class FeignConfig {
@Bean
public QueryMapEncoder queryMapEncoder() {
return new BeanQueryMapEncoder(); // Use Java Bean properties
// Or return new CustomQueryMapEncoder(); // Custom implementation
}
}
HATEOAS-ondersteuning
HATEOAS inschakelen
Voeg de afhankelijkheid toe:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-hateoas</artifactId>
</dependency>
HATEOAS-modellen gebruiken
@FeignClient(name = "hateoas-service")
public interface HateoasService {
@GetMapping("/resources")
CollectionModel<Resource> getResources();
@GetMapping("/resources/{id}")
EntityModel<Resource> getResource(@PathVariable String id);
}
Ondersteuning voor refresh scope
Refresh-ondersteuning inschakelen
spring:
cloud:
openfeign:
client:
refresh-enabled: true
Configuratie verversen
Ververs via het Actuator-endpoint:
POST /actuator/refresh
Belangrijke opmerkingen
- Annoteer een
@FeignClient-interface niet met@RefreshScope - De refresh-functie is standaard uitgeschakeld en moet expliciet worden ingeschakeld
- Ondersteunt het verversen van connect-timeout, read-timeout en URL-configuratie
Ondersteuning voor AOT en native images
Configuratie-eisen
spring:
cloud:
refresh:
enabled: false
openfeign:
client:
refresh-enabled: false
lazy-attributes-resolution: false
Native image bouwen
Zorg voor een juiste configuratie tijdens de bouwtijd en overschrijf de URL tijdens de runtime via systeemeigenschappen:
-Dspring.cloud.openfeign.client.config.[clientId].url=[url]
Deze geavanceerde functies maken OpenFeign niet alleen tot een eenvoudige HTTP-client, maar tot een allesomvattende oplossing voor microservicecommunicatie die aan uiteenlopende zakelijke toepassingsvereisten kan voldoen.
