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

The following examples show how to use com.rabbitmq.client.ConnectionFactory#setHost() . 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: ESBJAVA4569RabbiMQSSLStoreWithoutClientCertValidationTest.java    From product-ei with Apache License 2.0 9 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 = "";
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    factory.setPort(5671);
    factory.useSslProtocol();

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

    GetResponse chResponse = channel.basicGet("WithoutClientCertQueue", true);
    if(chResponse != null) {
        byte[] body = chResponse.getBody();
        result = new String(body);
    }
    channel.close();
    conn.close();
    return result;
}
 
Example 2
Source File: RabbitMQConfiguration.java    From cukes with Apache License 2.0 8 votes vote down vote up
@Bean
@DependsOn("amqpBroker")
CachingConnectionFactory connectionFactory() {
    log.info("Creating connection factory for MQ broker...");
    ConnectionFactory cf = new ConnectionFactory();
    cf.setHost(hostname);
    cf.setPort(port);
    cf.setUsername(userName);
    cf.setPassword(password);
    cf.setVirtualHost(virtualHost);
    cf.setAutomaticRecoveryEnabled(false);
    if (useSSL) {
        try {
            cf.useSslProtocol();
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            //TODO don't throw raw exceptions
            throw new RuntimeException(e);
        }
    }

    log.info("Connection factory created.");
    return new CachingConnectionFactory(cf);
}
 
Example 3
Source File: Producer.java    From SpringBoot-Course with MIT License 6 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 directExchangeName = "direct_exchange_name";
    String directRoutingKey = "direct_routingKey";
    String directMsg = "direct hello world";

    channel.basicPublish(directExchangeName, directRoutingKey, null, directMsg.getBytes());

    // 关闭链接
    channel.close();
    connection.close();
}
 
Example 4
Source File: AgentManagementServiceImpl.java    From Insights with Apache License 2.0 6 votes vote down vote up
private void publishAgentAction(String routingKey, byte[] data, BasicProperties props)
		throws TimeoutException, IOException {
	String exchangeName = ApplicationConfigProvider.getInstance().getAgentDetails().getAgentExchange();
	ConnectionFactory factory = new ConnectionFactory();
	factory.setHost(ApplicationConfigProvider.getInstance().getMessageQueue().getHost());
	factory.setUsername(ApplicationConfigProvider.getInstance().getMessageQueue().getUser());
	factory.setPassword(ApplicationConfigProvider.getInstance().getMessageQueue().getPassword());
	Connection connection = factory.newConnection();
	Channel channel = connection.createChannel();
	channel.exchangeDeclare(exchangeName, MessageConstants.EXCHANGE_TYPE, true);
	channel.queueDeclare(routingKey, true, false, false, null);
	channel.queueBind(routingKey, exchangeName, routingKey);
	channel.basicPublish(exchangeName, routingKey, props, data);
	channel.close();
	connection.close();
}
 
Example 5
Source File: RoutingSendDirect.java    From rabbitmq with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] argv) throws Exception {

        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
//		����������
        channel.exchangeDeclare(EXCHANGE_NAME, "direct");
//		������Ϣ
        for(String severity :routingKeys){
        	String message = "Send the message level:" + severity;
        	channel.basicPublish(EXCHANGE_NAME, severity, null, message.getBytes());
        	System.out.println(" [x] Sent '" + severity + "':'" + message + "'");
        }
        channel.close();
        connection.close();
    }
 
Example 6
Source File: Worker.java    From neo4j-mazerunner with Apache License 2.0 6 votes vote down vote up
public static void sendMessage(String message)
        throws java.io.IOException {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(ConfigurationLoader.getInstance().getRabbitmqNodename());
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);

    channel.basicPublish( "", TASK_QUEUE_NAME,
            MessageProperties.PERSISTENT_TEXT_PLAIN,
            message.getBytes());
    System.out.println(" [x] Sent '" + message + "'");

    channel.close();
    connection.close();
}
 
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: P.java    From rabbitmq with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] argv) throws Exception {
  ConnectionFactory factory = new ConnectionFactory();
  factory.setHost("localhost");
  Connection connection = factory.newConnection();
  Channel channel = connection.createChannel();
  
  channel.queueDeclare(QUEUE_NAME, false, false, false, null);
  String message = "Hello World!";
  channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8"));
  System.out.println("P [x] Sent '" + message + "'");

  channel.close();
  connection.close();
}
 
Example 9
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 10
Source File: AbstractRabbitMQInputOperator.java    From attic-apex-malhar with Apache License 2.0 5 votes vote down vote up
@Override
  public void activate(OperatorContext ctx)
  {
    try {
      connFactory = new ConnectionFactory();
      connFactory.setHost(host);
      if (port != 0) {
        connFactory.setPort(port);
      }

      connection = connFactory.newConnection();
      channel = connection.createChannel();

      channel.exchangeDeclare(exchange, exchangeType);
      boolean resetQueueName = false;
      if (queueName == null) {
        // unique queuename is generated
        // used in case of fanout exchange
        queueName = channel.queueDeclare().getQueue();
        resetQueueName = true;
      } else {
        // user supplied name
        // used in case of direct exchange
        channel.queueDeclare(queueName, true, false, false, null);
      }

      channel.queueBind(queueName, exchange, routingKey);

//      consumer = new QueueingConsumer(channel);
//      channel.basicConsume(queueName, true, consumer);
      tracingConsumer = new TracingConsumer(channel);
      cTag = channel.basicConsume(queueName, false, tracingConsumer);
      if (resetQueueName) {
        queueName = null;
      }
    } catch (IOException ex) {
      throw new RuntimeException("Connection Failure", ex);
    }
  }
 
Example 11
Source File: TradeReader.java    From ThriftBook with Apache License 2.0 5 votes vote down vote up
public static void main(String[] argv)
    throws java.io.IOException,
           java.lang.InterruptedException,
           java.util.concurrent.TimeoutException,
           TException,
           TTransportException {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    channel.queueDeclare(QUEUE_NAME, false, false, false, null);
    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(QUEUE_NAME, true, consumer);

    System.out.println("Waiting for trade reports...");
    while (true) {
        QueueingConsumer.Delivery delivery = consumer.nextDelivery();
        byte[] data = delivery.getBody();
        TMemoryBuffer trans = new TMemoryBuffer(data.length);
        trans.write(data, 0, data.length);
        TCompactProtocol proto = new TCompactProtocol(trans);
        TradeReport tr = new TradeReport();
        tr.read(proto);
        System.out.println("[" + tr.seq_num + "] " + tr.symbol + 
                           " @ " + tr.price + " x " + tr.size);
    }
}
 
Example 12
Source File: ScoreMarkConfig.java    From ExamStack with GNU General Public License v2.0 5 votes vote down vote up
@Bean
QueueingConsumer queueingConsumer() throws IOException {
	ConnectionFactory factory = new ConnectionFactory();
	factory.setHost(messageQueueHostname);
	Connection connection = factory.newConnection();
	Channel channel = connection.createChannel();
	channel.queueDeclare(Constants.ANSWERSHEET_DATA_QUEUE, true, false, false, null);
	QueueingConsumer consumer = new QueueingConsumer(channel);
	channel.basicConsume(Constants.ANSWERSHEET_DATA_QUEUE, true, consumer);
	return consumer;

}
 
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: Emitter.java    From helix with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
  if (args.length < 1) {
    System.err
        .println("USAGE: java Emitter rabbitmqServer (e.g. localhost) numberOfMessage (optional)");
    System.exit(1);
  }

  final String mqServer = args[0]; // "zzhang-ld";
  int count = Integer.MAX_VALUE;
  if (args.length > 1) {
    try {
      count = Integer.parseInt(args[1]);
    } catch (Exception e) {
      // TODO: handle exception
    }
  }
  System.out.println("Sending " + count + " messages with random topic id");

  ConnectionFactory factory = new ConnectionFactory();
  factory.setHost(mqServer);
  Connection connection = factory.newConnection();
  Channel channel = connection.createChannel();

  channel.exchangeDeclare(EXCHANGE_NAME, "topic");

  for (int i = 0; i < count; i++) {
    int rand = ((int) (Math.random() * 10000) % SetupConsumerCluster.DEFAULT_PARTITION_NUMBER);
    String routingKey = "topic_" + rand;
    String message = "message_" + rand;

    channel.basicPublish(EXCHANGE_NAME, routingKey, null, message.getBytes());
    System.out.println(" [x] Sent '" + routingKey + "':'" + message + "'");

    Thread.sleep(1000);
  }

  connection.close();
}
 
Example 15
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 {
	
	
	ConnectionFactory connectionFactory = new ConnectionFactory();
	connectionFactory.setHost(Constant.ip);
	connectionFactory.setPort(Constant.port);
	connectionFactory.setVirtualHost("/");
	
	Connection connection = connectionFactory.newConnection();
	Channel channel = connection.createChannel();
	
	
	String exchangeName = "test_qos_exchange";
	String queueName = "test_qos_queue";
	String routingKey = "qos.#";
	
	channel.exchangeDeclare(exchangeName, "topic", true, false, null);
	channel.queueDeclare(queueName, true, false, false, null);
	channel.queueBind(queueName, exchangeName, routingKey);
	
	/*
	 * prefetchSize:消息限制大小,一般为0,不做限制。
	 * prefetchCount:一次处理消息的个数,一般设置为1
	 * global:一般为false。true,在channel级别做限制;false,在consumer级别做限制
	 */
	channel.basicQos(0, 1, false);

	// 限流方式  第一件事就是 autoAck设置为 false
	channel.basicConsume(queueName, false, new MyConsumer(channel));
	
	
}
 
Example 16
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 17
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 18
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 19
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 20
Source File: RabbitMQConsumerClient.java    From micro-integrator with Apache License 2.0 4 votes vote down vote up
public RabbitMQConsumerClient(String host) {
    factory = new ConnectionFactory();
    factory.setHost(host);
}