Java Code Examples for com.rabbitmq.client.ConnectionFactory#setPassword()

The following examples show how to use com.rabbitmq.client.ConnectionFactory#setPassword() . 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: RabbitMQEventBus.java    From cloudstack with Apache License 2.0 8 votes vote down vote up
private synchronized Connection createConnection() throws KeyManagementException, NoSuchAlgorithmException, IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setUsername(username);
        factory.setPassword(password);
        factory.setHost(amqpHost);
        factory.setPort(port);

        if (virtualHost != null && !virtualHost.isEmpty()) {
            factory.setVirtualHost(virtualHost);
        } else {
            factory.setVirtualHost("/");
        }

        if (useSsl != null && !useSsl.isEmpty() && useSsl.equalsIgnoreCase("true")) {
            factory.useSslProtocol(secureProtocol);
        }
        Connection connection = factory.newConnection();
        connection.addShutdownListener(disconnectHandler);
        connection.addBlockedListener(blockedConnectionHandler);
        s_connection = connection;
        return s_connection;
}
 
Example 2
Source File: RabbitMqConnFactoryUtil.java    From springboot-learn with MIT License 6 votes vote down vote up
/**
 * 获取rabbit连接
 */
public static Connection getRabbitConn() throws IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUsername("guest");
    factory.setPassword("guest");
    factory.setVirtualHost("/");
    factory.setHost("192.168.242.131");
    factory.setPort(5672);
    Connection conn = factory.newConnection();

    //高级连接使用线程池
    // ExecutorService es = Executors.newFixedThreadPool(20);
    // Connection conn = factory.newConnection(es);

    return conn;
}
 
Example 3
Source File: TestClient.java    From rabbitmq-cdi with MIT License 6 votes vote down vote up
public static void main(String[] args) {
  CountDownLatch countDown = new CountDownLatch(1);
  ConnectionFactory factory = new ConnectionFactory();
  factory.setUsername("guest");
  factory.setPassword("guest");
  factory.setHost("127.0.0.1");
  try (Connection con = factory.newConnection(); Channel chn = con.createChannel()) {
    AtomicLong receivedMessages = new AtomicLong();
    String consumerTag =
        chn.basicConsume("product.catalog_item.sync", true, new DefaultConsumer(chn) {
          @Override
          public void handleDelivery(String tag, Envelope envelope, BasicProperties properties,
              byte[] body) throws IOException {
            long actualCount = receivedMessages.incrementAndGet();
            if (actualCount % 1000 == 0) {
              System.out.println("Received " + actualCount + " messages so far.");
            }
            // countDown.countDown();
          }
        });
    System.out.println(consumerTag);
    countDown.await();
  } catch (Exception e) {
    e.printStackTrace();
  }
}
 
Example 4
Source File: CacheInvalidationSubscriber.java    From carbon-commons with Apache License 2.0 6 votes vote down vote up
private void subscribe() {
    log.debug("Global cache invalidation: initializing the subscription");
    try {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(ConfigurationManager.getProviderUrl());
        int port = Integer.parseInt(ConfigurationManager.getProviderPort());
        factory.setPort(port);
        factory.setUsername(ConfigurationManager.getProviderUsername());
        factory.setPassword(ConfigurationManager.getProviderPassword());
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        channel.exchangeDeclare(ConfigurationManager.getTopicName(), "topic");
        String queueName = channel.queueDeclare().getQueue();
        channel.queueBind(queueName, ConfigurationManager.getTopicName(), "#");
        consumer = new QueueingConsumer(channel);
        channel.basicConsume(queueName, true, consumer);
        Thread reciever = new Thread(messageReciever);
        reciever.start();
        log.info("Global cache invalidation is online");
    } catch (Exception e) {
        log.error("Global cache invalidation: Error message broker initialization", e);
    }
}
 
Example 5
Source File: RabbitMqClientDemo.java    From xian with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUsername(XianConfig.get("rabbitmqUserName"));
    factory.setPassword(XianConfig.get("rabbitmqPwd"));
    factory.setVirtualHost("/");
    factory.setHost("production-internet-mq.apaycloud.com");
    factory.setPort(5672);
    Connection conn = factory.newConnection();
    Channel channel = conn.createChannel();


    String exchangeName = "yy-exchange";
    String routingKey = "yy-routingKey";
    String queueName = "yy-queueName";

    channel.exchangeDeclare(exchangeName, "direct", true);
    channel.queueDeclare(queueName, true, false, false, null);
    channel.queueBind(queueName, exchangeName, routingKey);

    byte[] messageBodyBytes = "Hello, world2!".getBytes();
    channel.basicPublish(exchangeName, routingKey, null, messageBodyBytes);


    Thread.sleep(1000 * 60);

    channel.close();
    conn.close();
}
 
Example 6
Source File: AMQPConnectionFactory.java    From NationStatesPlusPlus with MIT License 5 votes vote down vote up
public Channel createChannel() throws IOException {
	ConnectionFactory factory = new ConnectionFactory();
	factory.setUsername(user);
	factory.setPassword(pass);
	factory.setHost(host);
	factory.setPort(port);

	Connection amqpConn = factory.newConnection();
	return amqpConn.createChannel();
}
 
Example 7
Source File: RabbitMqTestUtils.java    From roboconf-platform with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a channel to interact with a RabbitMQ server for tests.
 * @param messageServerIp the message server's IP address
 * @param username the user name for the messaging server
 * @param password the password for the messaging server
 * @return a non-null channel
 * @throws IOException if the creation failed
 */
public static Channel createTestChannel( String messageServerIp, String username, String password ) throws IOException {

	ConnectionFactory factory = new ConnectionFactory();
	factory.setHost( messageServerIp );
	factory.setUsername( username );
	factory.setPassword( password );

	return factory.newConnection().createChannel();
}
 
Example 8
Source File: RabbitMqIngressTest.java    From pitchfork with Apache License 2.0 5 votes vote down vote up
private static Channel getRabbitMqChannel() throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUsername("guest");
    factory.setPassword("guest");
    factory.setVirtualHost("/");
    factory.setHost(rabbitMqContainer.getContainerIpAddress());
    factory.setPort(rabbitMqContainer.getFirstMappedPort());

    var connection = factory.newConnection();

    return connection.createChannel();
}
 
Example 9
Source File: RabbitMqIngressSpringConfig.java    From pitchfork with Apache License 2.0 5 votes vote down vote up
@Bean(destroyMethod = "close")
public Connection rabbitMqConnection(RabbitMqIngressConfigProperties properties) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUsername(properties.getUser());
    factory.setPassword(properties.getPassword());
    factory.setVirtualHost(properties.getVirtualHost());
    factory.setHost(properties.getHost());
    factory.setPort(properties.getPort());

    return factory.newConnection();
}
 
Example 10
Source File: RabbitEventChannelTestCase.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void start() throws Exception {
    rabbitMq.start();
    ConnectionFactory connectionFactory = new ConnectionFactory();
    connectionFactory.setHost("localhost");
    connectionFactory.setVirtualHost("/");
    connectionFactory.setUsername("guest");
    connectionFactory.setPassword("guest");
    connection = connectionFactory.newConnection();
    channel = connection.createChannel();
}
 
Example 11
Source File: RabbitMQProducerUtil.java    From flink-learning with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
        //创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();

        //设置RabbitMQ相关信息
        factory.setHost("localhost");
        factory.setUsername("admin");
        factory.setPassword("admin");
        factory.setPort(5672);

        //创建一个新的连接
        Connection connection = factory.newConnection();

        //创建一个通道
        Channel channel = connection.createChannel();

        // 声明一个队列
//        channel.queueDeclare(QUEUE_NAME, false, false, false, null);

        //发送消息到队列中
        String message = "Hello zhisheng";

        for (int i = 0; i < 1000; i++) {
            channel.basicPublish("", QUEUE_NAME, null, (message + i).getBytes("UTF-8"));
            System.out.println("Producer Send +'" + message + i);
        }

        //关闭通道和连接
        channel.close();
        connection.close();
    }
 
Example 12
Source File: ClientHelper.java    From ballerina-message-broker with Apache License 2.0 5 votes vote down vote up
public static Connection getAmqpConnection(String userName, String password, String brokerHost, String port)
        throws IOException, TimeoutException {
    ConnectionFactory connectionFactory = new ConnectionFactory();
    connectionFactory.setUsername(userName);
    connectionFactory.setPassword(password);
    connectionFactory.setVirtualHost("carbon");
    connectionFactory.setHost(brokerHost);
    connectionFactory.setPort(Integer.valueOf(port));
    return connectionFactory.newConnection();
}
 
Example 13
Source File: RabbitMQ.java    From judgels with GNU General Public License v2.0 5 votes vote down vote up
@Inject
public RabbitMQ(RabbitMQConfiguration config) {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(config.getHost());
    factory.setPort(config.getPort());
    factory.setUsername(config.getUsername());
    factory.setPassword(config.getPassword());
    factory.setVirtualHost(config.getVirtualHost());

    this.connectionFactory = factory;
}
 
Example 14
Source File: RabbitMqManager.java    From AuTe-Framework with Apache License 2.0 5 votes vote down vote up
RabbitMqManager(String host, int port, String username, String password) throws JMSException {

        try {
            ConnectionFactory connectionFactory = new ConnectionFactory();
            connectionFactory.setHost(host);
            connectionFactory.setPort(port);
            connectionFactory.setUsername(username);
            connectionFactory.setPassword(password);
            senderConnection = connectionFactory.newConnection();
        } catch (Exception e) {
            log.error("{}", e);
            throw new RuntimeException(e);
        }
    }
 
Example 15
Source File: Registration.java    From NFVO with Apache License 2.0 5 votes vote down vote up
/**
 * Sends a deregistration message to the NFVO
 *
 * @param brokerIp the rabbitmq broker ip
 * @param port the port of rabbitmq
 * @param username the username to connect with
 * @param password the password to connect with
 * @param virtualHost the virtualHost
 * @param managerCredentialUsername the username to remove
 * @param managerCredentialPassword the password to remove
 * @throws IOException In case of InterruptedException
 * @throws TimeoutException in case of TimeoutException
 */
public void deregisterPluginFromNfvo(
    String brokerIp,
    int port,
    String username,
    String password,
    String virtualHost,
    String managerCredentialUsername,
    String managerCredentialPassword)
    throws IOException, TimeoutException {
  String message =
      "{'username':'"
          + managerCredentialUsername
          + "','action':'deregister','password':'"
          + managerCredentialPassword
          + "'}";
  ConnectionFactory factory = new ConnectionFactory();
  factory.setHost(brokerIp);
  factory.setPort(port);
  factory.setUsername(username);
  factory.setPassword(password);
  factory.setVirtualHost(virtualHost);
  Connection connection = factory.newConnection();
  Channel channel = connection.createChannel();

  // check if exchange and queue exist
  channel.exchangeDeclarePassive("openbaton-exchange");
  channel.queueDeclarePassive("nfvo.manager.handling");
  channel.basicQos(1);

  AMQP.BasicProperties props =
      new AMQP.BasicProperties.Builder().contentType("text/plain").build();

  channel.basicPublish("openbaton-exchange", "nfvo.manager.handling", props, message.getBytes());
  channel.close();
  connection.close();
}
 
Example 16
Source File: EndPoint.java    From flink-learning with Apache License 2.0 4 votes vote down vote up
public EndPoint(String endpointName) throws Exception {
    this.endPointName = endpointName;

    ConnectionFactory factory = new ConnectionFactory();

    factory.setHost("127.0.0.1");
    factory.setUsername("admin");
    factory.setPassword("admin");
    factory.setPort(5672);

    connection = factory.newConnection();


    channel = connection.createChannel();

    channel.queueDeclare(endpointName, false, false, false, null);
}
 
Example 17
Source File: AbstractAMQPProcessor.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Creates {@link Connection} to AMQP system.
 */
private Connection createConnection(ProcessContext context) {
    ConnectionFactory cf = new ConnectionFactory();
    cf.setHost(context.getProperty(HOST).getValue());
    cf.setPort(Integer.parseInt(context.getProperty(PORT).getValue()));
    cf.setUsername(context.getProperty(USER).getValue());
    cf.setPassword(context.getProperty(PASSWORD).getValue());
    String vHost = context.getProperty(V_HOST).getValue();
    if (vHost != null) {
        cf.setVirtualHost(vHost);
    }

    // handles TLS/SSL aspects
    final SSLContextService sslService = context.getProperty(SSL_CONTEXT_SERVICE).asControllerService(SSLContextService.class);
    final String rawClientAuth = context.getProperty(CLIENT_AUTH).getValue();
    final SSLContext sslContext;

    if (sslService != null) {
        final SSLContextService.ClientAuth clientAuth;
        if (StringUtils.isBlank(rawClientAuth)) {
            clientAuth = SSLContextService.ClientAuth.REQUIRED;
        } else {
            try {
                clientAuth = SSLContextService.ClientAuth.valueOf(rawClientAuth);
            } catch (final IllegalArgumentException iae) {
                throw new ProviderCreationException(String.format("Unrecognized client auth '%s'. Possible values are [%s]",
                        rawClientAuth, StringUtils.join(SslContextFactory.ClientAuth.values(), ", ")));
            }
        }
        sslContext = sslService.createSSLContext(clientAuth);
    } else {
        sslContext = null;
    }

    // check if the ssl context is set and add it to the factory if so
    if (sslContext != null) {
        cf.useSslProtocol(sslContext);
    }

    try {
        Connection connection = cf.newConnection();
        return connection;
    } catch (Exception e) {
        throw new IllegalStateException("Failed to establish connection with AMQP Broker: " + cf.toString(), e);
    }
}
 
Example 18
Source File: EmbeddedRabbitMqTest.java    From embedded-rabbitmq with Apache License 2.0 4 votes vote down vote up
@Test
  public void start() throws Exception {
    File configFile = temporaryFolder.newFile("rabbitmq.conf");
    PrintWriter writer = new PrintWriter(configFile, "UTF-8");
    writer.println("log.connection.level = debug");
    writer.println("log.channel.level = debug");
    writer.close();

    EmbeddedRabbitMqConfig config = new EmbeddedRabbitMqConfig.Builder()
//        .version(PredefinedVersion.V3_8_0)
        .version(new BaseVersion("3.8.1"))
        .randomPort()
        .downloadFrom(OfficialArtifactRepository.GITHUB)
//        .downloadFrom(new URL("https://github.com/rabbitmq/rabbitmq-server/releases/download/rabbitmq_v3_6_6_milestone1/rabbitmq-server-mac-standalone-3.6.5.901.tar.xz"), "rabbitmq_server-3.6.5.901")
//        .envVar(RabbitMqEnvVar.NODE_PORT, String.valueOf(PORT))
        .envVar(RabbitMqEnvVar.CONFIG_FILE, configFile.toString().replace(".conf", ""))
        .extractionFolder(temporaryFolder.newFolder("extracted"))
        .rabbitMqServerInitializationTimeoutInMillis(TimeUnit.SECONDS.toMillis(20))
        .defaultRabbitMqCtlTimeoutInMillis(TimeUnit.SECONDS.toMillis(20))
        .erlangCheckTimeoutInMillis(TimeUnit.SECONDS.toMillis(10))
//        .useCachedDownload(false)
        .build();

    rabbitMq = new EmbeddedRabbitMq(config);
    rabbitMq.start();
    LOGGER.info("Back in the test!");

    ConnectionFactory connectionFactory = new ConnectionFactory();
    connectionFactory.setHost("localhost");
    connectionFactory.setPort(config.getRabbitMqPort());
    connectionFactory.setVirtualHost("/");
    connectionFactory.setUsername("guest");
    connectionFactory.setPassword("guest");

    Connection connection = connectionFactory.newConnection();
    assertThat(connection.isOpen(), equalTo(true));
    Channel channel = connection.createChannel();
    assertThat(channel.isOpen(), equalTo(true));

    ProcessResult listUsersResult = new RabbitMqCtl(config, Collections.singletonMap("TEST_ENV_VAR", "FooBar"))
        .execute("list_users")
        .get();

    assertThat(listUsersResult.getExitValue(), is(0));
    assertThat(listUsersResult.getOutput().getString(), containsString("guest"));

    RabbitMqPlugins rabbitMqPlugins = new RabbitMqPlugins(config);
    Map<Plugin.State, Set<Plugin>> groupedPlugins = rabbitMqPlugins.groupedList();
    assertThat(groupedPlugins.get(Plugin.State.ENABLED_EXPLICITLY).size(), equalTo(0));

    rabbitMqPlugins.enable("rabbitmq_management");

    Plugin plugin = rabbitMqPlugins.list().get("rabbitmq_management");
    assertThat(plugin, is(notNullValue()));
    assertThat(plugin.getState(),
        hasItems(Plugin.State.ENABLED_EXPLICITLY, Plugin.State.RUNNING));

    HttpURLConnection urlConnection = (HttpURLConnection) new URL("http://localhost:15672").openConnection();
    urlConnection.setRequestMethod("GET");
    urlConnection.connect();

    assertThat(urlConnection.getResponseCode(), equalTo(200));
    urlConnection.disconnect();

    rabbitMqPlugins.disable("rabbitmq_management");

    channel.close();
    connection.close();
  }
 
Example 19
Source File: RabbitMqSource.java    From tangyuan2 with GNU General Public License v3.0 4 votes vote down vote up
public void init(MqSourceVo msVo) throws Throwable {
	Map<String, String> properties = msVo.getProperties();

	if (properties.containsKey("maxConnections".toUpperCase())) {
		this.maxConnections = Integer.parseInt(properties.get("maxConnections".toUpperCase()));
	}

	// if (properties.containsKey("maxSessions".toUpperCase())) {
	// this.maxSessions = Integer.parseInt(properties.get("maxSessions".toUpperCase()));
	// }

	factory = new ConnectionFactory();

	if (properties.containsKey("Host".toUpperCase())) {
		factory.setHost(properties.get("Host".toUpperCase()));
	}
	if (properties.containsKey("Port".toUpperCase())) {
		factory.setPort(Integer.parseInt(properties.get("Port".toUpperCase())));
	}
	if (properties.containsKey("VirtualHost".toUpperCase())) {
		factory.setVirtualHost(properties.get("VirtualHost".toUpperCase()));
	}
	if (properties.containsKey("Username".toUpperCase())) {
		factory.setUsername(properties.get("Username".toUpperCase()));
	}
	if (properties.containsKey("Password".toUpperCase())) {
		factory.setPassword(properties.get("Password".toUpperCase()));
	}

	// factory.setAutomaticRecoveryEnabled(true);
	// factory.setNetworkRecoveryInterval(10000);// attempt recovery every 10 seconds

	// if (maxSessions > 1) {
	// poolSession = true;
	// }

	if (maxConnections > 1) {
		connectionQueue = new LinkedList<Connection>();
		for (int i = 0; i < maxConnections; i++) {
			Connection conn = factory.newConnection();
			connectionQueue.add(conn);
		}
		poolConnection = true;
	} else {
		connection = factory.newConnection();
	}

}
 
Example 20
Source File: EndPoint.java    From flink-learning with Apache License 2.0 4 votes vote down vote up
public EndPoint(String endpointName) throws Exception {
    this.endPointName = endpointName;

    ConnectionFactory factory = new ConnectionFactory();

    factory.setHost("127.0.0.1");
    factory.setUsername("admin");
    factory.setPassword("admin");
    factory.setPort(5672);

    connection = factory.newConnection();


    channel = connection.createChannel();

    channel.queueDeclare(endpointName, false, false, false, null);
}