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

अ‍ॅसिन्क समर्थन

CompletableFuture समर्थन

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

अ‍ॅसिन्क क्लायंट संरूपित करा

@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 ॲनोटेशन लावू नका
  • रिफ्रेश कार्यक्षमता डिपॉल्टपणे बंद असते, ती स्पष्टपणे सक्षम करावी लागते
  • कनेक्ट timeout, रीड timeout आणि URL संरूपण रिफ्रेश करण्यास समर्थन

AOT आणि नेटिव्ह इमेज समर्थन

संरूपण आवश्यकता

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

नेटिव्ह इमेज बिल्ड करा

बिल्ड वेळी योग्य संरूपणाची खात्री करा आणि system properties द्वारे रनटाइमवर URL ओव्हरराइड करा:

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

या प्रगत वैशिष्ट्यांमुळे OpenFeign फक्त साधा HTTP क्लायंट नाही राहिला, तर विविध एंटरप्राइझ अ‍ॅप्लिकेशन गरजांना पूर्ण करण्यास सक्षम सर्वसमावेशक मायक्रोसर्व्हिस संवाद समाधान बनतो.