Example usage for com.rabbitmq.client Channel txSelect

List of usage examples for com.rabbitmq.client Channel txSelect

Introduction

In this page you can find the example usage for com.rabbitmq.client Channel txSelect.

Prototype

Tx.SelectOk txSelect() throws IOException;

Source Link

Document

Enables TX mode on this channel.

Usage

From source file:org.springframework.amqp.rabbit.connection.CachingConnectionFactoryTests.java

License:Apache License

@Test
public void testTransactionalAndNonTransactionalChannelsSegregated() throws IOException {
    com.rabbitmq.client.ConnectionFactory mockConnectionFactory = mock(
            com.rabbitmq.client.ConnectionFactory.class);
    com.rabbitmq.client.Connection mockConnection = mock(com.rabbitmq.client.Connection.class);
    Channel mockChannel1 = mock(Channel.class);
    Channel mockChannel2 = mock(Channel.class);

    when(mockConnectionFactory.newConnection((ExecutorService) null)).thenReturn(mockConnection);
    when(mockConnection.createChannel()).thenReturn(mockChannel1).thenReturn(mockChannel2);
    when(mockConnection.isOpen()).thenReturn(true);

    // Called during physical close
    when(mockChannel1.isOpen()).thenReturn(true);
    when(mockChannel2.isOpen()).thenReturn(true);

    CachingConnectionFactory ccf = new CachingConnectionFactory(mockConnectionFactory);
    ccf.setChannelCacheSize(1);/*www .  j  av a2s  .c  o m*/

    Connection con = ccf.createConnection();

    Channel channel1 = con.createChannel(true);
    channel1.txSelect();
    channel1.close(); // should be ignored, and add last into channel cache.
    /*
     * When a channel is created as non-transactional we should create a new one.
     */
    Channel channel2 = con.createChannel(false);
    channel2.close(); // should be ignored, and add last into channel cache.
    assertNotSame(channel1, channel2);

    Channel ch1 = con.createChannel(true); // remove first entry in cache (channel1)
    Channel ch2 = con.createChannel(false); // create new channel

    assertNotSame(ch1, ch2);
    assertSame(ch1, channel1); // The non-transactional one
    assertSame(ch2, channel2);

    ch1.close();
    ch2.close();

    verify(mockConnection, times(2)).createChannel();

    con.close(); // should be ignored

    verify(mockConnection, never()).close();
    verify(mockChannel1, never()).close();
    verify(mockChannel2, never()).close();

    @SuppressWarnings("unchecked")
    List<Channel> notxlist = (List<Channel>) ReflectionTestUtils.getField(ccf,
            "cachedChannelsNonTransactional");
    assertEquals(1, notxlist.size());
    @SuppressWarnings("unchecked")
    List<Channel> txlist = (List<Channel>) ReflectionTestUtils.getField(ccf, "cachedChannelsTransactional");
    assertEquals(1, txlist.size());

}

From source file:org.springframework.amqp.rabbit.connection.RabbitUtils.java

License:Apache License

/**
 * Declare to that broker that a channel is going to be used transactionally, and convert exceptions that arise.
 *
 * @param channel the channel to use/*from w  w w .  j a v a  2s . c  o m*/
 */
public static void declareTransactional(Channel channel) {
    try {
        channel.txSelect();
    } catch (IOException e) {
        throw RabbitExceptionTranslator.convertRabbitAccessException(e);
    }
}

From source file:org.springframework.amqp.rabbit.connection.SimpleConnection.java

License:Apache License

public Channel createChannel(boolean transactional) {
    try {//from  ww w  .  ja v  a2s. c  o m
        Channel channel = delegate.createChannel();
        if (transactional) {
            // Just created so we want to start the transaction
            channel.txSelect();
        }
        return channel;
    } catch (IOException e) {
        throw RabbitExceptionTranslator.convertRabbitAccessException(e);
    }
}

From source file:org.springframework.amqp.rabbit.MulticastMain.java

License:Mozilla Public License

public static void main(String[] args) {
    Options options = getOptions();/*from   w  w  w.ja  v a 2 s  .  co m*/
    CommandLineParser parser = new GnuParser();
    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption('?')) {
            usage(options);
            System.exit(0);
        }

        String hostName = strArg(cmd, 'h', "localhost");
        int portNumber = intArg(cmd, 'p', AMQP.PROTOCOL.PORT);
        String exchangeType = strArg(cmd, 't', "direct");
        String exchangeName = strArg(cmd, 'e', exchangeType);
        int samplingInterval = intArg(cmd, 'i', 1);
        int rateLimit = intArg(cmd, 'r', 0);
        int producerCount = intArg(cmd, 'x', 1);
        int messageCount = intArg(cmd, 'N', 0);
        int consumerCount = intArg(cmd, 'y', 1);
        int connectionCount = cmd.hasOption('c') ? 1 : consumerCount;
        int producerTxSize = intArg(cmd, 'm', 0);
        int consumerTxSize = intArg(cmd, 'n', 0);
        boolean autoAck = cmd.hasOption('a');
        int prefetchCount = intArg(cmd, 'q', 0);
        int minMsgSize = intArg(cmd, 's', 0);
        int timeLimit = intArg(cmd, 'z', 0);
        List<String> flags = lstArg(cmd, 'f');
        int frameMax = intArg(cmd, 'M', 0);
        int heartbeat = intArg(cmd, 'b', 0);

        // setup
        String id = UUID.randomUUID().toString();
        Stats stats = new Stats(1000L * samplingInterval);
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(hostName);
        factory.setPort(portNumber);
        factory.setRequestedFrameMax(frameMax);
        factory.setRequestedHeartbeat(heartbeat);

        Connection[] consumerConnections = new Connection[connectionCount];
        for (int i = 0; i < connectionCount; i++) {
            Connection conn = factory.newConnection();
            consumerConnections[i] = conn;
        }
        Thread[] consumerThreads = new Thread[consumerCount];
        for (int i = 0; i < consumerCount; i++) {
            System.out.println("starting consumer #" + i);
            Connection conn = consumerConnections[i % connectionCount];
            Channel channel = conn.createChannel();
            if (consumerTxSize > 0)
                channel.txSelect();
            channel.exchangeDeclare(exchangeName, exchangeType);
            String queueName = channel.queueDeclare("", flags.contains("persistent"), true, false, null)
                    .getQueue();
            QueueingConsumer consumer = new QueueingConsumer(channel);
            if (prefetchCount > 0)
                channel.basicQos(prefetchCount);
            channel.basicConsume(queueName, autoAck, consumer);
            channel.queueBind(queueName, exchangeName, id);
            Thread t = new Thread(new Consumer(consumer, id, consumerTxSize, autoAck, stats, timeLimit));
            consumerThreads[i] = t;
            t.start();
        }
        Thread[] producerThreads = new Thread[producerCount];
        Connection[] producerConnections = new Connection[producerCount];
        for (int i = 0; i < producerCount; i++) {
            System.out.println("starting producer #" + i);
            Connection conn = factory.newConnection();
            producerConnections[i] = conn;
            Channel channel = conn.createChannel();
            if (producerTxSize > 0)
                channel.txSelect();
            channel.exchangeDeclare(exchangeName, exchangeType);
            final Producer p = new Producer(channel, exchangeName, id, flags, producerTxSize,
                    1000L * samplingInterval, rateLimit, minMsgSize, timeLimit, messageCount);
            channel.addReturnListener(p);
            Thread t = new Thread(p);
            producerThreads[i] = t;
            t.start();
        }

        for (int i = 0; i < producerCount; i++) {
            producerThreads[i].join();
            producerConnections[i].close();
        }

        for (int i = 0; i < consumerCount; i++) {
            consumerThreads[i].join();
        }
        for (int i = 0; i < connectionCount; i++) {
            consumerConnections[i].close();
        }

    } catch (ParseException exp) {
        System.err.println("Parsing failed. Reason: " + exp.getMessage());
        usage(options);
    } catch (Exception e) {
        System.err.println("Main thread caught exception: " + e);
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:org.springframework.amqp.rabbit.support.RabbitUtils.java

License:Apache License

/**
 * Declare to that broker that a channel is going to be used transactionally, and convert exceptions that arise.
 * /*from ww  w .  j a  va  2  s .  co  m*/
 * @param channel the channel to use
 */
public static void declareTransactional(Channel channel) {
    try {
        channel.txSelect();
    } catch (IOException e) {
        throw RabbitUtils.convertRabbitAccessException(e);
    }
}

From source file:org.trpr.mule.transport.rabbitmq.RabbitConnector.java

License:Apache License

/**
 * Creates and returns a ChannelHolder object for the specified endpoint.
 * @param endpoint declared Mule endpoint
 * @return a ChannelHolder instance containing the Connection
 * @throws IOException in case of I/O errors
 * @throws InitialisationException in case of initialization errors
 *///www. j a  v a 2s  .c o  m
public synchronized ChannelHolder createChannel(ImmutableEndpoint endpoint)
        throws IOException, InitialisationException {
    Channel channel = connection.createChannel();
    if (channel == null) {
        throw new InitialisationException(CoreMessages.failedToCreate(Channel.class.getName()), null);
    }
    // check if a pre-fetch count has been explicitly set and set it on the channel, else ignore        
    if (this.getPrefetchCount() != RabbitConnector.DEFAULT_PREFETCH_COUNT) {
        channel.basicQos(this.getPrefetchCount());
    }

    // set the newly created channel in txSelect mode if the endpoint is marked as durable and is of 
    // type OutboundEndPoint. TX is not supported for inbound end-points. Acking is preferred mechanism
    // for control over message consumption i.e. in RabbitMessageReceiver
    if (EndpointUtils.getDurable(endpoint) && endpoint instanceof OutboundEndpoint) {
        channel.txSelect();
    }
    return new ChannelHolder(channel);
}

From source file:vn.com.uet.performance.rabbitmq.MulticastParams.java

License:Open Source License

public Producer createProducer(Connection connection, Stats stats, String id) throws IOException {
    Channel channel = connection.createChannel();
    if (producerTxSize > 0)
        channel.txSelect();
    if (confirm >= 0)
        channel.confirmSelect();// ww w.  ja  va  2s. c o  m
    if (!predeclared || !exchangeExists(connection, exchangeName)) {
        channel.exchangeDeclare(exchangeName, exchangeType);
    }
    final Producer producer = new Producer(channel, exchangeName, id, randomRoutingKey, flags, producerTxSize,
            producerRateLimit, producerMsgCount, minMsgSize, timeLimit, confirm, stats);
    channel.addReturnListener(producer);
    channel.addConfirmListener(producer);
    return producer;
}

From source file:vn.com.uet.performance.rabbitmq.MulticastParams.java

License:Open Source License

public Consumer createConsumer(Connection connection, Stats stats, String id) throws IOException {
    Channel channel = connection.createChannel();
    if (consumerTxSize > 0)
        channel.txSelect();
    String qName = configureQueue(connection, id);
    if (consumerPrefetch > 0)
        channel.basicQos(consumerPrefetch);
    if (channelPrefetch > 0)
        channel.basicQos(channelPrefetch, true);
    return new Consumer(channel, id, qName, consumerTxSize, autoAck, multiAckEvery, stats, consumerRateLimit,
            consumerMsgCount, timeLimit);
}