List of usage examples for com.rabbitmq.client Channel txSelect
Tx.SelectOk txSelect() throws IOException;
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(); DeclareOk declareOk = senderChannel.queueDeclare("testQueue", true, false, false, null); new Thread(new Runnable() { int received; long totalReceived; Channel consumerChannel;/*from w w w .j ava2 s . co m*/ 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(); for (int i = 0; i < 5; i++) { channel.basicPublish("", declareOk.getQueue(), MessageProperties.PERSISTENT_BASIC, "this is a test message !!!".getBytes()); }//from www . j a v a 2 s .c om 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(); for (int i = 0; i < 5; i++) { channel.basicPublish("", declareOk.getQueue(), MessageProperties.PERSISTENT_BASIC, "this is a test message !!!".getBytes()); }// w ww . j a v a 2 s . co m 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 w w . ja va 2 s . c om 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 */// w w w. j a v a2 s .c o m 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/*from ww w. j av a 2 s.co 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 ww w . j a v a 2s. 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; }
From source file:org.axonframework.eventhandling.amqp.spring.SpringAMQPEventBus.java
License:Apache License
@Override protected void prepareCommit(List<? extends EventMessage<?>> events) { Channel channel = connectionFactory.createConnection().createChannel(isTransactional); try {// w w w . j a v a2 s. c o m if (isTransactional) { channel.txSelect(); } else if (waitForAck) { channel.confirmSelect(); } for (EventMessage event : events) { AMQPMessage amqpMessage = messageConverter.createAMQPMessage(event); doSendMessage(channel, amqpMessage); } if (CurrentUnitOfWork.isStarted()) { CurrentUnitOfWork.get().onCommit(u -> { if ((isTransactional || waitForAck) && !channel.isOpen()) { throw new EventPublicationFailedException( "Unable to Commit UnitOfWork changes to AMQP: Channel is closed.", channel.getCloseReason()); } }); CurrentUnitOfWork.get().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); }); CurrentUnitOfWork.get().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.mule.transport.amqp.internal.client.ChannelHandler.java
License:Open Source License
public Channel getTransactedResourceChannel(ImmutableEndpoint endpoint) throws IOException, TransactionException { final byte action = endpoint.getTransactionConfig().getAction(); final boolean mayUseChannelFromTransaction = action == TransactionConfig.ACTION_BEGIN_OR_JOIN || action == TransactionConfig.ACTION_JOIN_IF_POSSIBLE || action == TransactionConfig.ACTION_INDIFFERENT; final boolean mustUseChannelFromTransaction = action == TransactionConfig.ACTION_ALWAYS_JOIN; final Transaction transaction = TransactionCoordination.getInstance().getTransaction(); if (transaction instanceof AmqpTransaction) { if (mustUseChannelFromTransaction || mayUseChannelFromTransaction) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Using transacted channel from current transaction: " + transaction); }// w w w . j a va 2 s. c o m return ((AmqpTransaction) transaction).getTransactedChannel(); } } else if (transaction instanceof DelegateTransaction) { // we can't use the current endpoint channel because it may get closed (if the // endpoint instance is destroyed) while the transaction block is not done with... final Channel channel = createChannel(endpoint); channel.txSelect(); // we wrap the channel so the transaction will know it can safely close it an // commit/rollback transaction.bindResource(channel.getConnection(), new CloseableChannelWrapper(channel)); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Created transacted channel for delegate transaction: " + transaction); } return channel; } else { if (mustUseChannelFromTransaction) { throw new IllegalTransactionStateException(MessageFactory .createStaticMessage("No active AMQP transaction found for endpoint: " + endpoint)); } } return null; }