Search in sources :

Example 1 with AMQConnection

use of com.rabbitmq.client.impl.AMQConnection in project rabbitmq-java-client by rabbitmq.

the class ConnectionFactoryTest method tryNextAddressIfTimeoutExceptionNoAutoRecovery.

// see https://github.com/rabbitmq/rabbitmq-java-client/issues/262
@Test
public void tryNextAddressIfTimeoutExceptionNoAutoRecovery() throws IOException, TimeoutException {
    final AMQConnection connectionThatThrowsTimeout = mock(AMQConnection.class);
    final AMQConnection connectionThatSucceeds = mock(AMQConnection.class);
    final Queue<AMQConnection> connections = new ArrayBlockingQueue<AMQConnection>(10);
    connections.add(connectionThatThrowsTimeout);
    connections.add(connectionThatSucceeds);
    ConnectionFactory connectionFactory = new ConnectionFactory() {

        @Override
        protected AMQConnection createConnection(ConnectionParams params, FrameHandler frameHandler, MetricsCollector metricsCollector) {
            return connections.poll();
        }

        @Override
        protected synchronized FrameHandlerFactory createFrameHandlerFactory() throws IOException {
            return mock(FrameHandlerFactory.class);
        }
    };
    connectionFactory.setAutomaticRecoveryEnabled(false);
    doThrow(TimeoutException.class).when(connectionThatThrowsTimeout).start();
    doNothing().when(connectionThatSucceeds).start();
    Connection returnedConnection = connectionFactory.newConnection(new Address[] { new Address("host1"), new Address("host2") });
    assertSame(connectionThatSucceeds, returnedConnection);
}
Also used : MetricsCollector(com.rabbitmq.client.MetricsCollector) FrameHandler(com.rabbitmq.client.impl.FrameHandler) ConnectionFactory(com.rabbitmq.client.ConnectionFactory) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) Address(com.rabbitmq.client.Address) AMQConnection(com.rabbitmq.client.impl.AMQConnection) AMQConnection(com.rabbitmq.client.impl.AMQConnection) Connection(com.rabbitmq.client.Connection) ConnectionParams(com.rabbitmq.client.impl.ConnectionParams) Test(org.junit.Test)

Example 2 with AMQConnection

use of com.rabbitmq.client.impl.AMQConnection in project rxrabbit by meltwater.

the class DefaultChannelFactory method createConnection.

private synchronized Connection createConnection(ChannelType connectionType) throws ConnectionFailureException {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date startTime = new Date();
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
    settings.getClient_properties().put("connection_type", connectionType.toString());
    settings.getClient_properties().put("connect_time", sdf.format(startTime) + "Z");
    ConnectionFactory cf = new ConnectionFactory();
    cf.setRequestedHeartbeat(settings.getHeartbeat());
    cf.setConnectionTimeout(settings.getConnection_timeout_millis());
    cf.setShutdownTimeout(settings.getShutdown_timeout_millis());
    cf.setRequestedFrameMax(settings.getFrame_max());
    cf.setHandshakeTimeout(settings.getHandshake_timeout_millis());
    cf.setClientProperties((Map) settings.getClient_properties());
    // cf.setSocketConfigurator(); NOTE is this worth investigating??
    // Hard coded ..
    cf.setRequestedChannelMax(0);
    // Hard coded ..
    cf.setAutomaticRecoveryEnabled(false);
    // Hard coded ..
    cf.setTopologyRecoveryEnabled(false);
    Exception lastException = null;
    Connection connection = null;
    for (BrokerAddresses.BrokerAddress address : addresses) {
        cf.setPassword(address.password);
        cf.setUsername(address.username);
        cf.setPort(address.port);
        cf.setHost(address.host);
        cf.setVirtualHost(address.virtualHost);
        try {
            if (address.scheme.toLowerCase().equals("amqps")) {
                cf.useSslProtocol();
                // Because rabbit uses NoopTrustStore by default...
                cf.setSocketFactory(SSLSocketFactory.getDefault());
            }
            log.infoWithParams("Creating " + connectionType + " connection to broker ...", "address", address.toString(), "settings", settings.toString());
            connection = cf.newConnection();
            boolean isOpen = connection.isOpen();
            if (!isOpen) {
                continue;
            }
            break;
        } catch (Exception e) {
            log.debugWithParams("Failed to createConnection to broker", "address", address.toString());
            lastException = e;
        }
    }
    if (connection == null) {
        throw new ConnectionFailureException(cf, lastException);
    }
    conToChannel.put(connectionType, new ConnectionInfo(connection, new ArrayList<ChannelImpl>(), settings.getClient_properties(), connectionType));
    log.infoWithParams("Successfully created " + connectionType + " connection to broker.", "address", addresses.get(0).toString(), "localPort", ((AMQConnection) connection).getLocalPort(), "settings", settings.toString());
    return connection;
}
Also used : ConnectionFactory(com.rabbitmq.client.ConnectionFactory) Connection(com.rabbitmq.client.Connection) AMQConnection(com.rabbitmq.client.impl.AMQConnection) ArrayList(java.util.ArrayList) SimpleDateFormat(java.text.SimpleDateFormat) Date(java.util.Date) TimeoutException(java.util.concurrent.TimeoutException) IOException(java.io.IOException) BrokerAddresses(com.meltwater.rxrabbit.BrokerAddresses)

Example 3 with AMQConnection

use of com.rabbitmq.client.impl.AMQConnection in project pinpoint by naver.

the class RabbitMQConsumerHandleCompleteInboundCommandInterceptor method createTrace.

private Trace createTrace(AMQChannel amqChannel, AMQCommand amqCommand) {
    AMQConnection connection = amqChannel.getConnection();
    if (connection == null) {
        logger.debug("connection is null, skipping trace");
    }
    Method method = amqCommand.getMethod();
    AMQP.Basic.GetOk getOk = (AMQP.Basic.GetOk) method;
    String exchange = getOk.getExchange();
    if (RabbitMQClientPluginConfig.isExchangeExcluded(exchange, excludeExchangeFilter)) {
        if (isDebug) {
            logger.debug("exchange {} is excluded", exchange);
        }
        return null;
    }
    String routingKey = getOk.getRoutingKey();
    Map<String, Object> headers = getHeadersFromContentHeader(amqCommand.getContentHeader());
    // If this transaction is not traceable, mark as disabled.
    if (headers.get(RabbitMQClientConstants.META_SAMPLED) != null) {
        return traceContext.disableSampling();
    }
    final TraceId traceId = populateTraceIdFromRequest(headers);
    // If there's no trasanction id, a new trasaction begins here.
    final Trace trace = traceId == null ? traceContext.newTraceObject() : traceContext.continueTraceObject(traceId);
    if (trace.canSampled()) {
        final SpanRecorder recorder = trace.getSpanRecorder();
        recordRootSpan(recorder, connection, exchange, routingKey, headers);
    }
    return trace;
}
Also used : Trace(com.navercorp.pinpoint.bootstrap.context.Trace) SpanRecorder(com.navercorp.pinpoint.bootstrap.context.SpanRecorder) AMQConnection(com.rabbitmq.client.impl.AMQConnection) AMQP(com.rabbitmq.client.AMQP) TraceId(com.navercorp.pinpoint.bootstrap.context.TraceId) Method(com.rabbitmq.client.impl.Method)

Example 4 with AMQConnection

use of com.rabbitmq.client.impl.AMQConnection in project rabbitmq-java-client by rabbitmq.

the class SharedThreadPoolTest method willShutDownExecutor.

@Test
public void willShutDownExecutor() throws IOException, TimeoutException {
    ExecutorService executor1 = null;
    ExecutorService executor2 = null;
    AMQConnection conn1 = null;
    AMQConnection conn2 = null;
    AMQConnection conn3 = null;
    AMQConnection conn4 = null;
    try {
        ConnectionFactory cf = TestUtils.connectionFactory();
        cf.setAutomaticRecoveryEnabled(false);
        executor1 = Executors.newFixedThreadPool(8);
        cf.setSharedExecutor(executor1);
        conn1 = (AMQConnection) cf.newConnection();
        assertFalse(conn1.willShutDownConsumerExecutor());
        executor2 = Executors.newSingleThreadExecutor();
        conn2 = (AMQConnection) cf.newConnection(executor2);
        assertFalse(conn2.willShutDownConsumerExecutor());
        conn3 = (AMQConnection) cf.newConnection((ExecutorService) null);
        assertTrue(conn3.willShutDownConsumerExecutor());
        cf.setSharedExecutor(null);
        conn4 = (AMQConnection) cf.newConnection();
        assertTrue(conn4.willShutDownConsumerExecutor());
    } finally {
        close(conn1);
        close(conn2);
        close(conn3);
        close(conn4);
        close(executor1);
        close(executor2);
    }
}
Also used : ConnectionFactory(com.rabbitmq.client.ConnectionFactory) AMQConnection(com.rabbitmq.client.impl.AMQConnection) ExecutorService(java.util.concurrent.ExecutorService) Test(org.junit.Test)

Example 5 with AMQConnection

use of com.rabbitmq.client.impl.AMQConnection in project rabbitmq-java-client by rabbitmq.

the class AMQChannelTest method testRpcTimeoutReplyComesDuringNexRpc.

@Test
public void testRpcTimeoutReplyComesDuringNexRpc() throws Exception {
    int rpcTimeout = 100;
    AMQConnection connection = mock(AMQConnection.class);
    when(connection.getChannelRpcTimeout()).thenReturn(rpcTimeout);
    when(connection.willCheckRpcResponseType()).thenReturn(Boolean.TRUE);
    when(connection.getTrafficListener()).thenReturn(TrafficListener.NO_OP);
    final DummyAmqChannel channel = new DummyAmqChannel(connection, 1);
    Method method = new AMQImpl.Queue.Declare.Builder().queue("123").durable(false).exclusive(true).autoDelete(true).arguments(null).build();
    try {
        channel.rpc(method);
        fail("Should time out and throw an exception");
    } catch (final ChannelContinuationTimeoutException e) {
        // OK
        assertThat((DummyAmqChannel) e.getChannel()).isEqualTo(channel);
        assertThat(e.getChannelNumber()).isEqualTo(channel.getChannelNumber());
        assertThat(e.getMethod()).isEqualTo(method);
        assertThat(channel.nextOutstandingRpc()).as("outstanding RPC should have been cleaned").isNull();
    }
    // now do a basic.consume request and have the queue.declareok returned instead
    method = new AMQImpl.Basic.Consume.Builder().queue("123").consumerTag("").arguments(null).build();
    final Method response1 = new AMQImpl.Queue.DeclareOk.Builder().queue("123").consumerCount(0).messageCount(0).build();
    final Method response2 = new AMQImpl.Basic.ConsumeOk.Builder().consumerTag("456").build();
    scheduler.schedule((Callable<Void>) () -> {
        channel.handleCompleteInboundCommand(new AMQCommand(response1));
        Thread.sleep(10);
        channel.handleCompleteInboundCommand(new AMQCommand(response2));
        return null;
    }, (long) (rpcTimeout / 2.0), TimeUnit.MILLISECONDS);
    AMQCommand rpcResponse = channel.rpc(method);
    assertThat(rpcResponse.getMethod()).isEqualTo(response2);
}
Also used : AMQConnection(com.rabbitmq.client.impl.AMQConnection) Method(com.rabbitmq.client.Method) ChannelContinuationTimeoutException(com.rabbitmq.client.ChannelContinuationTimeoutException) AMQImpl(com.rabbitmq.client.impl.AMQImpl) AMQCommand(com.rabbitmq.client.impl.AMQCommand) Test(org.junit.Test)

Aggregations

AMQConnection (com.rabbitmq.client.impl.AMQConnection)14 Test (org.junit.Test)9 IOException (java.io.IOException)6 ChannelContinuationTimeoutException (com.rabbitmq.client.ChannelContinuationTimeoutException)3 Connection (com.rabbitmq.client.Connection)3 ConnectionFactory (com.rabbitmq.client.ConnectionFactory)3 Method (com.rabbitmq.client.Method)3 ConnectionParams (com.rabbitmq.client.impl.ConnectionParams)3 FrameHandler (com.rabbitmq.client.impl.FrameHandler)3 ArrayList (java.util.ArrayList)3 Trace (com.navercorp.pinpoint.bootstrap.context.Trace)2 RemoteAddressAccessor (com.navercorp.pinpoint.plugin.rabbitmq.client.field.accessor.RemoteAddressAccessor)2 UnexpectedFrameError (com.rabbitmq.client.UnexpectedFrameError)2 AMQCommand (com.rabbitmq.client.impl.AMQCommand)2 Frame (com.rabbitmq.client.impl.Frame)2 SocketTimeoutException (java.net.SocketTimeoutException)2 TimeoutException (java.util.concurrent.TimeoutException)2 BrokerAddresses (com.meltwater.rxrabbit.BrokerAddresses)1 SpanEventRecorder (com.navercorp.pinpoint.bootstrap.context.SpanEventRecorder)1 SpanRecorder (com.navercorp.pinpoint.bootstrap.context.SpanRecorder)1