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

The following examples show how to use com.rabbitmq.client.ConnectionFactory#setPort() . 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: Producer.java    From code with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException, TimeoutException {
    //1、创建一个ConnectionFactory, 并进行配置
    ConnectionFactory connectionFactory = new ConnectionFactory();
    connectionFactory.setHost(Constant.ip);
    connectionFactory.setPort(Constant.port);
    connectionFactory.setVirtualHost("/");

    //2、通过连接工厂创建连接
    Connection connection = connectionFactory.newConnection();

    //3、通过connection创建一个Channel
    Channel channel = connection.createChannel();

    //4、通过Channel发送数据
    for (int i = 0; i < 5; i++) {
        String msg = "Hello RabbitMQ!";
        //1 exchange   2 routingKey
        channel.basicPublish("", "test001", null, msg.getBytes());
    }

    //5、记得要关闭相关的连接
    channel.close();
    connection.close();
}
 
Example 2
Source File: RabbitMQClient.java    From jweb-cms with GNU Affero General Public License v3.0 6 votes vote down vote up
public RabbitMQClient(RabbitMQOptions rabbitMQOptions) {
    ConnectionFactory connectionFactory = new ConnectionFactory();
    connectionFactory.setUsername(rabbitMQOptions.username);
    connectionFactory.setPassword(rabbitMQOptions.password);
    connectionFactory.setVirtualHost(rabbitMQOptions.virtualHost);
    connectionFactory.setHost(rabbitMQOptions.host);
    connectionFactory.setPort(rabbitMQOptions.port);
    connectionFactory.setSharedExecutor(workers);
    connectionFactory.setAutomaticRecoveryEnabled(true);

    GenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig();
    genericObjectPoolConfig.setMinIdle(8);
    genericObjectPoolConfig.setMaxTotal(18);
    genericObjectPoolConfig.setMinIdle(8);
    pool = new GenericObjectPool<>(new RabbitMQChannelFactory(createConnection(connectionFactory)), genericObjectPoolConfig);
}
 
Example 3
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 4
Source File: ManSender.java    From demo_springboot_rabbitmq with Apache License 2.0 6 votes vote down vote up
public ManSender(String queueName) throws Exception {
    this.queueName = queueName;
    // 创建链接工厂
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(host);
    factory.setPort(port);
    factory.setVirtualHost(virtualHost);
    factory.setUsername(userName);
    factory.setPassword(password);
    // 创建链接
    connection = factory.newConnection();

    // 创建消息信道
    channel = connection.createChannel();

    // 生命消息队列
    channel.queueDeclare(queueName, true, false, false, null);
}
 
Example 5
Source File: Producer.java    From code with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {

        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(Constant.ip);
        connectionFactory.setPort(Constant.port);
        connectionFactory.setVirtualHost("/");

        Connection connection = connectionFactory.newConnection();
        Channel channel = connection.createChannel();

        String exchange = "test_consumer_exchange";
        String routingKey = "consumer.save";

        String msg = "Hello RabbitMQ Consumer Message";

        for (int i = 0; i < 5; i++) {
            channel.basicPublish(exchange, routingKey, true, null, msg.getBytes());
        }

    }
 
Example 6
Source File: AMQPCommon.java    From reactive with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
public static Channel connect() throws Exception {
	ConnectionFactory factory = new ConnectionFactory();
	factory.setHost("127.0.0.1");
	factory.setPort(32768);
	Connection conn = factory.newConnection();
	return conn.createChannel();
}
 
Example 7
Source File: Producer4TopicExchange.java    From code with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
	
	//1 创建ConnectionFactory
	ConnectionFactory connectionFactory = new ConnectionFactory();
	connectionFactory.setHost(Constant.ip);
	connectionFactory.setPort(Constant.port);
	connectionFactory.setVirtualHost("/");
	
	//2 创建Connection
	Connection connection = connectionFactory.newConnection();
	//3 创建Channel
	Channel channel = connection.createChannel();  
	//4 声明
	String exchangeName = "test_topic_exchange";
	String routingKey1 = "user.save";
	String routingKey2 = "user.update";
	String routingKey3 = "user.delete.abc";
	//5 发送
	
	String msg = "Hello World RabbitMQ 4 Topic Exchange Message ...";
	channel.basicPublish(exchangeName, routingKey1 , null , msg.getBytes()); 
	channel.basicPublish(exchangeName, routingKey2 , null , msg.getBytes()); 	
	channel.basicPublish(exchangeName, routingKey3 , null , msg.getBytes());

	channel.close();
       connection.close();
}
 
Example 8
Source File: Consumer4DirectExchange.java    From code with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {


        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(Constant.ip);
        connectionFactory.setPort(Constant.port);
        connectionFactory.setVirtualHost("/");

        connectionFactory.setAutomaticRecoveryEnabled(true);
        connectionFactory.setNetworkRecoveryInterval(3000);
        Connection connection = connectionFactory.newConnection();

        Channel channel = connection.createChannel();
        //4 声明
        String exchangeName = "test_direct_exchange";
        String exchangeType = "direct";
        String queueName = "test_direct_queue";
        String routingKey = "test.direct";

        //表示声明了一个交换机
        channel.exchangeDeclare(exchangeName, exchangeType, true, false, false, null);
        //表示声明了一个队列
        channel.queueDeclare(queueName, false, false, false, null);
        //建立一个绑定关系:
        channel.queueBind(queueName, exchangeName, routingKey);

        //durable 是否持久化消息
        QueueingConsumer consumer = new QueueingConsumer(channel);
        //参数:队列名称、是否自动ACK、Consumer
        channel.basicConsume(queueName, true, consumer);
        //循环获取消息  
        while (true) {
            //获取消息,如果没有消息,这一步将会一直阻塞  
            Delivery delivery = consumer.nextDelivery();
            String msg = new String(delivery.getBody());
            System.out.println("收到消息:" + msg);
        }
    }
 
Example 9
Source File: Producer.java    From SpringBoot-Course with MIT License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // 创建链接工厂
    ConnectionFactory connectionFactory = new ConnectionFactory();
    connectionFactory.setHost("127.0.0.1");
    connectionFactory.setPort(5672);
    connectionFactory.setVirtualHost("/");

    // 通过链接工厂创建链接
    Connection connection = connectionFactory.newConnection();

    // 通过链接创建通道(channel)
    Channel channel = connection.createChannel();

    // 通过 channel 发送数据
    // exchange:交换机,如果不传默认为 AMQP default
    String dlxExchangeName = "dlx_exchange_name";
    String dlxRoutingKey = "dlx_routingKey";
    String dlxMsg = "dlx hello world";

    AMQP.BasicProperties basicProperties = new AMQP.BasicProperties.Builder()
            .deliveryMode(2)
            .contentEncoding("UTF-8")
            .expiration("5000") // 设置 5 秒中过期
            .build();

    channel.basicPublish(dlxExchangeName, dlxRoutingKey, basicProperties, dlxMsg.getBytes());

    // 关闭链接
    channel.close();
    connection.close();
}
 
Example 10
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 11
Source File: Producer.java    From code with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
	
	ConnectionFactory connectionFactory = new ConnectionFactory();
	connectionFactory.setHost(Constant.ip);
	connectionFactory.setPort(Constant.port);
	connectionFactory.setVirtualHost("/");
	
	Connection connection = connectionFactory.newConnection();
	Channel channel = connection.createChannel();
	
	String exchange = "test_ack_exchange";
	String routingKey = "ack.save";

	for(int i =0; i<5; i ++){
		
		Map<String, Object> headers = new HashMap<String, Object>();
		headers.put("num", i);
		
		AMQP.BasicProperties properties = new AMQP.BasicProperties.Builder()
				.deliveryMode(2)
				.contentEncoding("UTF-8")
				.headers(headers)
				.build();
		String msg = "Hello RabbitMQ ACK Message " + i;
		channel.basicPublish(exchange, routingKey, true, properties, msg.getBytes());
	}
	
}
 
Example 12
Source File: RabbitMqConnectionFactoy.java    From util4j with Apache License 2.0 5 votes vote down vote up
public static Connection getConnection() throws IOException, TimeoutException {
	ConnectionFactory factory = new ConnectionFactory();
	factory.setHost("127.0.0.1");
	factory.setPort(5672);
	factory.setVirtualHost("/");
	factory.setUsername("guest");
	factory.setPassword("guest");
	return factory.newConnection();
}
 
Example 13
Source File: Consumer.java    From code with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        //1 创建一个ConnectionFactory, 并进行配置
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(Constant.ip);
        connectionFactory.setPort(Constant.port);
        connectionFactory.setVirtualHost("/");

        //2 通过连接工厂创建连接
        Connection connection = connectionFactory.newConnection();

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

        //4 声明(创建)一个队列
        String queueName = "test001";
        channel.queueDeclare(queueName, true, false, false, null);

        //5 创建消费者
        QueueingConsumer queueingConsumer = new QueueingConsumer(channel);

        //6 设置Channel
        channel.basicConsume(queueName, true, queueingConsumer);

        while (true) {
            //7 获取消息
            Delivery delivery = queueingConsumer.nextDelivery();
            String msg = new String(delivery.getBody());
            System.err.println("消费端: " + msg);
            Map<String, Object> headers = delivery.getProperties().getHeaders();
            System.err.println("headers get my1 value: " + headers.get("my1") + "\tmy1 value:" + headers.get("my2"));

            //Envelope envelope = delivery.getEnvelope();
        }

    }
 
Example 14
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 15
Source File: RabbitMQProducerClient.java    From product-ei with Apache License 2.0 5 votes vote down vote up
public RabbitMQProducerClient(String host, int port, String username, String password) {
    factory = new ConnectionFactory();
    factory.setHost(host);
    factory.setPort(port);
    factory.setUsername(username);
    factory.setPassword(password);
}
 
Example 16
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 17
Source File: ConnectionFactoryProducer.java    From hammock with Apache License 2.0 4 votes vote down vote up
@Produces
@ApplicationScoped
public ConnectionFactory createConnectionFactory(RabbitMQConfiguration rabbitMQConfiguration) {
    ConnectionFactory connectionFactory = new ConnectionFactory();
    connectionFactory.setAutomaticRecoveryEnabled(rabbitMQConfiguration.isAutomaticRecovery());
    connectionFactory.setClientProperties(rabbitMQConfiguration.getClientProperties());
    connectionFactory.setConnectionTimeout(rabbitMQConfiguration.getConnectionTimeout());
    connectionFactory.setExceptionHandler(rabbitMQConfiguration.getExceptionHandler());
    connectionFactory.setHandshakeTimeout(rabbitMQConfiguration.getHandshakeTimeout());
    connectionFactory.setHeartbeatExecutor(rabbitMQConfiguration.getHeartbeatExecutor());
    connectionFactory.setMetricsCollector(rabbitMQConfiguration.getMetricsCollector());
    connectionFactory.setHost(rabbitMQConfiguration.getHost());
    connectionFactory.setNetworkRecoveryInterval(rabbitMQConfiguration.getNetworkRecoveryInterval());
    if(rabbitMQConfiguration.isNio()) {
        connectionFactory.useNio();
        connectionFactory.setNioParams(rabbitMQConfiguration.getNioParams());
    }
    connectionFactory.setPassword(rabbitMQConfiguration.getPassword());
    connectionFactory.setPort(rabbitMQConfiguration.getPort());
    connectionFactory.setRequestedChannelMax(rabbitMQConfiguration.getRequestedChannelMax());
    connectionFactory.setRequestedFrameMax(rabbitMQConfiguration.getRequestedFrameMax());
    connectionFactory.setRequestedHeartbeat(rabbitMQConfiguration.getRequestedHeartbeat());
    connectionFactory.setSaslConfig(rabbitMQConfiguration.getSaslConfig());
    connectionFactory.setSharedExecutor(rabbitMQConfiguration.getSharedExecutor());
    connectionFactory.setShutdownExecutor(rabbitMQConfiguration.getShutdownExecutor());
    connectionFactory.setShutdownTimeout(rabbitMQConfiguration.getShutdownTimeout());
    connectionFactory.setSocketConfigurator(rabbitMQConfiguration.getSocketConf());
    connectionFactory.setSocketFactory(rabbitMQConfiguration.getFactory());
    connectionFactory.setThreadFactory(rabbitMQConfiguration.getThreadFactory());
    connectionFactory.setTopologyRecoveryEnabled(rabbitMQConfiguration.isTopologyRecovery());
    try {
        connectionFactory.setUri(rabbitMQConfiguration.getUri());
    }
    catch (Exception e) {
        throw new RuntimeException("Unable to populate URI ",e);
    }
    connectionFactory.setUsername(rabbitMQConfiguration.getUsername());
    connectionFactory.setVirtualHost(rabbitMQConfiguration.getVirtualHost());
    if(rabbitMQConfiguration.getSslContext() != null) {
        connectionFactory.useSslProtocol(rabbitMQConfiguration.getSslContext());
    }
    return connectionFactory;
}
 
Example 18
Source File: ESBJAVA4569RabbiMQSSLStoreWithClientCertValidationTest.java    From product-ei with Apache License 2.0 4 votes vote down vote up
/**
 * Helper method to retrieve queue message from rabbitMQ
 *
 * @return result
 * @throws Exception
 */
private static String consumeWithoutCertificate() throws Exception {
    String result = "";

    String basePath = TestConfigurationProvider.getResourceLocation() + "/artifacts/ESB/messageStore/rabbitMQ/SSL/";

    String truststoreLocation = basePath + "rabbitMQ/certs/client/rabbitstore";
    String keystoreLocation = basePath + "rabbitMQ/certs/client/keycert.p12";

    char[] keyPassphrase = "MySecretPassword".toCharArray();
    KeyStore ks = KeyStore.getInstance("PKCS12");
    ks.load(new FileInputStream(keystoreLocation), keyPassphrase);

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(ks, keyPassphrase);

    char[] trustPassphrase = "rabbitstore".toCharArray();
    KeyStore tks = KeyStore.getInstance("JKS");
    tks.load(new FileInputStream(truststoreLocation), trustPassphrase);

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    tmf.init(tks);

    SSLContext c = SSLContext.getInstance("SSL");
    c.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    factory.setPort(5671);
    factory.useSslProtocol(c);

    Connection conn = factory.newConnection();
    Channel channel = conn.createChannel();

    GetResponse chResponse = channel.basicGet("WithClientCertQueue", true);
    if(chResponse != null) {
        byte[] body = chResponse.getBody();
        result = new String(body);
    }
    channel.close();
    conn.close();
    return result;
}
 
Example 19
Source File: SharedRabbitMQResource.java    From baleen with Apache License 2.0 4 votes vote down vote up
@Override
protected boolean doInitialize(
    final ResourceSpecifier aSpecifier, final Map<String, Object> aAdditionalParams)
    throws ResourceInitializationException {
  try {
    final ConnectionFactory factory = new ConnectionFactory();
    factory.setUsername(username);
    factory.setPassword(password);
    factory.setVirtualHost(virtualHost);
    factory.setHost(host);
    factory.setPort(port);

    if (useHttps) {
      if (trustAll) {
        factory.useSslProtocol();
      } else {

        try (FileInputStream keystoreStream = new FileInputStream(keystorePath);
            FileInputStream trustStoreStream = new FileInputStream(truststorePath); ) {

          KeyStore ks = KeyStore.getInstance("PKCS12");
          ks.load(keystoreStream, keystorePass.toCharArray());

          KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
          kmf.init(ks, keystorePass.toCharArray());

          KeyStore tks = KeyStore.getInstance("JKS");
          tks.load(trustStoreStream, truststorePass.toCharArray());

          TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
          tmf.init(tks);

          SSLContext c = SSLContext.getInstance(sslProtocol);
          c.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

          factory.useSslProtocol(c);
        }
      }
    }

    connection = factory.newConnection();
  } catch (final Exception e) {
    throw new ResourceInitializationException(
        new BaleenException("Error connecting to RabbitMQ", e));
  }

  getMonitor().info("Initialised shared RabbitMQ resource");
  return true;
}
 
Example 20
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();
	}

}