Search in sources :

Example 1 with Dispatcher

use of io.nats.client.Dispatcher in project micronaut-nats by micronaut-projects.

the class NatsConsumerAdvice method process.

@Override
public void process(BeanDefinition<?> beanDefinition, ExecutableMethod<?, ?> method) {
    if (method.hasAnnotation(NatsListener.class)) {
        AnnotationValue<Subject> subjectAnn = method.getAnnotation(Subject.class);
        if (subjectAnn != null) {
            String subject = subjectAnn.getRequiredValue(String.class);
            String connectionName = method.findAnnotation(NatsConnection.class).flatMap(conn -> conn.get("connection", String.class)).orElse(NatsConnection.DEFAULT_CONNECTION);
            io.micronaut.context.Qualifier<Object> qualifer = beanDefinition.getAnnotationTypeByStereotype("javax.inject.Qualifier").map(type -> Qualifiers.byAnnotation(beanDefinition, type)).orElse(null);
            Class<Object> beanType = (Class<Object>) beanDefinition.getBeanType();
            Class<?> returnTypeClass = method.getReturnType().getType();
            boolean isVoid = returnTypeClass == Void.class || returnTypeClass == void.class;
            Object bean = beanContext.findBean(beanType, qualifer).orElseThrow(() -> new MessageListenerException("Could not find the bean to execute the method " + method));
            Connection connection = beanContext.getBean(Connection.class, Qualifiers.byName(connectionName));
            DefaultExecutableBinder<Message> binder = new DefaultExecutableBinder<>();
            Dispatcher ds = connection.createDispatcher(msg -> {
                BoundExecutable boundExecutable = null;
                try {
                    boundExecutable = binder.bind(method, binderRegistry, msg);
                } catch (Throwable e) {
                    handleException(new NatsListenerException("An error occurred binding the message to the method", e, bean, msg));
                }
                if (boundExecutable != null) {
                    Object returnedValue = boundExecutable.invoke(bean);
                    if (!isVoid && StringUtils.isNotEmpty(msg.getReplyTo())) {
                        byte[] converted = null;
                        if (returnedValue != null) {
                            NatsMessageSerDes serDes = serDesRegistry.findSerdes(method.getReturnType().asArgument()).map(NatsMessageSerDes.class::cast).orElseThrow(() -> new NatsListenerException(String.format("Could not find a serializer for the body argument of type [%s]", returnedValue.getClass().getName()), bean, msg));
                            converted = serDes.serialize(returnedValue);
                        }
                        connection.publish(msg.getReplyTo(), converted);
                    }
                }
            });
            Optional<String> queueOptional = subjectAnn.get("queue", String.class);
            if (queueOptional.isPresent() && !queueOptional.get().isEmpty()) {
                ds.subscribe(subject, queueOptional.get());
            } else {
                ds.subscribe(subject);
            }
            consumerDispatchers.put(ds, subject);
        }
    }
}
Also used : NatsBinderRegistry(io.micronaut.nats.bind.NatsBinderRegistry) BeanContext(io.micronaut.context.BeanContext) MessageListenerException(io.micronaut.messaging.exceptions.MessageListenerException) NatsConnection(io.micronaut.nats.annotation.NatsConnection) Dispatcher(io.nats.client.Dispatcher) NatsMessageSerDes(io.micronaut.nats.serdes.NatsMessageSerDes) ExecutableMethod(io.micronaut.inject.ExecutableMethod) NatsListenerExceptionHandler(io.micronaut.nats.exception.NatsListenerExceptionHandler) Message(io.nats.client.Message) NatsListenerException(io.micronaut.nats.exception.NatsListenerException) NatsMessageSerDesRegistry(io.micronaut.nats.serdes.NatsMessageSerDesRegistry) Map(java.util.Map) Connection(io.nats.client.Connection) BoundExecutable(io.micronaut.core.bind.BoundExecutable) DefaultExecutableBinder(io.micronaut.core.bind.DefaultExecutableBinder) Iterator(java.util.Iterator) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Qualifiers(io.micronaut.inject.qualifiers.Qualifiers) Singleton(jakarta.inject.Singleton) ExecutableMethodProcessor(io.micronaut.context.processor.ExecutableMethodProcessor) StringUtils(io.micronaut.core.util.StringUtils) NatsListener(io.micronaut.nats.annotation.NatsListener) AnnotationValue(io.micronaut.core.annotation.AnnotationValue) Subject(io.micronaut.nats.annotation.Subject) Optional(java.util.Optional) BeanDefinition(io.micronaut.inject.BeanDefinition) Message(io.nats.client.Message) Dispatcher(io.nats.client.Dispatcher) NatsMessageSerDes(io.micronaut.nats.serdes.NatsMessageSerDes) MessageListenerException(io.micronaut.messaging.exceptions.MessageListenerException) DefaultExecutableBinder(io.micronaut.core.bind.DefaultExecutableBinder) NatsConnection(io.micronaut.nats.annotation.NatsConnection) Connection(io.nats.client.Connection) Subject(io.micronaut.nats.annotation.Subject) BoundExecutable(io.micronaut.core.bind.BoundExecutable) NatsListenerException(io.micronaut.nats.exception.NatsListenerException)

Example 2 with Dispatcher

use of io.nats.client.Dispatcher in project micronaut-nats by micronaut-projects.

the class NatsConsumerAdvice method close.

@Override
public void close() {
    final Iterator<Map.Entry<Dispatcher, String>> it = consumerDispatchers.entrySet().iterator();
    while (it.hasNext()) {
        final Map.Entry<Dispatcher, String> entry = it.next();
        Dispatcher dispatcher = entry.getKey();
        String subject = entry.getValue();
        dispatcher.unsubscribe(subject);
        if (!dispatcher.isActive()) {
            it.remove();
        }
    }
}
Also used : Dispatcher(io.nats.client.Dispatcher) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap)

Example 3 with Dispatcher

use of io.nats.client.Dispatcher in project carbon-mediation by wso2.

the class TLSConnection method initializeConsumer.

/**
 * Consume the message received and inject into the sequence.
 *
 * @param sequenceName the sequence to inject the message to.
 */
@Override
public void initializeConsumer(String sequenceName) throws IOException, InterruptedException {
    if (createConnection()) {
        Dispatcher dispatcher;
        dispatcher = connection.createDispatcher(natsMessage -> {
            if (natsMessage != null) {
                String message = new String(natsMessage.getData(), StandardCharsets.UTF_8);
                if (log.isDebugEnabled()) {
                    log.debug("Message Received to NATS Inbound EP: " + message);
                }
                injectHandler.invoke(message.getBytes(), sequenceName, natsMessage.getReplyTo(), connection);
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Message is null.");
                }
            }
        });
        String queueGroup = natsProperties.getProperty(NatsConstants.QUEUE_GROUP);
        if (StringUtils.isNotEmpty(queueGroup)) {
            dispatcher.subscribe(subject, queueGroup);
        } else {
            dispatcher.subscribe(subject);
        }
    }
}
Also used : StringUtils(org.apache.commons.lang.StringUtils) SSLContext(javax.net.ssl.SSLContext) Nats(io.nats.client.Nats) BufferedInputStream(java.io.BufferedInputStream) Properties(java.util.Properties) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) Dispatcher(io.nats.client.Dispatcher) KeyManagerFactory(javax.net.ssl.KeyManagerFactory) IOException(java.io.IOException) KeyStore(java.security.KeyStore) FileInputStream(java.io.FileInputStream) KeyStoreException(java.security.KeyStoreException) KeyManagementException(java.security.KeyManagementException) CertificateException(java.security.cert.CertificateException) StandardCharsets(java.nio.charset.StandardCharsets) SecureRandom(java.security.SecureRandom) Connection(io.nats.client.Connection) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) Log(org.apache.commons.logging.Log) LogFactory(org.apache.commons.logging.LogFactory) Options(io.nats.client.Options) Dispatcher(io.nats.client.Dispatcher)

Aggregations

Dispatcher (io.nats.client.Dispatcher)3 Connection (io.nats.client.Connection)2 Map (java.util.Map)2 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)2 BeanContext (io.micronaut.context.BeanContext)1 ExecutableMethodProcessor (io.micronaut.context.processor.ExecutableMethodProcessor)1 AnnotationValue (io.micronaut.core.annotation.AnnotationValue)1 BoundExecutable (io.micronaut.core.bind.BoundExecutable)1 DefaultExecutableBinder (io.micronaut.core.bind.DefaultExecutableBinder)1 StringUtils (io.micronaut.core.util.StringUtils)1 BeanDefinition (io.micronaut.inject.BeanDefinition)1 ExecutableMethod (io.micronaut.inject.ExecutableMethod)1 Qualifiers (io.micronaut.inject.qualifiers.Qualifiers)1 MessageListenerException (io.micronaut.messaging.exceptions.MessageListenerException)1 NatsConnection (io.micronaut.nats.annotation.NatsConnection)1 NatsListener (io.micronaut.nats.annotation.NatsListener)1 Subject (io.micronaut.nats.annotation.Subject)1 NatsBinderRegistry (io.micronaut.nats.bind.NatsBinderRegistry)1 NatsListenerException (io.micronaut.nats.exception.NatsListenerException)1 NatsListenerExceptionHandler (io.micronaut.nats.exception.NatsListenerExceptionHandler)1