use of com.rabbitmq.client.DeliverCallback in project jms-messaging-plugin by jenkinsci.
the class RabbitMQMessagingWorker method waitForMessage.
@Override
public String waitForMessage(Run<?, ?> build, TaskListener listener, ProviderData pdata) {
RabbitMQSubscriberProviderData pd = (RabbitMQSubscriberProviderData) pdata;
try {
if (connection == null || !connection.isOpen()) {
connect();
}
if (channel == null || !channel.isOpen()) {
this.channel = connection.createChannel();
}
channel.exchangeDeclarePassive(exchangeName);
channel.queueBind(getQueue(provider), exchangeName, this.topic);
} catch (Exception ex) {
log.severe("Connection to broker can't be established!");
log.severe(ExceptionUtils.getStackTrace(ex));
listener.error("Connection to broker can't be established!");
listener.error(ExceptionUtils.getStackTrace(ex));
return null;
}
log.info("Waiting for message.");
listener.getLogger().println("Waiting for message.");
for (MsgCheck msgCheck : pd.getChecks()) {
log.info(" with check: " + msgCheck.toString());
listener.getLogger().println(" with check: " + msgCheck);
}
Integer timeout = (pd.getTimeout() != null ? pd.getTimeout() : RabbitMQSubscriberProviderData.DEFAULT_TIMEOUT_IN_MINUTES);
log.info(" with timeout: " + timeout + " minutes");
listener.getLogger().println(" with timeout: " + timeout + " minutes");
// Create deliver callback to listen for messages
DeliverCallback deliverCallback = (consumerTag, delivery) -> {
String json = new String(delivery.getBody(), StandardCharsets.UTF_8);
listener.getLogger().println("Received '" + delivery.getEnvelope().getRoutingKey() + "':\n" + "Message id: '" + delivery.getProperties().getMessageId() + "'\n'" + json + "'");
log.info("Received '" + delivery.getEnvelope().getRoutingKey() + "':\n" + "Message id: '" + delivery.getProperties().getMessageId() + "'\n'" + json + "'");
RabbitMQMessage message = new RabbitMQMessage(delivery.getEnvelope().getRoutingKey(), json, delivery.getProperties().getMessageId());
message.setTimestamp(new Date().getTime());
message.setDeliveryTag(delivery.getEnvelope().getDeliveryTag());
messageQueue.add(message);
};
String consumerTag = null;
long startTime = new Date().getTime();
int timeoutInMs = timeout * 60 * 1000;
try {
consumerTag = channel.basicConsume(getQueue(provider), deliverCallback, (CancelCallback) null);
while ((new Date().getTime() - startTime) < timeoutInMs) {
if (!messageQueue.isEmpty()) {
RabbitMQMessage message = messageQueue.poll();
log.info("Obtained message from queue: " + message.toJson());
if (!provider.verify(message.getBodyJson(), pd.getChecks(), jobname)) {
channel.basicAck(message.getDeliveryTag(), false);
continue;
}
listener.getLogger().println("Message: '" + message.getMsgId() + "' was succesfully checked.");
if (build != null) {
if (StringUtils.isNotEmpty(pd.getVariable())) {
EnvVars vars = new EnvVars();
vars.put(pd.getVariable(), message.getBodyJson());
build.addAction(new CIEnvironmentContributingAction(vars));
}
}
channel.basicAck(message.getDeliveryTag(), false);
return message.getBodyJson();
}
if (interrupt) {
return null;
}
TimeUnit.MILLISECONDS.sleep(500);
}
log.severe("Timed out waiting for message!");
listener.getLogger().println("Timed out waiting for message!");
} catch (Exception e) {
// for more info
if (e.getClass() == InterruptedException.class) {
Thread.currentThread().interrupt();
}
log.log(Level.SEVERE, "Unhandled exception waiting for message.", e);
} finally {
try {
if (consumerTag != null) {
channel.basicCancel(consumerTag);
}
channel.close();
} catch (Exception e) {
listener.getLogger().println("exception in finally");
}
}
return null;
}
use of com.rabbitmq.client.DeliverCallback in project olive by ClareTung.
the class RPCServer method main.
public static void main(String[] argv) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
try (Connection connection = factory.newConnection();
Channel channel = connection.createChannel()) {
channel.queueDeclare(RPC_QUEUE_NAME, false, false, false, null);
channel.queuePurge(RPC_QUEUE_NAME);
channel.basicQos(1);
System.out.println(" [x] Awaiting RPC requests");
Object monitor = new Object();
DeliverCallback deliverCallback = (consumerTag, delivery) -> {
AMQP.BasicProperties replyProps = new AMQP.BasicProperties.Builder().correlationId(delivery.getProperties().getCorrelationId()).build();
String response = "";
try {
String message = new String(delivery.getBody(), "UTF-8");
int n = Integer.parseInt(message);
System.out.println(" [.] fib(" + message + ")");
response += fib(n);
} catch (RuntimeException e) {
System.out.println(" [.] " + e.toString());
} finally {
channel.basicPublish("", delivery.getProperties().getReplyTo(), replyProps, response.getBytes("UTF-8"));
channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
// RabbitMq consumer worker thread notifies the RPC server owner thread
synchronized (monitor) {
monitor.notify();
}
}
};
channel.basicConsume(RPC_QUEUE_NAME, false, deliverCallback, (consumerTag -> {
}));
// Wait and be prepared to consume the message from RPC client.
while (true) {
synchronized (monitor) {
try {
monitor.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
use of com.rabbitmq.client.DeliverCallback in project olive by ClareTung.
the class ReceiveLogsTopic method main.
public static void main(String[] argv) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare(EXCHANGE_NAME, "topic");
String queueName = channel.queueDeclare().getQueue();
// 关注所有的授权日志、所有info和waring级别的日志
String[] bindingKeys = { "auth.*", "*.info", "#.warning" };
for (String bindingKey : bindingKeys) {
// 关注所有级别的日志(多重绑定)
channel.queueBind(queueName, EXCHANGE_NAME, bindingKey);
}
System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
DeliverCallback deliverCallback = (consumerTag, delivery) -> {
String message = new String(delivery.getBody(), "UTF-8");
System.out.println(" [x] Received '" + delivery.getEnvelope().getRoutingKey() + "':'" + message + "'");
};
channel.basicConsume(queueName, true, deliverCallback, consumerTag -> {
});
}
use of com.rabbitmq.client.DeliverCallback in project olive by ClareTung.
the class ReceiveLogsTopic2 method main.
public static void main(String[] argv) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare(EXCHANGE_NAME, "topic");
String queueName = channel.queueDeclare().getQueue();
// 只关注核心错误级别的日志,然后记录到文件中去
String severity = "kern.error";
channel.queueBind(queueName, EXCHANGE_NAME, severity);
System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
DeliverCallback deliverCallback = (consumerTag, delivery) -> {
String message = new String(delivery.getBody(), "UTF-8");
print2File(message);
};
channel.basicConsume(queueName, true, deliverCallback, consumerTag -> {
});
}
use of com.rabbitmq.client.DeliverCallback in project olive by ClareTung.
the class Worker method main.
public static void main(String[] argv) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
final Connection connection = factory.newConnection();
final Channel channel = connection.createChannel();
// 持久化
boolean durable = true;
channel.queueDeclare(TASK_QUEUE_NAME, durable, false, false, null);
System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
// 公平分发
channel.basicQos(1);
DeliverCallback deliverCallback = (consumerTag, delivery) -> {
String message = new String(delivery.getBody(), "UTF-8");
System.out.println(" [x] Received '" + message + "'");
try {
doWork(message);
} finally {
System.out.println(" [x] Done");
// 消息确认
channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
}
};
channel.basicConsume(TASK_QUEUE_NAME, false, deliverCallback, consumerTag -> {
});
}
Aggregations