List of usage examples for com.rabbitmq.client Channel txCommit
Tx.CommitOk txCommit() throws IOException;
From source file:com.kurento.kmf.rabbitmq.RabbitTemplate.java
License:Apache License
@Override public Message receive(final String queueName) { return execute(new ChannelCallback<Message>() { @Override// w ww. jav a2 s. c om public Message doInRabbit(Channel channel) throws IOException { GetResponse response = channel.basicGet(queueName, !isChannelTransacted()); // Response can be null is the case that there is no message on // the queue. if (response != null) { long deliveryTag = response.getEnvelope().getDeliveryTag(); if (isChannelLocallyTransacted(channel)) { channel.basicAck(deliveryTag, false); channel.txCommit(); } else if (isChannelTransacted()) { // Not locally transacted but it is transacted so it // could be synchronized with an external transaction ConnectionFactoryUtils.registerDeliveryTag(getConnectionFactory(), channel, deliveryTag); } return RabbitTemplate.this.buildMessageFromResponse(response); } return null; } }); }
From source file:com.kurento.kmf.rabbitmq.RabbitTemplate.java
License:Apache License
@SuppressWarnings("unchecked") private <R, S> boolean doReceiveAndReply(final String queueName, final ReceiveAndReplyCallback<R, S> callback, final ReplyToAddressCallback<S> replyToAddressCallback) throws AmqpException { return this.execute(new ChannelCallback<Boolean>() { @Override/* w w w . j av a 2 s . c o m*/ public Boolean doInRabbit(Channel channel) throws Exception { boolean channelTransacted = RabbitTemplate.this.isChannelTransacted(); GetResponse response = channel.basicGet(queueName, !channelTransacted); // Response can be null in the case that there is no message on // the queue. if (response != null) { long deliveryTag = response.getEnvelope().getDeliveryTag(); boolean channelLocallyTransacted = RabbitTemplate.this.isChannelLocallyTransacted(channel); if (channelLocallyTransacted) { channel.basicAck(deliveryTag, false); } else if (channelTransacted) { // Not locally transacted but it is transacted so it // could be synchronized with an external transaction ConnectionFactoryUtils.registerDeliveryTag(RabbitTemplate.this.getConnectionFactory(), channel, deliveryTag); } Message receiveMessage = RabbitTemplate.this.buildMessageFromResponse(response); Object receive = receiveMessage; if (!(ReceiveAndReplyMessageCallback.class.isAssignableFrom(callback.getClass()))) { receive = RabbitTemplate.this.getRequiredMessageConverter().fromMessage(receiveMessage); } S reply; try { reply = callback.handle((R) receive); } catch (ClassCastException e) { StackTraceElement[] trace = e.getStackTrace(); if (trace[0].getMethodName().equals("handle") && trace[1].getFileName().equals("RabbitTemplate.java")) { throw new IllegalArgumentException("ReceiveAndReplyCallback '" + callback + "' can't handle received object '" + receive + "'", e); } else { throw e; } } if (reply != null) { Address replyTo = replyToAddressCallback.getReplyToAddress(receiveMessage, reply); Message replyMessage = RabbitTemplate.this.convertMessageIfNecessary(reply); MessageProperties receiveMessageProperties = receiveMessage.getMessageProperties(); MessageProperties replyMessageProperties = replyMessage.getMessageProperties(); Object correlation = RabbitTemplate.this.correlationKey == null ? receiveMessageProperties.getCorrelationId() : receiveMessageProperties.getHeaders().get(RabbitTemplate.this.correlationKey); if (RabbitTemplate.this.correlationKey == null || correlation == null) { // using standard correlationId property if (correlation == null) { String messageId = receiveMessageProperties.getMessageId(); if (messageId != null) { correlation = messageId.getBytes(RabbitTemplate.this.encoding); } } replyMessageProperties.setCorrelationId((byte[]) correlation); } else { replyMessageProperties.setHeader(RabbitTemplate.this.correlationKey, correlation); } // 'doSend()' takes care about 'channel.txCommit()'. RabbitTemplate.this.doSend(channel, replyTo.getExchangeName(), replyTo.getRoutingKey(), replyMessage, null); } else if (channelLocallyTransacted) { channel.txCommit(); } return true; } return false; } }); }
From source file:joram.amqp.PersistenceKillTest.java
License:Open Source License
public void killingTest() throws Exception { senderConnection = new LiveServerConnection("sender", "localhost", 5672, null, null); receiverConnection = new LiveServerConnection("receiver", "localhost", 5672, null, null); senderConnection.startLiveConnection(); receiverConnection.startLiveConnection(); Channel senderChannel = senderConnection.getConnection().createChannel(); senderChannel.txSelect();/* w w w. j ava2s . com*/ DeclareOk declareOk = senderChannel.queueDeclare("testQueue", true, false, false, null); new Thread(new Runnable() { int received; long totalReceived; Channel consumerChannel; QueueingConsumer consumer; // Consumer thread public void run() { try { consumerChannel = receiverConnection.getConnection().createChannel(); consumerChannel.txSelect(); consumer = new QueueingConsumer(consumerChannel); consumerChannel.basicConsume("testQueue", false, consumer); } catch (Exception exc) { exc.printStackTrace(); } while (true) { QueueingConsumer.Delivery delivery; try { delivery = consumer.nextDelivery(); long receivedNb = Long.parseLong(new String(delivery.getBody())); consumer.getChannel().basicAck(delivery.getEnvelope().getDeliveryTag(), false); try { Thread.sleep(1); } catch (InterruptedException exc1) { } if (receivedNb < totalReceived) { System.out.println("Duplicate received: " + receivedNb); continue; } // We can receive duplicates but can't miss one message // One duplicate if the channel is transacted, multiple if it is not assertEquals(totalReceived, receivedNb); totalReceived++; received++; consumerChannel.txCommit(); if (received == nbMsgRound) { received = 0; synchronized (lock) { lock.notify(); } } if (totalReceived == nbMsgRound * nbRounds) { consumer.getChannel().close(); return; } } catch (Exception ie) { if (totalReceived == nbRounds * nbMsgRound) { return; } System.out.println("Consumer connection broken. Reconnect."); while (!receiverConnection.isConnectionOpen()) { try { Thread.sleep(100); } catch (InterruptedException exc) { exc.printStackTrace(); } } try { consumerChannel = receiverConnection.getConnection().createChannel(); consumerChannel.txSelect(); consumer = new QueueingConsumer(consumerChannel); consumerChannel.basicConsume("testQueue", false, consumer); } catch (IOException exc) { exc.printStackTrace(); } System.out.println("Consumer Reconnected --- totalReceived = " + totalReceived); continue; } } } }).start(); long start = System.nanoTime(); // Killer thread new Thread(new Runnable() { public void run() { try { Thread.sleep(5000); System.out.println("Kill server"); killAgentServer((short) 0); Thread.sleep(5000); startAgentServer((short) 0); System.out.println("server restarted."); } catch (Exception exc) { exc.printStackTrace(); } } }).start(); // Sender for (int i = 0; i < nbRounds; i++) { if (i % 20 == 0) { long delta = System.nanoTime() - start; System.out.println("Round " + i + " " + ((i * nbMsgRound * 1000000000L) / delta) + " msg/s"); } try { for (int j = 0; j < nbMsgRound; j++) { senderChannel.basicPublish("", declareOk.getQueue(), MessageProperties.PERSISTENT_BASIC, new Long(i * nbMsgRound + j).toString().getBytes()); } synchronized (lock) { senderChannel.txCommit(); lock.wait(); } } catch (Exception exc) { i--; System.out.println("Sender connection broken. Reconnect."); while (!senderConnection.isConnectionOpen()) { Thread.sleep(100); } senderChannel = senderConnection.getConnection().createChannel(); senderChannel.txSelect(); System.out.println("Sender Reconnected"); Thread.sleep(1000); System.out.println("Restart Sender"); } } long delta = System.nanoTime() - start; System.out.println(delta / 1000000L + " ms"); System.out.println(((nbRounds * nbMsgRound * 1000000000L) / delta) + " msg/s"); senderChannel.queueDelete(declareOk.getQueue()); senderChannel.close(); senderConnection.stopLiveConnection(); receiverConnection.stopLiveConnection(); }
From source file:joram.amqp.PersistenceSimpleTest.java
License:Open Source License
public void recover1() throws Exception { ConnectionFactory cnxFactory = new ConnectionFactory(); Connection connection = cnxFactory.newConnection(); Channel channel = connection.createChannel(); DeclareOk declareOk = channel.queueDeclare("testqueue", true, false, false, null); channel.txSelect();/*from w w w .j a v a 2 s .c o m*/ for (int i = 0; i < 5; i++) { channel.basicPublish("", declareOk.getQueue(), MessageProperties.PERSISTENT_BASIC, "this is a test message !!!".getBytes()); } channel.txCommit(); killAgentServer((short) 0); startAgentServer((short) 0); connection = cnxFactory.newConnection(); channel = connection.createChannel(); declareOk = channel.queueDeclarePassive("testqueue"); for (int i = 0; i < 5; i++) { GetResponse msg = channel.basicGet("testqueue", true); assertNotNull(msg); assertEquals("this is a test message !!!", new String(msg.getBody())); } GetResponse msg = channel.basicGet("testqueue", true); assertNull(msg); channel.queueDelete(declareOk.getQueue()); }
From source file:joram.amqp.PersistenceSimpleTest.java
License:Open Source License
public void recover2() throws Exception { ConnectionFactory cnxFactory = new ConnectionFactory(); Connection connection = cnxFactory.newConnection(); Channel channel = connection.createChannel(); DeclareOk declareOk = channel.queueDeclare("testqueue", true, false, false, null); channel.txSelect();//from w w w .j a v a2 s. c om for (int i = 0; i < 5; i++) { channel.basicPublish("", declareOk.getQueue(), MessageProperties.PERSISTENT_BASIC, "this is a test message !!!".getBytes()); } channel.txCommit(); killAgentServer((short) 0); startAgentServer((short) 0); Thread.sleep(500); connection = cnxFactory.newConnection(); channel = connection.createChannel(); declareOk = channel.queueDeclarePassive("testqueue"); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(declareOk.getQueue(), true, consumer); for (int i = 0; i < 5; i++) { Delivery msg = consumer.nextDelivery(1000); assertNotNull(msg); assertEquals("this is a test message !!!", new String(msg.getBody())); } Delivery msg = consumer.nextDelivery(1000); assertNull(msg); channel.queueDelete(declareOk.getQueue()); }
From source file:org.axonframework.amqp.eventhandling.RabbitMQBenchmark.java
License:Apache License
private static List<Thread> createChannelCreatingThreads(final Connection connection, final String queueName, final boolean transactional) { List<Thread> threads = new ArrayList<>(); for (int i = 0; i < THREAD_COUNT; i++) { threads.add(new Thread(() -> { try { for (int t = 0; t < COMMIT_COUNT; t++) { final Channel localChannel = connection.createChannel(); if (transactional) { localChannel.txSelect(); }/*from w w w . j a va2 s . c o m*/ for (int j = 0; j < COMMIT_SIZE; j++) { localChannel.basicPublish("", queueName, null, ("message" + t).getBytes("UTF-8")); } if (transactional) { localChannel.txCommit(); } localChannel.close(); } } catch (IOException | TimeoutException e) { e.printStackTrace(); } })); } return threads; }
From source file:org.axonframework.amqp.eventhandling.RabbitMQBenchmark.java
License:Apache License
private static List<Thread> createChannelPoolSharingThreads(final Connection connection, final String queueName) { List<Thread> threads = new ArrayList<>(); final Queue<Channel> channels = new ArrayBlockingQueue<>(15); for (int i = 0; i < THREAD_COUNT; i++) { threads.add(new Thread(() -> { try { for (int t = 0; t < COMMIT_COUNT; t++) { Channel localChannel = channels.poll(); if (localChannel == null) { localChannel = connection.createChannel(); }/* w ww. j a v a 2 s . c o m*/ localChannel.txSelect(); for (int j = 0; j < COMMIT_SIZE; j++) { localChannel.basicPublish("", queueName, null, ("message" + t).getBytes("UTF-8")); } localChannel.txCommit(); if (!channels.offer(localChannel)) { localChannel.close(); } } } catch (IOException | TimeoutException e) { e.printStackTrace(); } })); } return threads; }
From source file:org.axonframework.amqp.eventhandling.spring.SpringAMQPPublisher.java
License:Apache License
/** * Sends the given {@code events} to the configured AMQP Exchange. It takes the current Unit of Work into account * when available. Otherwise, it simply publishes directly. * * @param events the events to publish on the AMQP Message Broker *///from w ww . j ava 2 s.c om protected void send(List<? extends EventMessage<?>> events) { Channel channel = connectionFactory.createConnection().createChannel(isTransactional); try { if (isTransactional) { channel.txSelect(); } else if (waitForAck) { channel.confirmSelect(); } for (EventMessage event : events) { AMQPMessage amqpMessage = messageConverter.createAMQPMessage(event); doSendMessage(channel, amqpMessage); } if (CurrentUnitOfWork.isStarted()) { UnitOfWork<?> unitOfWork = CurrentUnitOfWork.get(); unitOfWork.onCommit(u -> { if ((isTransactional || waitForAck) && !channel.isOpen()) { throw new EventPublicationFailedException( "Unable to Commit UnitOfWork changes to AMQP: Channel is closed.", channel.getCloseReason()); } }); unitOfWork.afterCommit(u -> { try { if (isTransactional) { channel.txCommit(); } else if (waitForAck) { try { channel.waitForConfirmsOrDie(publisherAckTimeout); } catch (IOException ex) { throw new EventPublicationFailedException( "Failed to receive acknowledgements for all events", ex); } catch (TimeoutException ex) { throw new EventPublicationFailedException( "Timeout while waiting for publisher acknowledgements", ex); } } } catch (IOException e) { logger.warn("Unable to commit transaction on channel.", e); } catch (InterruptedException e) { logger.warn("Interrupt received when waiting for message confirms."); Thread.currentThread().interrupt(); } tryClose(channel); }); unitOfWork.onRollback(u -> { try { if (isTransactional) { channel.txRollback(); } } catch (IOException ex) { logger.warn("Unable to rollback transaction on channel.", ex); } tryClose(channel); }); } else if (isTransactional) { channel.txCommit(); } else if (waitForAck) { channel.waitForConfirmsOrDie(); } } catch (IOException e) { if (isTransactional) { tryRollback(channel); } throw new EventPublicationFailedException("Failed to dispatch Events to the Message Broker.", e); } catch (ShutdownSignalException e) { throw new EventPublicationFailedException("Failed to dispatch Events to the Message Broker.", e); } catch (InterruptedException e) { logger.warn("Interrupt received when waiting for message confirms."); Thread.currentThread().interrupt(); } finally { if (!CurrentUnitOfWork.isStarted()) { tryClose(channel); } } }
From source file:org.axonframework.eventhandling.amqp.RabbitMQBenchmark.java
License:Apache License
private static List<Thread> createChannelCreatingThreads(final Connection connection, final String queueName, final boolean transactional) { List<Thread> threads = new ArrayList<Thread>(); for (int i = 0; i < THREAD_COUNT; i++) { threads.add(new Thread(new Runnable() { @Override/* w w w.j a v a2 s. c o m*/ public void run() { try { for (int t = 0; t < COMMIT_COUNT; t++) { final Channel localChannel = connection.createChannel(); if (transactional) { localChannel.txSelect(); } for (int j = 0; j < COMMIT_SIZE; j++) { localChannel.basicPublish("", queueName, null, ("message" + t).getBytes("UTF-8")); } if (transactional) { localChannel.txCommit(); } localChannel.close(); } } catch (IOException e) { e.printStackTrace(); } } })); } return threads; }
From source file:org.axonframework.eventhandling.amqp.RabbitMQBenchmark.java
License:Apache License
private static List<Thread> createChannelPoolSharingThreads(final Connection connection, final String queueName) { List<Thread> threads = new ArrayList<Thread>(); final Queue<Channel> channels = new ArrayBlockingQueue<Channel>(15); for (int i = 0; i < THREAD_COUNT; i++) { threads.add(new Thread(new Runnable() { @Override/*from w w w. jav a2s.c o m*/ public void run() { try { for (int t = 0; t < COMMIT_COUNT; t++) { Channel localChannel = channels.poll(); if (localChannel == null) { localChannel = connection.createChannel(); } localChannel.txSelect(); for (int j = 0; j < COMMIT_SIZE; j++) { localChannel.basicPublish("", queueName, null, ("message" + t).getBytes("UTF-8")); } localChannel.txCommit(); if (!channels.offer(localChannel)) { localChannel.close(); } } } catch (IOException e) { e.printStackTrace(); } } })); } return threads; }