net.jodah.lyra.config.Config Java Examples

The following examples show how to use net.jodah.lyra.config.Config. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ChannelInvocationTest.java    From lyra with Apache License 2.0 6 votes vote down vote up
/**
 * Asserts that invocation failures are rethrown when a connection is shutdown and a retry policy
 * is not set, but the connection and channel should still be recovered.
 */
public void shouldThrowOnConnectionShutdownWithNoRetryPolicy() throws Throwable {
  config = new Config().withRetryPolicy(RetryPolicies.retryNever()).withRecoveryPolicy(
      RecoveryPolicies.recoverAlways());
  performThrowableInvocation(retryableConnectionShutdownSignal());

  // Assert that the channel is recovered asynchronously
  assertTrue(mockChannel(1).channelHandler.circuit.await(Duration.secs(1)));
  verifyCxnCreations(2);
  verifyChannelCreations(1, 2);
  verifyChannelCreations(2, 2);
  verifyConsumerCreations(1, 1, 2);
  verifyConsumerCreations(1, 2, 2);
  verifyConsumerCreations(2, 5, 2);
  verifyConsumerCreations(2, 6, 2);
  verifyInvocations(1);
}
 
Example #2
Source File: ChannelInvocationTest.java    From lyra with Apache License 2.0 6 votes vote down vote up
/**
 * Asserts that a failed invocation results in the failure being rethrown immediately if retries
 * are not configured while recovery takes place in the background.
 */
public void shouldThrowOnChannelShutdownWithNoRetryPolicy() throws Throwable {
  config = new Config().withRetryPolicy(RetryPolicies.retryNever()).withRecoveryPolicy(
      RecoveryPolicies.recoverAlways());
  performThrowableInvocation(retryableChannelShutdownSignal());

  // Assert that the channel is recovered asynchronously
  assertTrue(mockChannel(1).channelHandler.circuit.await(Duration.secs(1)));
  verifyCxnCreations(1);
  verifyChannelCreations(1, 2);
  verifyChannelCreations(2, 1);
  verifyConsumerCreations(1, 1, 2);
  verifyConsumerCreations(1, 2, 2);
  verifyConsumerCreations(2, 5, 1);
  verifyConsumerCreations(2, 6, 1);
  verifyInvocations(1);
}
 
Example #3
Source File: ConnectionFactoryInvocationTest.java    From lyra with Apache License 2.0 6 votes vote down vote up
/**
 * Asserts that invocation failures are rethrown when a retry policy is not set.
 */
public void shouldThrowOnInvocationFailureWithNoRetryPolicy() throws Throwable {
  config = new Config().withRetryPolicy(RetryPolicies.retryNever());
  connectionFactory = mock(ConnectionFactory.class);
  connection = mock(Connection.class);
  when(connectionFactory.newConnection(any(ExecutorService.class), any(Address[].class), anyString())).thenAnswer(
      failNTimes(3, new ConnectException("fail"), connection, connectionHandler));

  try {
    mockConnection();
    fail();
  } catch (Exception expected) {
  }

  verifyCxnCreations(1);
}
 
Example #4
Source File: ConnectionInvocationTest.java    From lyra with Apache License 2.0 6 votes vote down vote up
/**
 * Asserts that a failed invocation results in the failure being rethrown immediately if retries
 * are not configured while recovery takes place in the background.
 */
public void shouldThrowImmediatelyOnInvocationFailureWithNoRetryPolicy() throws Throwable {
  config = new Config().withRetryPolicy(RetryPolicies.retryNever()).withRecoveryPolicy(
      RecoveryPolicies.recoverAlways());
  performThrowableInvocation(retryableConnectionShutdownSignal());

  // Assert that the connection is recovered asynchronously
  assertTrue(connectionHandler.circuit.await(Duration.secs(1)));
  verifyCxnCreations(2);
  verifyChannelCreations(1, 2);
  verifyChannelCreations(2, 2);
  verifyConsumerCreations(1, 1, 2);
  verifyConsumerCreations(1, 2, 2);
  verifyConsumerCreations(2, 5, 2);
  verifyConsumerCreations(2, 6, 2);
  verifyInvocations(1);
}
 
Example #5
Source File: AbstractFunctionalTest.java    From lyra with Apache License 2.0 5 votes vote down vote up
protected void mockConnection() throws IOException, TimeoutException {
  if (connectionFactory == null) {
    mockConnectionOnly();
    connectionFactory = mock(ConnectionFactory.class);
    when(connectionFactory.getVirtualHost()).thenReturn("/");
    when(connectionFactory.newConnection(any(ExecutorService.class), any(Address[].class), anyString()))
        .thenReturn(connection);
  }

  if (options == null)
    options = new ConnectionOptions().withHost("test-host");
  options.withConnectionFactory(connectionFactory);
  if (config == null)
    config =
        new Config().withRetryPolicy(
            RetryPolicies.retryAlways().withInterval(Duration.millis(10))).withRecoveryPolicy(
            RecoveryPolicies.recoverAlways());

  if (connectionHandler == null) {
    connectionHandler = new ConnectionHandler(options, config, Connection.class.getClassLoader());
    connectionProxy =
        (ConfigurableConnection) Proxy.newProxyInstance(Connection.class.getClassLoader(),
            new Class<?>[] {ConfigurableConnection.class}, connectionHandler);
    connectionHandler.createConnection(connectionProxy);
    channels = new HashMap<Integer, MockChannel>();
  }
}
 
Example #6
Source File: ChannelInvocationTest.java    From lyra with Apache License 2.0 5 votes vote down vote up
/**
 * Asserts that invocation failures are rethrown when a channel is shutdown and a connection
 * recovery policy is set but a channel recovery policy is not.
 */
public void shouldThrowOnConnectionShutdownWithNoChannelRecoveryPolicy() throws Throwable {
  config = new Config().withRetryPolicy(RetryPolicies.retryAlways())
      .withConnectionRecoveryPolicy(RecoveryPolicies.recoverAlways())
      .withChannelRecoveryPolicy(RecoveryPolicies.recoverNever());
  performThrowableInvocation(retryableConnectionShutdownSignal());
  verifyCxnCreations(2);
  verifyChannelCreations(1, 1);
  verifyChannelCreations(2, 1);
  verifyConsumerCreations(1, 1, 1);
  verifyConsumerCreations(1, 2, 1);
  verifyConsumerCreations(2, 5, 1);
  verifyConsumerCreations(2, 6, 1);
  verifyInvocations(1);
}
 
Example #7
Source File: ChannelInvocationTest.java    From lyra with Apache License 2.0 5 votes vote down vote up
/**
 * Asserts that invocation failures are rethrown when a connection is shutdown and a connection
 * recovery policy is not set even when a channel recovery policy is set.
 */
public void shouldThrowOnConnectionShutdownWithNoCxnRecoveryPolicy() throws Throwable {
  config = new Config().withRetryPolicy(RetryPolicies.retryAlways())
      .withConnectionRecoveryPolicy(RecoveryPolicies.recoverNever())
      .withChannelRecoveryPolicy(RecoveryPolicies.recoverAlways());
  performThrowableInvocation(retryableConnectionShutdownSignal());
  verifySingleInvocation();
}
 
Example #8
Source File: ChannelInvocationTest.java    From lyra with Apache License 2.0 5 votes vote down vote up
/**
 * Asserts that invocation failures are rethrown when a connection is shutdown and a recovery
 * policy is not set.
 */
public void shouldThrowOnConnectionShutdownWithNoRecoveryPolicy() throws Throwable {
  config = new Config().withRetryPolicy(RetryPolicies.retryAlways()).withRecoveryPolicy(
      RecoveryPolicies.recoverNever());
  performThrowableInvocation(retryableConnectionShutdownSignal());
  verifySingleInvocation();
}
 
Example #9
Source File: ChannelInvocationTest.java    From lyra with Apache License 2.0 5 votes vote down vote up
/**
 * Asserts that invocation failures are rethrown when a channel is shutdown and a recovery policy
 * is not set.
 */
public void shouldThrowOnChannelShutdownWithNoRecoveryPolicy() throws Throwable {
  config = new Config().withRetryPolicy(RetryPolicies.retryAlways()).withRecoveryPolicy(
      RecoveryPolicies.recoverNever());
  performThrowableInvocation(retryableChannelShutdownSignal());
  verifySingleInvocation();
}
 
Example #10
Source File: ChannelRecoveryTest.java    From lyra with Apache License 2.0 5 votes vote down vote up
/**
 * Asserts that a failure from a channel listener during recovery results in the channel being
 * recovered.
 */
public void shouldHandleRecoveryFailureFromChannelListener() throws Throwable {
  final AtomicBoolean shutdownCalled = new AtomicBoolean();
  config = new Config().withRetryPolicy(
      RetryPolicies.retryAlways().withInterval(Duration.millis(10)))
      .withRecoveryPolicy(RecoveryPolicies.recoverAlways())
      .withChannelListeners(new DefaultChannelListener() {
        @Override
        public void onRecovery(Channel channel) {
          if (!shutdownCalled.get() && channel == mockChannel(2).proxy) {
            ShutdownSignalException e = nonRetryableChannelShutdownSignal();
            shutdownCalled.set(true);
            callShutdownListener(mockChannel(2).channelHandler, e);
            throw e;
          }
        }
      });

  performRecovery(mockChannel(2).channelHandler, mockChannel(2).channelHandler, 0, 0);
  verifyCxnCreations(1);
  verifyChannelCreations(1, 1);
  verifyConsumerCreations(1, 1, 1);
  verifyConsumerCreations(1, 2, 1);

  verifyChannelCreations(2, 3);
  verifyConsumerCreations(2, 5, 2); // Only attempted once since first attempt fails
  verifyConsumerCreations(2, 6, 2);
}
 
Example #11
Source File: ConnectionInvocationTest.java    From lyra with Apache License 2.0 5 votes vote down vote up
/**
 * Asserts that invocation failures are rethrown when a connection is shutdown and a recovery
 * policy is not set.
 */
public void shouldThrowOnInvocationFailureWithNoRecoveryPolicy() throws Throwable {
  config = new Config().withRetryPolicy(RetryPolicies.retryAlways()).withRecoveryPolicy(
      RecoveryPolicies.recoverNever());
  performThrowableInvocation(retryableConnectionShutdownSignal());
  verifyCxnCreations(1);
  verifyChannelCreations(1, 1);
  verifyChannelCreations(2, 1);
  verifyConsumerCreations(1, 1, 1);
  verifyConsumerCreations(1, 2, 1);
  verifyConsumerCreations(2, 5, 1);
  verifyConsumerCreations(2, 6, 1);
  verifyInvocations(1);
}
 
Example #12
Source File: ConnectionUtils.java    From simpleci with MIT License 5 votes vote down vote up
public static Connection createRabbitmqConnection(String host, int port, String user, String password) throws IOException, TimeoutException {
    Config config = new Config()
            .withRecoveryPolicy(new RecoveryPolicy()
                    .withBackoff(Duration.seconds(1), Duration.seconds(30))
                    .withMaxAttempts(20));
    ConnectionOptions options = new ConnectionOptions()
            .withHost(host)
            .withPort(port)
            .withUsername(user)
            .withPassword(password);

    return Connections.create(options, config);
}
 
Example #13
Source File: Connections.java    From lyra with Apache License 2.0 5 votes vote down vote up
/**
 * Creates and returns a new Lyra managed ConfigurableConnection for the given {@code options} and
 * {@code config}. If the connection attempt fails, retries will be performed according to the
 * {@link Config#getConnectRetryPolicy() configured RetryPolicy} before throwing the failure.
 * 
 * @throws NullPointerException if {@code options} or {@code config} are null
 * @throws IOException if the connection could not be created
 */
public static ConfigurableConnection create(ConnectionOptions options, Config config, ClassLoader classLoader)
    throws IOException, TimeoutException {
  Assert.notNull(options, "options");
  Assert.notNull(config, "config");
  Assert.notNull(classLoader, CLASS_LOADER_PARAMETER_NAME);
  ConnectionHandler handler = new ConnectionHandler(options.copy(), new Config(config), classLoader);
  ConfigurableConnection proxy = (ConfigurableConnection) Proxy.newProxyInstance(
      classLoader, CONNECTION_TYPES, handler);
  handler.createConnection(proxy);
  return proxy;
}
 
Example #14
Source File: ConnectionHandler.java    From lyra with Apache License 2.0 5 votes vote down vote up
public ConnectionHandler(ConnectionOptions options, Config config, ClassLoader classLoader) throws IOException {
  this.options = options;
  this.config = config;
  this.classLoader = Assert.notNull(classLoader, "classLoader");
  this.connectionName =
      options.getName() == null ? String.format("cxn-%s", CONNECTION_COUNTER.incrementAndGet())
          : options.getName();
  consumerThreadPool =
      options.getConsumerExecutor() == null ? Executors.newCachedThreadPool(new NamedThreadFactory(
          String.format("rabbitmq-%s-consumer", connectionName), config.isUsingDaemonThreads())) : options.getConsumerExecutor();
}
 
Example #15
Source File: ChannelHandler.java    From lyra with Apache License 2.0 5 votes vote down vote up
public ChannelHandler(ConnectionHandler connectionHandler, Channel delegate, Config config) {
  this.connectionHandler = connectionHandler;
  this.delegate = delegate;
  this.config = config;

  ShutdownListener listener = new ChannelShutdownListener();
  shutdownListeners.add(listener);
  delegate.addShutdownListener(listener);
}
 
Example #16
Source File: RabbitMQMessagingService.java    From elasticactors with Apache License 2.0 4 votes vote down vote up
@PostConstruct
public void start() throws IOException, TimeoutException {
    // millis
    connectionFactory.setConnectionTimeout(1000);
    // seconds
    connectionFactory.setRequestedHeartbeat(4);
    // turn off recovery as we are using Lyra
    connectionFactory.setAutomaticRecoveryEnabled(false);
    connectionFactory.setTopologyRecoveryEnabled(false);
    // lyra reconnect logic
    Config config = new Config()
            .withRecoveryPolicy(new RecoveryPolicy()
                    .withMaxAttempts(-1)
                    .withInterval(Duration.seconds(1)))
            .withChannelListeners(this);

    ConnectionOptions connectionOptions = new ConnectionOptions(connectionFactory)
            .withHosts(StringUtils.commaDelimitedListToStringArray(rabbitmqHosts))
            .withPort(rabbitmqPort)
            .withUsername(username)
            .withPassword(password);
    // create single connection
    //clientConnection = connectionFactory.newConnection(Address.parseAddresses(rabbitmqHosts));
    clientConnection = Connections.create(connectionOptions,config);
    // create a seperate producer and a seperate consumer channel
    consumerChannel = clientConnection.createChannel();
    consumerChannel.basicQos(prefetchCount);
    producerChannel = clientConnection.createChannel();
    // add logging shutdown listener
    consumerChannel.addShutdownListener(LoggingShutdownListener.INSTANCE);
    producerChannel.addShutdownListener(LoggingShutdownListener.INSTANCE);
    // ensure the exchange is there
    consumerChannel.exchangeDeclare(exchangeName,"direct",true);
    if(ackType == BUFFERED) {
        messageAcker = new BufferingMessageAcker(consumerChannel);
    } else if(ackType == WRITE_BEHIND) {
        messageAcker = new WriteBehindMessageAcker(consumerChannel);
    } else if(ackType == ASYNC) {
        messageAcker = new AsyncMessageAcker(consumerChannel);
    } else {
        messageAcker = new DirectMessageAcker(consumerChannel);
    }
    messageAcker.start();
}
 
Example #17
Source File: RabbitMQMessagingService.java    From elasticactors with Apache License 2.0 4 votes vote down vote up
@PostConstruct
public void start() throws IOException, TimeoutException {
    // millis
    connectionFactory.setConnectionTimeout(1000);
    // seconds
    connectionFactory.setRequestedHeartbeat(4);
    // turn off recovery as we are using Lyra
    connectionFactory.setAutomaticRecoveryEnabled(false);
    connectionFactory.setTopologyRecoveryEnabled(false);
    // lyra reconnect logic
    Config config = new Config()
            .withRecoveryPolicy(new RecoveryPolicy()
                    .withMaxAttempts(-1)
                    .withInterval(Duration.seconds(1)))
            .withChannelListeners(this);

    ConnectionOptions connectionOptions = new ConnectionOptions(connectionFactory)
            .withHosts(StringUtils.commaDelimitedListToStringArray(rabbitmqHosts))
            .withPort(rabbitmqPort)
            .withUsername(username)
            .withPassword(password);
    // create single connection
    //clientConnection = connectionFactory.newConnection(Address.parseAddresses(rabbitmqHosts));
    clientConnection = Connections.create(connectionOptions,config);
    // create a seperate consumer channel
    consumerChannel = clientConnection.createChannel();
    consumerChannel.basicQos(prefetchCount);
    // prepare the consumer channels
    for (int i = 0; i < queueExecutor.getThreadCount(); i++) {
        producerChannels.add(clientConnection.createChannel());
    }
    // add logging shutdown listener
    consumerChannel.addShutdownListener(LoggingShutdownListener.INSTANCE);
    for (Channel producerChannel : producerChannels) {
        producerChannel.addShutdownListener(LoggingShutdownListener.INSTANCE);
    }
    // ensure the exchange is there
    consumerChannel.exchangeDeclare(exchangeName,"direct",true);
    if(ackType == BUFFERED) {
        messageAcker = new BufferingMessageAcker(consumerChannel);
    } else if(ackType == WRITE_BEHIND) {
        messageAcker = new WriteBehindMessageAcker(consumerChannel);
    } else if(ackType == ASYNC) {
        messageAcker = new AsyncMessageAcker(consumerChannel);
    } else {
        messageAcker = new DirectMessageAcker(consumerChannel);
    }
    messageAcker.start();
}
 
Example #18
Source File: Connections.java    From lyra with Apache License 2.0 3 votes vote down vote up
/**
 * Creates and returns a new Lyra managed ConfigurableConnection for the given {@code options} and
 * {@code config}. If the connection attempt fails, retries will be performed according to the
 * {@link Config#getConnectRetryPolicy() configured RetryPolicy} before throwing the failure.
 *
 * @throws NullPointerException if {@code options} or {@code config} are null
 * @throws IOException if the connection could not be created
 */
public static ConfigurableConnection create(ConnectionOptions options, Config config)
    throws IOException, TimeoutException {
  Assert.notNull(options, "options");
  Assert.notNull(config, "config");
  return create(options, config, DEFAULT_CLASS_LOADER);
}
 
Example #19
Source File: Connections.java    From lyra with Apache License 2.0 3 votes vote down vote up
/**
 * Creates and returns a new Lyra managed ConfigurableConnection for the given
 * {@code connectionFactory} and {@code config}. If the connection attempt fails, retries will be
 * performed according to the {@link Config#getConnectRetryPolicy() configured RetryPolicy} before
 * throwing the failure.
 *
 * @throws NullPointerException if {@code connectionFactory} or {@code config} are null
 * @throws IOException if the connection could not be created
 */
public static ConfigurableConnection create(ConnectionFactory connectionFactory, Config config, ClassLoader classLoader)
    throws IOException, TimeoutException {
  Assert.notNull(connectionFactory, "connectionFactory");
  Assert.notNull(classLoader, CLASS_LOADER_PARAMETER_NAME);
  return create(new ConnectionOptions(connectionFactory), config, classLoader);
}
 
Example #20
Source File: Connections.java    From lyra with Apache License 2.0 2 votes vote down vote up
/**
 * Creates and returns a new Lyra managed ConfigurableConnection for the given
 * {@code connectionFactory} and {@code config}. If the connection attempt fails, retries will be
 * performed according to the {@link Config#getConnectRetryPolicy() configured RetryPolicy} before
 * throwing the failure.
 *
 * @throws NullPointerException if {@code connectionFactory} or {@code config} are null
 * @throws IOException if the connection could not be created
 */
public static ConfigurableConnection create(ConnectionFactory connectionFactory, Config config)
    throws IOException, TimeoutException {
  Assert.notNull(connectionFactory, "connectionFactory");
  return create(new ConnectionOptions(connectionFactory), config, DEFAULT_CLASS_LOADER);
}
 
Example #21
Source File: Connections.java    From lyra with Apache License 2.0 2 votes vote down vote up
/**
 * Creates and returns a new Lyra managed ConfigurableConnection for the given {@code config}. If
 * the connection attempt fails, retries will be performed according to the
 * {@link Config#getConnectRetryPolicy() configured RetryPolicy} before throwing the failure.
 *
 * @throws NullPointerException if {@code connectionFactory} or {@code config} are null
 * @throws IOException if the connection could not be created
 */
public static ConfigurableConnection create(Config config, ClassLoader classLoader) throws IOException, TimeoutException {
  Assert.notNull(classLoader, CLASS_LOADER_PARAMETER_NAME);
  return create(new ConnectionOptions(), config, classLoader);
}
 
Example #22
Source File: Connections.java    From lyra with Apache License 2.0 2 votes vote down vote up
/**
 * Creates and returns a new Lyra managed ConfigurableConnection for the given {@code config}. If
 * the connection attempt fails, retries will be performed according to the
 * {@link Config#getConnectRetryPolicy() configured RetryPolicy} before throwing the failure.
 *
 * @throws NullPointerException if {@code connectionFactory} or {@code config} are null
 * @throws IOException if the connection could not be created
 */
public static ConfigurableConnection create(Config config) throws IOException, TimeoutException {
  return create(new ConnectionOptions(), config, DEFAULT_CLASS_LOADER);
}