Podręcznik użytkownika OpenFeign

Równoważenie obciążenia

Integracja ze Spring Cloud LoadBalancer

OpenFeign domyślnie integruje się ze Spring Cloud LoadBalancer, zapewniając funkcjonalność równoważenia obciążenia po stronie klienta.

@FeignClient(name = "user-service")
public interface UserService {
    @GetMapping("/users/{id}")
    User getUser(@PathVariable("id") Long id);
}

Skonfiguruj instancje usług w application.yml:

spring:
  cloud:
    discovery:
      client:
        simple:
          instances:
            user-service:
              - uri: http://localhost:8081
              - uri: http://localhost:8082
              - uri: http://localhost:8083

Własna strategia równoważenia obciążenia

@Configuration
public class LoadBalancerConfig {
    
    @Bean
    public ServiceInstanceListSupplier serviceInstanceListSupplier(
            ConfigurableApplicationContext context) {
        return ServiceInstanceListSupplier.builder()
                .withDiscoveryClient()
                .withCaching()
                .build(context);
    }
}

Przekształcanie zrównoważonego żądania HTTP

@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());
        }
    };
}

Obsługa Circuit Breaker

Integracja ze Spring Cloud CircuitBreaker

Włącz obsługę circuit breaker:

spring:
  cloud:
    openfeign:
      circuitbreaker:
        enabled: true

Awaryjne zastępstwo (fallback) 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");
    }
}

Fabryka fallback z informacją o wyjątku

@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");
            }
        };
    }
}

Własna nazwa circuit breaker

@Configuration
public class CircuitBreakerConfig {
    @Bean
    public CircuitBreakerNameResolver circuitBreakerNameResolver() {
        return (String feignClientName, Target<?> target, Method method) -> 
            feignClientName + "_" + method.getName();
    }
}

Logowanie

Konfiguracja poziomu logowania

@Configuration
public class FeignLoggingConfig {
    
    @Bean
    Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;
    }
}

Lub za pomocą pliku konfiguracyjnego:

logging:
  level:
    com.example.clients.UserService: DEBUG

spring:
  cloud:
    openfeign:
      client:
        config:
          user-service:
            logger-level: full

Własne filtrowanie logów

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
    }
}

Kompresja żądań/odpowiedzi

Włączenie kompresji

spring:
  cloud:
    openfeign:
      compression:
        request:
          enabled: true
          mime-types: text/xml,application/xml,application/json
          min-request-size: 2048
        response:
          enabled: true

Ważne uwagi

  • Przy korzystaniu z OkHttpClient kompresja jest wyłączona, jeśli obecne są nagłówki content-encoding lub accept-encoding
  • Kompresja dotyczy tylko wskazanych typów MIME
  • Rozmiar żądania musi przekroczyć min-request-size, aby został skompresowany

Obsługa OAuth2

Włączenie OAuth2

spring:
  cloud:
    openfeign:
      oauth2:
        enabled: true
        client-registration-id: my-client

Konfiguracja zależności

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>

Konfiguracja klienta 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

Obsługa buforowania

Włączenie buforowania

@SpringBootApplication
@EnableCaching
@EnableFeignClients
public class Application {
    // ...
}

Użycie buforowania w kliencie 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);
}

Wyłączenie buforowania

spring:
  cloud:
    openfeign:
      cache:
        enabled: false

Obsługa asynchroniczności

Obsługa CompletableFuture

@FeignClient(name = "async-service")
public interface AsyncService {
    
    @GetMapping("/data/{id}")
    CompletableFuture<Data> getDataAsync(@PathVariable String id);
}

Konfiguracja klienta asynchronicznego

@Configuration
public class AsyncFeignConfig {
    
    @Bean
    public AsyncClient asyncClient() {
        return new AsyncClient.Default();
    }
}

Przykład użycia

@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);
            }
        });
    }
}

Obsługa dziedziczenia

Definicja interfejsu bazowego

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);
}

Konkretna implementacja serwisu

@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);
}

Mapowanie parametrów zapytania

Użycie @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);
}

Własny QueryMapEncoder

@Configuration
public class FeignConfig {
    
    @Bean
    public QueryMapEncoder queryMapEncoder() {
        return new BeanQueryMapEncoder(); // Use Java Bean properties
        // Or return new CustomQueryMapEncoder(); // Custom implementation
    }
}

Obsługa HATEOAS

Włączenie HATEOAS

Dodaj zależność:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-hateoas</artifactId>
</dependency>

Użycie modeli HATEOAS

@FeignClient(name = "hateoas-service")
public interface HateoasService {
    
    @GetMapping("/resources")
    CollectionModel<Resource> getResources();
    
    @GetMapping("/resources/{id}")
    EntityModel<Resource> getResource(@PathVariable String id);
}

Obsługa Refresh Scope

Włączenie obsługi odświeżania

spring:
  cloud:
    openfeign:
      client:
        refresh-enabled: true

Odświeżanie konfiguracji

Odśwież za pomocą punktu końcowego Actuator:

POST /actuator/refresh

Ważne uwagi

  • Nie oznaczaj interfejsu @FeignClient adnotacją @RefreshScope
  • Funkcja odświeżania jest domyślnie wyłączona i wymaga jawnego włączenia
  • Obsługuje odświeżanie limitu czasu połączenia, limitu czasu odczytu i konfiguracji URL

Obsługa AOT i obrazów natywnych

Wymagania konfiguracyjne

spring:
  cloud:
    refresh:
      enabled: false
    openfeign:
      client:
        refresh-enabled: false
      lazy-attributes-resolution: false

Budowanie obrazu natywnego

Zapewnij poprawną konfigurację podczas kompilacji i nadpisz URL w czasie wykonania za pomocą właściwości systemowych:

-Dspring.cloud.openfeign.client.config.[clientId].url=[url]

Te zaawansowane funkcje sprawiają, że OpenFeign to nie tylko prosty klient HTTP, lecz kompleksowe rozwiązanie do komunikacji mikrousługowe, zdolne spełnić różnorodne wymagania aplikacji klasy enterprise.