Search in sources :

Example 1 with Async

use of io.micronaut.scheduling.annotation.Async in project quick by bakdata.

the class TopicRegistryInitializer method onStartUp.

/**
 * Ensures the topic registry itself and its topic are created.
 */
@EventListener
@Async
public void onStartUp(final StartupEvent event) {
    // the topic registry is a basically just a mirror application
    // therefore, it needs its own kafka topic
    final Properties properties = new Properties();
    properties.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, this.kafkaConfig.getBootstrapServer());
    boolean registryExists = false;
    try (final AdminClient admin = AdminClient.create(properties)) {
        final NewTopic immutableTopic = this.topicRegistryConfig.toNewKafkaTopic();
        admin.createTopics(List.of(immutableTopic));
    } catch (final TopicExistsException ignored) {
        log.info("Internal registry topic already exists");
        registryExists = true;
    } catch (final KafkaException e) {
        throw new InternalErrorException("Kafka could not be reached: " + e.getMessage());
    }
    // register the avro schema of the topic data class with the schema registry
    try {
        final String subject = VALUE.asSubject(this.topicRegistryConfig.getTopicName());
        final Schema topicDataSchema = AvroTopicData.getClassSchema();
        this.schemaRegistryClient.register(subject, topicDataSchema);
    } catch (final IOException | RestClientException exception) {
        if (!registryExists) {
            throw new InternalErrorException("Could not register schema for internal topic registry topic");
        }
    }
    final MirrorCreationData topicRegistryCreationData = new MirrorCreationData(this.topicRegistryConfig.getServiceName(), this.topicRegistryConfig.getTopicName(), 1, // null means we use the default tag
    null, null);
    // create topic-registry mirror
    // no retention time
    this.mirrorService.createInternalMirror(topicRegistryCreationData).subscribe(() -> log.info("Deployed internal topic-registry service"), e -> log.info("Could not deploy internal topic-registry service: {}", e.getMessage())).dispose();
}
Also used : MirrorCreationData(com.bakdata.quick.common.api.model.manager.creation.MirrorCreationData) Async(io.micronaut.scheduling.annotation.Async) SchemaRegistryClient(io.confluent.kafka.schemaregistry.client.SchemaRegistryClient) KafkaException(org.apache.kafka.common.KafkaException) Singleton(javax.inject.Singleton) Inject(javax.inject.Inject) AdminClient(org.apache.kafka.clients.admin.AdminClient) KafkaConfig(com.bakdata.quick.common.config.KafkaConfig) EventListener(io.micronaut.runtime.event.annotation.EventListener) InternalErrorException(com.bakdata.quick.common.exception.InternalErrorException) AvroTopicData(com.bakdata.quick.common.api.model.AvroTopicData) MirrorService(com.bakdata.quick.manager.mirror.MirrorService) Requires(io.micronaut.context.annotation.Requires) RestClientException(io.confluent.kafka.schemaregistry.client.rest.exceptions.RestClientException) TopicRegistryConfig(com.bakdata.quick.common.config.TopicRegistryConfig) Properties(java.util.Properties) Schema(org.apache.avro.Schema) AdminClientConfig(org.apache.kafka.clients.admin.AdminClientConfig) NewTopic(org.apache.kafka.clients.admin.NewTopic) IOException(java.io.IOException) VALUE(com.bakdata.quick.common.api.model.KeyValueEnum.VALUE) StringUtils(io.micronaut.core.util.StringUtils) List(java.util.List) Slf4j(lombok.extern.slf4j.Slf4j) TopicExistsException(org.apache.kafka.common.errors.TopicExistsException) StartupEvent(io.micronaut.context.event.StartupEvent) CachedSchemaRegistryClient(io.confluent.kafka.schemaregistry.client.CachedSchemaRegistryClient) Schema(org.apache.avro.Schema) InternalErrorException(com.bakdata.quick.common.exception.InternalErrorException) IOException(java.io.IOException) Properties(java.util.Properties) TopicExistsException(org.apache.kafka.common.errors.TopicExistsException) MirrorCreationData(com.bakdata.quick.common.api.model.manager.creation.MirrorCreationData) RestClientException(io.confluent.kafka.schemaregistry.client.rest.exceptions.RestClientException) NewTopic(org.apache.kafka.clients.admin.NewTopic) KafkaException(org.apache.kafka.common.KafkaException) AdminClient(org.apache.kafka.clients.admin.AdminClient) Async(io.micronaut.scheduling.annotation.Async) EventListener(io.micronaut.runtime.event.annotation.EventListener)

Example 2 with Async

use of io.micronaut.scheduling.annotation.Async in project micronaut-core by micronaut-projects.

the class AsyncInterceptor method intercept.

@Nullable
@Override
public Object intercept(MethodInvocationContext<Object, Object> context) {
    String executorServiceName = context.stringValue(Async.class).orElse(TaskExecutors.SCHEDULED);
    ExecutorService executorService;
    if (TaskExecutors.SCHEDULED.equals(executorServiceName) && scheduledExecutorService.isPresent()) {
        executorService = scheduledExecutorService.get().get();
    } else {
        executorService = scheduledExecutorServices.computeIfAbsent(executorServiceName, name -> beanLocator.findBean(ExecutorService.class, Qualifiers.byName(name)).orElseThrow(() -> new TaskExecutionException("No ExecutorService named [" + name + "] configured in application context")));
    }
    InterceptedMethod interceptedMethod = InterceptedMethod.of(context);
    try {
        switch(interceptedMethod.resultType()) {
            case PUBLISHER:
                return interceptedMethod.handleResult(interceptedMethod.interceptResultAsPublisher(executorService));
            case COMPLETION_STAGE:
                return interceptedMethod.handleResult(CompletableFuture.supplyAsync(() -> interceptedMethod.interceptResultAsCompletionStage(), executorService).thenCompose(Function.identity()));
            case SYNCHRONOUS:
                ReturnType<Object> rt = context.getReturnType();
                Class<?> returnType = rt.getType();
                if (void.class == returnType) {
                    executorService.submit(() -> {
                        try {
                            context.proceed();
                        } catch (Throwable e) {
                            if (LOG.isErrorEnabled()) {
                                LOG.error("Error occurred executing @Async method [" + context.getExecutableMethod() + "]: " + e.getMessage(), e);
                            }
                        }
                    });
                    return null;
                }
                throw new TaskExecutionException("Method [" + context.getExecutableMethod() + "] must return either void, or an instance of Publisher or CompletionStage");
            default:
                return interceptedMethod.unsupported();
        }
    } catch (Exception e) {
        return interceptedMethod.handleException(e);
    }
}
Also used : TaskExecutionException(io.micronaut.scheduling.exceptions.TaskExecutionException) Async(io.micronaut.scheduling.annotation.Async) Logger(org.slf4j.Logger) LoggerFactory(org.slf4j.LoggerFactory) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Qualifiers(io.micronaut.inject.qualifiers.Qualifiers) Singleton(jakarta.inject.Singleton) CompletableFuture(java.util.concurrent.CompletableFuture) Internal(io.micronaut.core.annotation.Internal) InterceptedMethod(io.micronaut.aop.InterceptedMethod) Function(java.util.function.Function) TaskExecutors(io.micronaut.scheduling.TaskExecutors) MethodInterceptor(io.micronaut.aop.MethodInterceptor) MethodInvocationContext(io.micronaut.aop.MethodInvocationContext) BeanProvider(io.micronaut.context.BeanProvider) Nullable(io.micronaut.core.annotation.Nullable) Map(java.util.Map) ReturnType(io.micronaut.core.type.ReturnType) Optional(java.util.Optional) BeanLocator(io.micronaut.context.BeanLocator) InterceptPhase(io.micronaut.aop.InterceptPhase) ExecutorService(java.util.concurrent.ExecutorService) Named(jakarta.inject.Named) TaskExecutionException(io.micronaut.scheduling.exceptions.TaskExecutionException) Async(io.micronaut.scheduling.annotation.Async) InterceptedMethod(io.micronaut.aop.InterceptedMethod) ExecutorService(java.util.concurrent.ExecutorService) TaskExecutionException(io.micronaut.scheduling.exceptions.TaskExecutionException) Nullable(io.micronaut.core.annotation.Nullable)

Example 3 with Async

use of io.micronaut.scheduling.annotation.Async in project micronaut-zeebe-client by camunda-community-hub.

the class ProcessDeployer method onStartupEvent.

@EventListener
@Async
public void onStartupEvent(StartupEvent event) {
    DeploymentEvent deployment = zeebeClient.newDeployCommand().addResourceFromClasspath("bpmn/say_hello.bpmn").requestTimeout(Duration.ofSeconds(10)).send().join();
    Process process = deployment.getProcesses().get(0);
    logger.info("deployed process {} with id {}", process.getResourceName(), process.getProcessDefinitionKey());
    processId = process.getBpmnProcessId();
}
Also used : Process(io.camunda.zeebe.client.api.response.Process) DeploymentEvent(io.camunda.zeebe.client.api.response.DeploymentEvent) Async(io.micronaut.scheduling.annotation.Async) EventListener(io.micronaut.runtime.event.annotation.EventListener)

Aggregations

Async (io.micronaut.scheduling.annotation.Async)3 EventListener (io.micronaut.runtime.event.annotation.EventListener)2 AvroTopicData (com.bakdata.quick.common.api.model.AvroTopicData)1 VALUE (com.bakdata.quick.common.api.model.KeyValueEnum.VALUE)1 MirrorCreationData (com.bakdata.quick.common.api.model.manager.creation.MirrorCreationData)1 KafkaConfig (com.bakdata.quick.common.config.KafkaConfig)1 TopicRegistryConfig (com.bakdata.quick.common.config.TopicRegistryConfig)1 InternalErrorException (com.bakdata.quick.common.exception.InternalErrorException)1 MirrorService (com.bakdata.quick.manager.mirror.MirrorService)1 DeploymentEvent (io.camunda.zeebe.client.api.response.DeploymentEvent)1 Process (io.camunda.zeebe.client.api.response.Process)1 CachedSchemaRegistryClient (io.confluent.kafka.schemaregistry.client.CachedSchemaRegistryClient)1 SchemaRegistryClient (io.confluent.kafka.schemaregistry.client.SchemaRegistryClient)1 RestClientException (io.confluent.kafka.schemaregistry.client.rest.exceptions.RestClientException)1 InterceptPhase (io.micronaut.aop.InterceptPhase)1 InterceptedMethod (io.micronaut.aop.InterceptedMethod)1 MethodInterceptor (io.micronaut.aop.MethodInterceptor)1 MethodInvocationContext (io.micronaut.aop.MethodInvocationContext)1 BeanLocator (io.micronaut.context.BeanLocator)1 BeanProvider (io.micronaut.context.BeanProvider)1