コード例 #1
0
  static RabbitConnectionFactoryConfig uriToConnectionConfig(String uri) {
    RabbitConnectionFactoryConfig properties = new RabbitConnectionFactoryConfig();
    if (isNotEmpty(uri)) {
      String username = StringUtils.substringBetween(uri, "amqp://", ":");
      String password = StringUtils.substringBetween(uri, username + ":", "@");
      String hostWithPort = StringUtils.substringBetween(uri, "@", "/");

      // If no virtual host is specified
      if (isEmpty(hostWithPort)) {
        hostWithPort = StringUtils.substringAfter(uri, "@");
      }

      int port = properties.getPort();
      String host = hostWithPort;
      boolean hasPort = StringUtils.contains(hostWithPort, ":");
      if (hasPort) {
        host = StringUtils.substringBefore(hostWithPort, ":");
        port = NumberUtils.toInt(StringUtils.substringAfter(hostWithPort, ":"));
      }
      String virtualHost = StringUtils.substringAfter(uri, hostWithPort + "/");

      properties.setUsername(username);
      properties.setPassword(password);
      properties.setHost(host);
      properties.setPort(port);

      if (isNotEmpty(virtualHost)) {
        properties.setVirtualHost(virtualHost);
      }
    }
    return properties;
  }
コード例 #2
0
  @Bean
  public CachingConnectionFactory rabbitConnectionFactory() {
    log.info("AMQP URL: {}", isBlank(amqpConnectionUri) ? "localhost:5672" : amqpConnectionUri);

    RabbitConnectionFactoryConfig config = uriToConnectionConfig(amqpConnectionUri);
    CachingConnectionFactory connectionFactory = new CachingConnectionFactory(config.getHost());
    connectionFactory.setPort(config.getPort());

    if (config.getUsername() != null) {
      connectionFactory.setUsername(config.getUsername());
    }
    if (config.getPassword() != null) {
      connectionFactory.setPassword(config.getPassword());
    }
    if (config.getVirtualHost() != null) {
      connectionFactory.setVirtualHost(StringUtils.remove(config.getVirtualHost(), '/'));
    }

    return connectionFactory;
  }