OpenFeign उपयोगकर्ता मैनुअल

लोड बैलेंसिंग

Spring Cloud LoadBalancer एकीकरण

OpenFeign डिफ़ॉल्ट रूप से Spring Cloud LoadBalancer के साथ एकीकृत होता है, जो क्लाइंट-साइड लोड बैलेंसिंग कार्यक्षमता प्रदान करता है।

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

application.yml में सेवा इंस्टेंस कॉन्फ़िगर करें:

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

कस्टम लोड बैलेंसिंग रणनीति

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

लोड बैलेंस्ड 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());
        }
    };
}

सर्किट ब्रेकर समर्थन

Spring Cloud CircuitBreaker एकीकरण

सर्किट ब्रेकर समर्थन सक्षम करें:

spring:
  cloud:
    openfeign:
      circuitbreaker:
        enabled: true

सर्किट ब्रेकर फ़ॉलबैक

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

अपवाद जानकारी के साथ फ़ॉलबैक फ़ैक्टरी

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

कस्टम सर्किट ब्रेकर नाम

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

लॉगिंग

लॉग स्तर कॉन्फ़िगर करें

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

या कॉन्फ़िगरेशन फ़ाइल के माध्यम से:

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

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

कस्टम लॉग फ़िल्टरिंग

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

अनुरोध/प्रतिक्रिया संपीड़न

संपीड़न सक्षम करें

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

महत्वपूर्ण नोट्स

  • OkHttpClient का उपयोग करते समय, यदि content-encoding या accept-encoding हेडर मौजूद हैं तो संपीड़न अक्षम हो जाता है
  • संपीड़न केवल निर्दिष्ट MIME प्रकारों पर लागू होता है
  • संपीड़ित होने के लिए अनुरोध का आकार min-request-size से अधिक होना चाहिए

OAuth2 समर्थन

OAuth2 सक्षम करें

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

निर्भरता कॉन्फ़िगरेशन

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

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

कैशिंग समर्थन

कैशिंग सक्षम करें

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

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

कैशिंग अक्षम करें

spring:
  cloud:
    openfeign:
      cache:
        enabled: false

Async समर्थन

CompletableFuture समर्थन

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

Async क्लाइंट कॉन्फ़िगर करें

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

उपयोग उदाहरण

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

इनहेरिटेंस समर्थन

बेस इंटरफ़ेस परिभाषा

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

ठोस सेवा कार्यान्वयन

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

क्वेरी पैरामीटर मैपिंग

@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

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

HATEOAS समर्थन

HATEOAS सक्षम करें

निर्भरता जोड़ें:

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

HATEOAS मॉडल का उपयोग

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

रिफ्रेश स्कोप समर्थन

रिफ्रेश समर्थन सक्षम करें

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

रिफ्रेश कॉन्फ़िगरेशन

Actuator एंडपॉइंट के माध्यम से रिफ्रेश करें:

POST /actuator/refresh

महत्वपूर्ण नोट्स

  • @FeignClient इंटरफ़ेस को @RefreshScope के साथ एनोटेट न करें
  • रिफ्रेश कार्यक्षमता डिफ़ॉल्ट रूप से अक्षम है, स्पष्ट रूप से सक्षम करने की आवश्यकता है
  • connect timeout, read timeout और URL कॉन्फ़िगरेशन को रिफ्रेश करने का समर्थन करता है

AOT और Native Image समर्थन

कॉन्फ़िगरेशन आवश्यकताएँ

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

Native Image बिल्ड करें

बिल्ड समय के दौरान सही कॉन्फ़िगरेशन सुनिश्चित करें, और रनटाइम पर सिस्टम गुणों के माध्यम से URL को ओवरराइड करें:

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

ये उन्नत सुविधाएँ OpenFeign को केवल एक सरल HTTP क्लाइंट नहीं, बल्कि एक व्यापक माइक्रोसर्विस संचार समाधान बनाती हैं जो विभिन्न एंटरप्राइज़ अनुप्रयोग आवश्यकताओं को पूरा करने में सक्षम है।