use of com.rabbitmq.client.CancelCallback in project hummer-framework by hummer-team.
the class RabbitMqConsumer method start.
public void start() throws IOException, NoSuchAlgorithmException, KeyManagementException, URISyntaxException, TimeoutException {
createConnection();
channel = connection.createChannel();
channel.queueDeclare(queueConfig.getQueueName(), queueConfig.isDurable(), queueConfig.isExclusive(), queueConfig.isAutoDelete(), queueConfig.getArguments());
if (StringUtils.isNotEmpty(queueConfig.getRouteKey())) {
channel.queueBind(queueConfig.getQueueName(), queueConfig.getExchange(), queueConfig.getRouteKey());
}
channel.addShutdownListener(new ShutdownListener() {
@Override
public void shutdownCompleted(ShutdownSignalException e) {
if (!exitSignal) {
log.warn("mq shutdown completed, reason is ", e);
}
}
});
channel.addReturnListener(new ReturnListener() {
@Override
public void handleReturn(int replyCode, String replyText, String exchange, String routingKey, AMQP.BasicProperties properties, byte[] body) throws IOException {
log.info("consumer return {}", replyText);
}
});
channel.basicQos(queueConfig.getQos());
MqDeserializer mqDeserializer = DeserializerFactory.deserializer(queueConfig.getSerializerType());
consumerTag = channel.basicConsume(queueConfig.getQueueName(), queueConfig.isAutoAck(), new DeliverCallback() {
@Override
public void handle(String consumerTag, Delivery message) throws IOException {
T data;
try {
data = mqDeserializer.deserialize(message.getBody(), handler.messageType());
} catch (Exception e) {
log.error("deserialize message failed, topic is {} message type is {}", topic, handler.messageType(), e);
return;
}
MessageData<T> messageData = new MessageData<>();
messageData.setData(data);
messageData.setQueueOffset(message.getEnvelope().getDeliveryTag());
messageData.setProperties(Optional.ofNullable(message.getProperties().getHeaders()).orElse(Collections.emptyMap()).entrySet().stream().collect(Collectors.toConcurrentMap(Map.Entry::getKey, e -> String.valueOf(e.getValue()))));
ListenableFuture<Long> future = ((ListeningExecutorService) executorService).submit(() -> handler.handlerAndReturnOffset(messageData));
Futures.addCallback(future, new FutureCallback<>() {
@Override
public void onSuccess(@Nullable Long offset) {
ack(offset);
}
@Override
public void onFailure(Throwable throwable) {
log.warn("business handler message failed {}", topic, throwable);
}
}, executorService);
}
}, new CancelCallback() {
@Override
public void handle(String consumerTag) throws IOException {
log.warn("consumer cancel {}", consumerTag);
}
}, new ConsumerShutdownSignalCallback() {
@Override
public void handleShutdownSignal(String consumerTag, ShutdownSignalException sig) {
log.warn("consumer shutdown {} ", consumerTag, sig);
}
});
log.info("consumer {} start ok,queueConfig is {}", consumerTag, queueConfig);
}
use of com.rabbitmq.client.CancelCallback 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.CancelCallback in project Iot-now-start by Dongboy111.
the class Work01 method main.
public static void main(String[] args) throws IOException, TimeoutException {
Channel channel = RabbitMqUtils.getChannel();
// 声明接受消息
DeliverCallback deliverCallback = (consumerTag, message) -> {
System.out.println("接受到的消息:" + new String(message.getBody()));
};
// 取消消息消费
CancelCallback cancelCallback = cousumerTag -> {
System.out.println("消费被中断");
};
System.out.println("C2等到接收消息,,,,");
channel.basicConsume(QUEUE_NAME, true, deliverCallback, cancelCallback);
// 不关闭的话一直等待
}
use of com.rabbitmq.client.CancelCallback in project jms-messaging-plugin by jenkinsci.
the class RabbitMQMessagingWorker method subscribe.
@Override
public boolean subscribe(String jobname, String selector) {
if (interrupt) {
return true;
}
if (this.topic != null) {
while (!Thread.currentThread().isInterrupted()) {
try {
if (connection == null || !connection.isOpen()) {
if (!connect()) {
return false;
}
}
if (channel == null || !channel.isOpen()) {
this.channel = connection.createChannel();
log.info("Subscribing job '" + jobname + "' to " + this.topic + " topic.");
String queueName = getQueue(provider);
try {
// Check if queue exists
channel.queueDeclarePassive(queueName);
} catch (IOException e) {
// Request new queue - durable false, exclusive true, autodelete true
this.channel = connection.createChannel();
channel.queueDeclare(queueName, false, true, true, null);
}
channel.exchangeDeclarePassive(exchangeName);
channel.queueBind(queueName, exchangeName, this.topic);
// Create deliver callback to listen for messages
DeliverCallback deliverCallback = (consumerTag, delivery) -> {
String json = new String(delivery.getBody(), StandardCharsets.UTF_8);
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);
};
this.consumerTag = channel.basicConsume(queueName, deliverCallback, (CancelCallback) null);
log.info("Successfully subscribed job '" + jobname + "' to topic '" + this.topic + "'.");
} else {
log.info("Already subscribed job '" + jobname + "' to topic '" + this.topic + "'.");
}
return true;
} catch (Exception ex) {
// Either we were interrupted, or something else went
// wrong. If we were interrupted, then we will jump ship
// on the next iteration. If something else happened,
// then we just unsubscribe here, sleep, so that we may
// try again on the next iteration.
log.log(Level.SEVERE, "Eexception raised while subscribing job '" + jobname + "', retrying in " + RETRY_MINUTES + " minutes.", ex);
if (!Thread.currentThread().isInterrupted()) {
unsubscribe(jobname);
try {
Thread.sleep(RETRY_MINUTES * 60 * 1000);
} catch (InterruptedException ie) {
// We were interrupted while waiting to retry.
// We will jump ship on the next iteration.
// NB: The interrupt flag was cleared when
// InterruptedException was thrown. We have to
// re-install it to make sure we eventually
// leave this thread.
Thread.currentThread().interrupt();
}
}
}
}
}
return false;
}
Aggregations