use of io.vertx.mutiny.core.buffer.Buffer in project smallrye-reactive-messaging by smallrye.
the class RabbitMQUsage method produce.
/**
* Use the supplied function to asynchronously produce messages and write them to the host.
*
* @param exchange the exchange, must not be null
* @param messageCount the number of messages to produce; must be positive
* @param messageSupplier the function to produce messages; may not be null
*/
void produce(String exchange, String queue, String routingKey, int messageCount, Supplier<Object> messageSupplier) {
CountDownLatch done = new CountDownLatch(messageCount);
// Start the machinery to receive the messages
client.startAndAwait();
final Thread t = new Thread(() -> {
LOGGER.infof("Starting RabbitMQ sender to write %s messages with routing key %s", messageCount, routingKey);
try {
for (int i = 0; i != messageCount; ++i) {
final Object payload = messageSupplier.get();
final Buffer body = Buffer.buffer(payload.toString());
final BasicProperties properties = new AMQP.BasicProperties().builder().expiration("10000").contentType("text/plain").build();
client.basicPublish(exchange, routingKey, properties, body).subscribe().with(v -> {
LOGGER.infof("Producer sent message %s", payload);
done.countDown();
}, Throwable::printStackTrace);
}
} catch (Exception e) {
LOGGER.error("Unable to send message", e);
}
LOGGER.infof("Finished sending %s messages with routing key %s", messageCount, routingKey);
});
t.setName(exchange + "-thread");
t.start();
try {
done.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
// Ignore me
}
}
use of io.vertx.mutiny.core.buffer.Buffer in project smallrye-reactive-messaging by smallrye.
the class RabbitMQMessageConverter method convert.
/**
* Converts the supplied {@link Message} to an {@link OutgoingRabbitMQMessage}.
*
* @param message the source message
* @param exchange the destination exchange
* @param defaultRoutingKey the fallback routing key to use
* @param isTracingEnabled whether tracing is enabled
* @param attributeHeaders a list (possibly empty) of message header names whose values should be
* included as span attributes
* @return an {@link OutgoingRabbitMQMessage}
*/
public static OutgoingRabbitMQMessage convert(final Message<?> message, final String exchange, final String defaultRoutingKey, final Optional<Long> defaultTtl, final boolean isTracingEnabled, final List<String> attributeHeaders) {
final Optional<io.vertx.mutiny.rabbitmq.RabbitMQMessage> rabbitMQMessage = getRabbitMQMessage(message);
final String routingKey = getRoutingKey(message).orElse(defaultRoutingKey);
// Figure out the body and properties
Buffer body;
BasicProperties properties;
if (rabbitMQMessage.isPresent()) {
// If we already have a RabbitMQMessage present, use it as the basis for the outgoing one
body = rabbitMQMessage.get().body();
final BasicProperties sourceProperties = rabbitMQMessage.get().properties();
// Make a copy of the source headers as the original is probably immutable
final Map<String, Object> sourceHeaders = new HashMap<>(sourceProperties.getHeaders());
if (isTracingEnabled) {
// Create a new span for the outbound message and record updated tracing information in
// the headers; this has to be done before we build the properties below
TracingUtils.createOutgoingTrace(message, sourceHeaders, exchange, routingKey, attributeHeaders);
}
// Reconstruct the properties from the source, except with the (possibly) modified headers;
// only override the existing expiration if not already set and a non-negative default TTL
// has been specified.
final String expiration = (null != sourceProperties.getExpiration()) ? sourceProperties.getExpiration() : defaultTtl.map(String::valueOf).orElse(null);
// If not already specified, figure out the content type from the message payload
final String contentType = (sourceProperties.getContentType() != null) ? sourceProperties.getContentType() : getDefaultContentTypeForPayload(message.getPayload());
properties = new AMQP.BasicProperties.Builder().contentType(contentType).contentEncoding(sourceProperties.getContentEncoding()).headers(sourceHeaders).deliveryMode(sourceProperties.getDeliveryMode()).priority(sourceProperties.getPriority()).correlationId(sourceProperties.getCorrelationId()).replyTo(sourceProperties.getReplyTo()).expiration(expiration).messageId(sourceProperties.getMessageId()).timestamp(sourceProperties.getTimestamp()).type(sourceProperties.getType()).userId(sourceProperties.getUserId()).appId(sourceProperties.getAppId()).build();
} else {
// Getting here means we have to work a little harder
final String defaultContentType = getDefaultContentTypeForPayload(message.getPayload());
body = getBodyFromPayload(message.getPayload());
final OutgoingRabbitMQMetadata metadata = message.getMetadata(OutgoingRabbitMQMetadata.class).orElse(new OutgoingRabbitMQMetadata.Builder().withContentType(defaultContentType).withExpiration(defaultTtl.map(String::valueOf).orElse(null)).build());
if (isTracingEnabled) {
// Create a new span for the outbound message and record updated tracing information in
// the message headers; this has to be done before we build the properties below
TracingUtils.createOutgoingTrace(message, metadata.getHeaders(), exchange, routingKey, attributeHeaders);
}
final Date timestamp = (metadata.getTimestamp() != null) ? Date.from(metadata.getTimestamp().toInstant()) : null;
// If not already specified, use the default content type for the message payload
final String contentType = (metadata.getContentType() != null) ? metadata.getContentType() : defaultContentType;
properties = new AMQP.BasicProperties.Builder().contentType(contentType).contentEncoding(metadata.getContentEncoding()).headers(metadata.getHeaders()).deliveryMode(metadata.getDeliveryMode()).priority(metadata.getPriority()).correlationId(metadata.getCorrelationId()).replyTo(metadata.getReplyTo()).expiration(metadata.getExpiration()).messageId(metadata.getMessageId()).timestamp(timestamp).type(metadata.getType()).userId(metadata.getUserId()).appId(metadata.getAppId()).clusterId(metadata.getClusterId()).build();
}
return new OutgoingRabbitMQMessage(routingKey, body, properties);
}
use of io.vertx.mutiny.core.buffer.Buffer in project smallrye-reactive-messaging by smallrye.
the class AmqpSinkTest method testSinkUsingMutinyBuffer.
@Test
@Timeout(30)
public void testSinkUsingMutinyBuffer() throws Exception {
int msgCount = 10;
CountDownLatch msgsReceived = new CountDownLatch(msgCount);
List<org.apache.qpid.proton.message.Message> messagesReceived = Collections.synchronizedList(new ArrayList<>(msgCount));
server = setupMockServerForTypeTest(messagesReceived, msgsReceived);
SubscriberBuilder<? extends Message<?>, Void> sink = createProviderAndSink(UUID.randomUUID().toString(), server.actualPort());
// noinspection unchecked
Multi.createFrom().range(0, 10).map(i -> new Buffer(new JsonObject().put(ID, HELLO + i).toBuffer())).map(Message::of).subscribe((Subscriber<? super Message<?>>) sink.build());
assertThat(msgsReceived.await(6, TimeUnit.SECONDS)).isTrue();
AtomicInteger count = new AtomicInteger();
messagesReceived.forEach(msg -> {
assertThat(msg.getContentType()).isEqualTo("application/octet-stream");
Section body = msg.getBody();
assertThat(body).isInstanceOf(Data.class);
byte[] receievedBytes = Binary.copy(((Data) body).getValue()).getArray();
byte[] expectedBytes = new JsonObject().put(ID, HELLO + count.get()).toBuffer().getBytes();
assertThat(receievedBytes).isEqualTo(expectedBytes);
count.incrementAndGet();
});
assertThat(count.get()).isEqualTo(msgCount);
}
use of io.vertx.mutiny.core.buffer.Buffer in project quarkus-config-extensions by quarkiverse.
the class VertxConsulConfigGateway method getValue.
@Override
public Uni<Response> getValue(String key) {
HttpRequest<Buffer> request = webClient.get(consulConfig.agent.hostPort.getPort(), consulConfig.agent.hostPort.getHostString(), "/v1/kv/" + key).ssl(consulConfig.agent.useHttps).putHeader("Accept", "application/json;charset=UTF-8");
if (consulConfig.agent.token.isPresent()) {
request.putHeader("Authorization", "Bearer " + consulConfig.agent.token.get());
}
log.debug("Attempting to look up value of key '" + key + "' from Consul.");
return request.send().map(r -> {
if (r.statusCode() != 200) {
log.debug("Look up of key '" + key + "' from Consul yielded a non success HTTP error-code: " + r.statusCode());
return null;
} else {
JsonArray jsonArray = r.bodyAsJsonArray();
if (jsonArray.size() != 1) {
throw new IllegalStateException("Consul returned an unexpected number of results when looking up value of key '" + key + "'");
}
JsonObject jsonObject = jsonArray.getJsonObject(0);
return new Response(jsonObject.getString("Key"), jsonObject.getString("Value"));
}
});
}
Aggregations