Search in sources :

Example 11 with ExecutableMethod

use of io.micronaut.inject.ExecutableMethod in project resilience4j by resilience4j.

the class CircuitBreakerInterceptor method intercept.

@Override
public Object intercept(MethodInvocationContext<Object, Object> context) {
    Optional<AnnotationValue<io.github.resilience4j.micronaut.annotation.CircuitBreaker>> opt = context.findAnnotation(io.github.resilience4j.micronaut.annotation.CircuitBreaker.class);
    if (!opt.isPresent()) {
        return context.proceed();
    }
    ExecutableMethod executableMethod = context.getExecutableMethod();
    final String name = executableMethod.stringValue(io.github.resilience4j.micronaut.annotation.CircuitBreaker.class, "name").orElse("default");
    CircuitBreaker circuitBreaker = this.circuitBreakerRegistry.circuitBreaker(name);
    InterceptedMethod interceptedMethod = InterceptedMethod.of(context);
    try {
        switch(interceptedMethod.resultType()) {
            case PUBLISHER:
                return interceptedMethod.handleResult(fallbackReactiveTypes(Flowable.fromPublisher(interceptedMethod.interceptResultAsPublisher()).compose(CircuitBreakerOperator.of(circuitBreaker)), context));
            case COMPLETION_STAGE:
                return interceptedMethod.handleResult(fallbackForFuture(circuitBreaker.executeCompletionStage(() -> {
                    try {
                        return interceptedMethod.interceptResultAsCompletionStage();
                    } catch (Exception e) {
                        throw new CompletionException(e);
                    }
                }), context));
            case SYNCHRONOUS:
                try {
                    return circuitBreaker.executeCheckedSupplier(context::proceed);
                } catch (Throwable exception) {
                    return fallback(context, exception);
                }
            default:
                return interceptedMethod.unsupported();
        }
    } catch (Exception e) {
        return interceptedMethod.handleException(e);
    }
}
Also used : CircuitBreaker(io.github.resilience4j.circuitbreaker.CircuitBreaker) ExecutableMethod(io.micronaut.inject.ExecutableMethod) InterceptedMethod(io.micronaut.aop.InterceptedMethod) CompletionException(java.util.concurrent.CompletionException) CompletionException(java.util.concurrent.CompletionException) AnnotationValue(io.micronaut.core.annotation.AnnotationValue)

Example 12 with ExecutableMethod

use of io.micronaut.inject.ExecutableMethod in project resilience4j by resilience4j.

the class RateLimiterInterceptor method findFallbackMethod.

/**
 * Finds a fallback method for the given context.
 *
 * @param context The context
 * @return The fallback method if it is present
 */
public Optional<? extends MethodExecutionHandle<?, Object>> findFallbackMethod(MethodInvocationContext<Object, Object> context) {
    ExecutableMethod executableMethod = context.getExecutableMethod();
    final String fallbackMethod = executableMethod.stringValue(io.github.resilience4j.micronaut.annotation.RateLimiter.class, "fallbackMethod").orElse("");
    Class<?> declaringType = context.getDeclaringType();
    return executionHandleLocator.findExecutionHandle(declaringType, fallbackMethod, context.getArgumentTypes());
}
Also used : ExecutableMethod(io.micronaut.inject.ExecutableMethod) RateLimiter(io.github.resilience4j.ratelimiter.RateLimiter)

Example 13 with ExecutableMethod

use of io.micronaut.inject.ExecutableMethod in project resilience4j by resilience4j.

the class TimeLimiterInterceptor method intercept.

@Override
public Object intercept(MethodInvocationContext<Object, Object> context) {
    Optional<AnnotationValue<io.github.resilience4j.micronaut.annotation.TimeLimiter>> opt = context.findAnnotation(io.github.resilience4j.micronaut.annotation.TimeLimiter.class);
    if (!opt.isPresent()) {
        return context.proceed();
    }
    ExecutableMethod executableMethod = context.getExecutableMethod();
    final String name = executableMethod.stringValue(io.github.resilience4j.micronaut.annotation.TimeLimiter.class).orElse("default");
    TimeLimiter timeLimiter = this.timeLimiterRegistry.timeLimiter(name);
    InterceptedMethod interceptedMethod = InterceptedMethod.of(context);
    try {
        switch(interceptedMethod.resultType()) {
            case PUBLISHER:
                return interceptedMethod.handleResult(fallbackReactiveTypes(Flowable.fromPublisher(interceptedMethod.interceptResultAsPublisher()).compose(TimeLimiterTransformer.of(timeLimiter)), context));
            case COMPLETION_STAGE:
                return interceptedMethod.handleResult(fallbackForFuture(timeLimiter.executeCompletionStage(executorService, () -> {
                    try {
                        return interceptedMethod.interceptResultAsCompletionStage();
                    } catch (Exception e) {
                        throw new CompletionException(e);
                    }
                }), context));
            case SYNCHRONOUS:
                try {
                    return timeLimiter.executeFutureSupplier(() -> CompletableFuture.supplyAsync(context::proceed));
                } catch (Throwable exception) {
                    return fallback(context, exception);
                }
            default:
                return interceptedMethod.unsupported();
        }
    } catch (Exception e) {
        return interceptedMethod.handleException(e);
    }
}
Also used : TimeLimiter(io.github.resilience4j.timelimiter.TimeLimiter) ExecutableMethod(io.micronaut.inject.ExecutableMethod) InterceptedMethod(io.micronaut.aop.InterceptedMethod) CompletionException(java.util.concurrent.CompletionException) CompletionException(java.util.concurrent.CompletionException) AnnotationValue(io.micronaut.core.annotation.AnnotationValue)

Example 14 with ExecutableMethod

use of io.micronaut.inject.ExecutableMethod in project resilience4j by resilience4j.

the class TimeLimiterInterceptor method findFallbackMethod.

/**
 * Finds a fallback method for the given context.
 *
 * @param context The context
 * @return The fallback method if it is present
 */
@Override
public Optional<? extends MethodExecutionHandle<?, Object>> findFallbackMethod(MethodInvocationContext<Object, Object> context) {
    ExecutableMethod executableMethod = context.getExecutableMethod();
    final String fallbackMethod = executableMethod.stringValue(io.github.resilience4j.micronaut.annotation.TimeLimiter.class, "fallbackMethod").orElse("");
    Class<?> declaringType = context.getDeclaringType();
    return executionHandleLocator.findExecutionHandle(declaringType, fallbackMethod, context.getArgumentTypes());
}
Also used : TimeLimiter(io.github.resilience4j.timelimiter.TimeLimiter) ExecutableMethod(io.micronaut.inject.ExecutableMethod)

Example 15 with ExecutableMethod

use of io.micronaut.inject.ExecutableMethod in project micronaut-kafka by micronaut-projects.

the class KafkaConsumerProcessor method configureDeserializers.

private void configureDeserializers(final ExecutableMethod<?, ?> method, final DefaultKafkaConsumerConfiguration consumerConfiguration) {
    final Properties properties = consumerConfiguration.getConfig();
    // figure out the Key deserializer
    final Argument<?> bodyArgument = findBodyArgument(method);
    if (!properties.containsKey(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG) && !consumerConfiguration.getKeyDeserializer().isPresent()) {
        final Optional<Argument<?>> keyArgument = Arrays.stream(method.getArguments()).filter(arg -> arg.isAnnotationPresent(KafkaKey.class)).findFirst();
        if (keyArgument.isPresent()) {
            consumerConfiguration.setKeyDeserializer(serdeRegistry.pickDeserializer(keyArgument.get()));
        } else {
            // noinspection SingleStatementInBlock
            if (bodyArgument != null && ConsumerRecord.class.isAssignableFrom(bodyArgument.getType())) {
                final Optional<Argument<?>> keyType = bodyArgument.getTypeVariable("K");
                if (keyType.isPresent()) {
                    consumerConfiguration.setKeyDeserializer(serdeRegistry.pickDeserializer(keyType.get()));
                } else {
                    consumerConfiguration.setKeyDeserializer(new ByteArrayDeserializer());
                }
            } else {
                consumerConfiguration.setKeyDeserializer(new ByteArrayDeserializer());
            }
        }
    }
    // figure out the Value deserializer
    if (!properties.containsKey(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG) && !consumerConfiguration.getValueDeserializer().isPresent()) {
        if (bodyArgument == null) {
            // noinspection SingleStatementInBlock
            consumerConfiguration.setValueDeserializer(new StringDeserializer());
        } else {
            if (ConsumerRecord.class.isAssignableFrom(bodyArgument.getType())) {
                final Optional<Argument<?>> valueType = bodyArgument.getTypeVariable("V");
                if (valueType.isPresent()) {
                    consumerConfiguration.setValueDeserializer(serdeRegistry.pickDeserializer(valueType.get()));
                } else {
                    consumerConfiguration.setValueDeserializer(new StringDeserializer());
                }
            } else {
                final boolean batch = method.isTrue(KafkaListener.class, "batch");
                consumerConfiguration.setValueDeserializer(serdeRegistry.pickDeserializer(batch ? getComponentType(bodyArgument) : bodyArgument));
            }
        }
    }
    debugDeserializationConfiguration(method, consumerConfiguration, properties);
}
Also used : Topic(io.micronaut.configuration.kafka.annotation.Topic) Publishers(io.micronaut.core.async.publisher.Publishers) Bindable(io.micronaut.core.bind.annotation.Bindable) Arrays(java.util.Arrays) KafkaAcknowledgement(io.micronaut.configuration.kafka.KafkaAcknowledgement) ConsumerRecords(org.apache.kafka.clients.consumer.ConsumerRecords) MessagingSystemException(io.micronaut.messaging.exceptions.MessagingSystemException) ConsumerRecordBinderRegistry(io.micronaut.configuration.kafka.bind.ConsumerRecordBinderRegistry) StringDeserializer(org.apache.kafka.common.serialization.StringDeserializer) Duration(java.time.Duration) Map(java.util.Map) OffsetCommitCallback(org.apache.kafka.clients.consumer.OffsetCommitCallback) ArgumentUtils(io.micronaut.core.util.ArgumentUtils) DefaultExecutableBinder(io.micronaut.core.bind.DefaultExecutableBinder) Singleton(jakarta.inject.Singleton) Set(java.util.Set) Acknowledgement(io.micronaut.messaging.Acknowledgement) ConsumerConfig(org.apache.kafka.clients.consumer.ConsumerConfig) RecordMetadata(org.apache.kafka.clients.producer.RecordMetadata) ErrorStrategy(io.micronaut.configuration.kafka.annotation.ErrorStrategy) ExecutableMethodProcessor(io.micronaut.context.processor.ExecutableMethodProcessor) StandardCharsets(java.nio.charset.StandardCharsets) KafkaKey(io.micronaut.configuration.kafka.annotation.KafkaKey) SerdeRegistry(io.micronaut.configuration.kafka.serde.SerdeRegistry) ConsumerRecord(org.apache.kafka.clients.consumer.ConsumerRecord) AnnotationValue(io.micronaut.core.annotation.AnnotationValue) AbstractKafkaConsumerConfiguration(io.micronaut.configuration.kafka.config.AbstractKafkaConsumerConfiguration) ProducerRegistry(io.micronaut.configuration.kafka.ProducerRegistry) MessageBody(io.micronaut.messaging.annotation.MessageBody) ConsumerRegistry(io.micronaut.configuration.kafka.ConsumerRegistry) RecordHeader(org.apache.kafka.common.header.internals.RecordHeader) KafkaMessage(io.micronaut.configuration.kafka.KafkaMessage) Nullable(io.micronaut.core.annotation.Nullable) ReturnType(io.micronaut.core.type.ReturnType) Argument(io.micronaut.core.type.Argument) Blocking(io.micronaut.core.annotation.Blocking) ByteArrayDeserializer(org.apache.kafka.common.serialization.ByteArrayDeserializer) Properties(java.util.Properties) Producer(org.apache.kafka.clients.producer.Producer) OffsetStrategy(io.micronaut.configuration.kafka.annotation.OffsetStrategy) Publisher(org.reactivestreams.Publisher) KafkaListenerException(io.micronaut.configuration.kafka.exceptions.KafkaListenerException) Mono(reactor.core.publisher.Mono) SendTo(io.micronaut.messaging.annotation.SendTo) Flux(reactor.core.publisher.Flux) CommitFailedException(org.apache.kafka.clients.consumer.CommitFailedException) TaskScheduler(io.micronaut.scheduling.TaskScheduler) BeanDefinition(io.micronaut.inject.BeanDefinition) BeanContext(io.micronaut.context.BeanContext) ArrayUtils(io.micronaut.core.util.ArrayUtils) LoggerFactory(org.slf4j.LoggerFactory) PreDestroy(javax.annotation.PreDestroy) TaskExecutors(io.micronaut.scheduling.TaskExecutors) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Locale(java.util.Locale) KafkaListenerExceptionHandler(io.micronaut.configuration.kafka.exceptions.KafkaListenerExceptionHandler) ApplicationConfiguration(io.micronaut.runtime.ApplicationConfiguration) NameUtils(io.micronaut.core.naming.NameUtils) Consumer(org.apache.kafka.clients.consumer.Consumer) TopicPartition(org.apache.kafka.common.TopicPartition) WakeupException(org.apache.kafka.common.errors.WakeupException) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Qualifiers(io.micronaut.inject.qualifiers.Qualifiers) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) StringUtils(io.micronaut.core.util.StringUtils) ConsumerRebalanceListener(org.apache.kafka.clients.consumer.ConsumerRebalanceListener) List(java.util.List) ProducerFencedException(org.apache.kafka.common.errors.ProducerFencedException) OffsetAndMetadata(org.apache.kafka.clients.consumer.OffsetAndMetadata) Optional(java.util.Optional) Pattern(java.util.regex.Pattern) Named(jakarta.inject.Named) KafkaListener(io.micronaut.configuration.kafka.annotation.KafkaListener) BatchConsumerRecordsBinderRegistry(io.micronaut.configuration.kafka.bind.batch.BatchConsumerRecordsBinderRegistry) ProducerRecord(org.apache.kafka.clients.producer.ProducerRecord) ErrorStrategyValue(io.micronaut.configuration.kafka.annotation.ErrorStrategyValue) ScheduledExecutorTaskScheduler(io.micronaut.scheduling.ScheduledExecutorTaskScheduler) TransactionalProducerRegistry(io.micronaut.configuration.kafka.TransactionalProducerRegistry) KafkaDefaultConfiguration(io.micronaut.configuration.kafka.config.KafkaDefaultConfiguration) HashMap(java.util.HashMap) Scheduler(reactor.core.scheduler.Scheduler) Function(java.util.function.Function) ExecutableMethod(io.micronaut.inject.ExecutableMethod) HashSet(java.util.HashSet) ExecutableBinder(io.micronaut.core.bind.ExecutableBinder) Requires(io.micronaut.context.annotation.Requires) Schedulers(reactor.core.scheduler.Schedulers) BoundExecutable(io.micronaut.core.bind.BoundExecutable) ExecutorService(java.util.concurrent.ExecutorService) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) OffsetReset(io.micronaut.configuration.kafka.annotation.OffsetReset) NonNull(io.micronaut.core.annotation.NonNull) IsolationLevel(org.apache.kafka.common.IsolationLevel) CollectionUtils(io.micronaut.core.util.CollectionUtils) DefaultKafkaConsumerConfiguration(io.micronaut.configuration.kafka.config.DefaultKafkaConsumerConfiguration) Collections(java.util.Collections) ConsumerAware(io.micronaut.configuration.kafka.ConsumerAware) Argument(io.micronaut.core.type.Argument) StringDeserializer(org.apache.kafka.common.serialization.StringDeserializer) Properties(java.util.Properties) ByteArrayDeserializer(org.apache.kafka.common.serialization.ByteArrayDeserializer) ConsumerRecord(org.apache.kafka.clients.consumer.ConsumerRecord)

Aggregations

ExecutableMethod (io.micronaut.inject.ExecutableMethod)17 AnnotationValue (io.micronaut.core.annotation.AnnotationValue)11 BeanContext (io.micronaut.context.BeanContext)8 Qualifiers (io.micronaut.inject.qualifiers.Qualifiers)8 ExecutableMethodProcessor (io.micronaut.context.processor.ExecutableMethodProcessor)7 BoundExecutable (io.micronaut.core.bind.BoundExecutable)7 DefaultExecutableBinder (io.micronaut.core.bind.DefaultExecutableBinder)7 BeanDefinition (io.micronaut.inject.BeanDefinition)7 MessageBody (io.micronaut.messaging.annotation.MessageBody)6 Singleton (jakarta.inject.Singleton)6 Logger (org.slf4j.Logger)6 LoggerFactory (org.slf4j.LoggerFactory)6 Argument (io.micronaut.core.type.Argument)5 Map (java.util.Map)5 ExecutorService (java.util.concurrent.ExecutorService)5 InterceptedMethod (io.micronaut.aop.InterceptedMethod)4 StringUtils (io.micronaut.core.util.StringUtils)4 ConsumerAware (io.micronaut.configuration.kafka.ConsumerAware)3 ConsumerRegistry (io.micronaut.configuration.kafka.ConsumerRegistry)3 KafkaAcknowledgement (io.micronaut.configuration.kafka.KafkaAcknowledgement)3