com.rabbitmq.client.ConnectionFactory Java Examples

The following examples show how to use com.rabbitmq.client.ConnectionFactory. 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: Publisher.java    From rabbitmq-tutorial with MIT License 8 votes vote down vote up
public static void main(String[] args) throws NoSuchAlgorithmException, KeyManagementException, URISyntaxException, IOException, InterruptedException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUri("amqp://guest:guest@localhost");
    factory.setConnectionTimeout(300000);
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.queueDeclare("my-queue", true, false, false, null);

    int count = 0;

    while (count < 5000) {
        String message = "Message number " + count;

        channel.basicPublish("", "my-queue", null, message.getBytes());
        count++;
        System.out.println("Published message: " + message);

        Thread.sleep(5000);
    }
}
 
Example #3
Source File: NewTask.java    From java-study with Apache License 2.0 7 votes vote down vote up
public static void main(String[] argv) throws Exception {
	// 创建工厂类
	ConnectionFactory factory = new ConnectionFactory();
	//factory.setHost("localhost");
	factory.setUri("amqp://guest:[email protected]:5672");
	Connection connection = factory.newConnection();
	Channel channel = connection.createChannel();

	channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);
	 Map map=new HashMap();  
        map.put("aa", 11);
        map.put("bb", 22);
        map.put("cc", 33);
	String message = getMessage(argv);

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

	channel.close();
	connection.close();
}
 
Example #4
Source File: RMQSink.java    From flink with Apache License 2.0 6 votes vote down vote up
@Override
public void open(Configuration config) throws Exception {
	ConnectionFactory factory = rmqConnectionConfig.getConnectionFactory();
	try {
		connection = factory.newConnection();
		channel = connection.createChannel();
		if (channel == null) {
			throw new RuntimeException("None of RabbitMQ channels are available");
		}
		setupQueue();
		if (returnListener != null) {
			channel.addReturnListener(returnListener);
		}
	} catch (IOException e) {
		throw new RuntimeException("Error while creating the channel", e);
	}
}
 
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: ConnectionConfig.java    From storm-rabbitmq with MIT License 6 votes vote down vote up
public static ConnectionConfig getFromStormConfig(Map<String, Object> stormConfig) {
    if (stormConfig.containsKey("rabbitmq.uri")) {
        return new ConnectionConfig(getFromMap("rabbitmq.uri", stormConfig));
    } else {
        String highAvailabilityHostsString = getFromMap("rabbitmq.ha.hosts", stormConfig);
        if(highAvailabilityHostsString != null){
            final ConfigAvailableHosts haHosts = ConfigAvailableHosts.fromString(highAvailabilityHostsString);
            return new ConnectionConfig(haHosts,
                getFromMap("rabbitmq.host", stormConfig, ConnectionFactory.DEFAULT_HOST),
                getFromMapAsInt("rabbitmq.port", stormConfig, ConnectionFactory.DEFAULT_AMQP_PORT),
                getFromMap("rabbitmq.username", stormConfig, ConnectionFactory.DEFAULT_USER),
                getFromMap("rabbitmq.password", stormConfig, ConnectionFactory.DEFAULT_PASS),
                getFromMap("rabbitmq.virtualhost", stormConfig, ConnectionFactory.DEFAULT_VHOST),
                getFromMapAsInt("rabbitmq.heartbeat", stormConfig, ConnectionFactory.DEFAULT_HEARTBEAT),
                getFromMapAsBoolean("rabbitmq.ssl", stormConfig, false));
        }else{
          return new ConnectionConfig(getFromMap("rabbitmq.host", stormConfig, ConnectionFactory.DEFAULT_HOST),
                getFromMapAsInt("rabbitmq.port", stormConfig, ConnectionFactory.DEFAULT_AMQP_PORT),
                getFromMap("rabbitmq.username", stormConfig, ConnectionFactory.DEFAULT_USER),
                getFromMap("rabbitmq.password", stormConfig, ConnectionFactory.DEFAULT_PASS),
                getFromMap("rabbitmq.virtualhost", stormConfig, ConnectionFactory.DEFAULT_VHOST),
                getFromMapAsInt("rabbitmq.heartbeat", stormConfig, ConnectionFactory.DEFAULT_HEARTBEAT),
                getFromMapAsBoolean("rabbitmq.ssl", stormConfig, false));
        }
    }
}
 
Example #7
Source File: AmqpWriter.java    From kieker with Apache License 2.0 6 votes vote down vote up
private Connection createConnection() throws KeyManagementException, NoSuchAlgorithmException, URISyntaxException, IOException, TimeoutException {
	final ConnectionFactory connectionFactory = new ConnectionFactory();

	connectionFactory.setUri(this.uri);
	connectionFactory.setRequestedHeartbeat(this.heartbeat);
	// Use only daemon threads for connections. Otherwise, all connections would have to be explicitly
	// closed for the JVM to terminate.
	connectionFactory.setThreadFactory(new DaemonThreadFactory());

	return connectionFactory.newConnection();
}
 
Example #8
Source File: AmqpForwardAttributeTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Test
public void serviceShouldPublishAttributeContentWhenAttributeInMailAndIsAList() throws Exception {
    mailet.init(mailetConfig);
    Channel channel = mock(Channel.class);
    Connection connection = mock(Connection.class);
    when(connection.createChannel()).thenReturn(channel);
    ConnectionFactory connectionFactory = mock(ConnectionFactory.class);
    when(connectionFactory.newConnection()).thenReturn(connection);
    mailet.setConnectionFactory(connectionFactory);
    Mail mail = mock(Mail.class);
    when(mail.getAttribute(MAIL_ATTRIBUTE)).thenReturn(Optional.of(new Attribute(MAIL_ATTRIBUTE, AttributeValue.of(ImmutableList.of(AttributeValue.ofSerializable(ATTACHMENT_CONTENT))))));
    BasicProperties expectedProperties = new AMQP.BasicProperties();

    mailet.service(mail);

    ArgumentCaptor<BasicProperties> basicPropertiesCaptor = ArgumentCaptor.forClass(BasicProperties.class);
    verify(channel).basicPublish(eq(EXCHANGE_NAME), eq(ROUTING_KEY), basicPropertiesCaptor.capture(), eq(ATTACHMENT_CONTENT));
    assertThat(basicPropertiesCaptor.getValue()).isEqualToComparingFieldByField(expectedProperties);
}
 
Example #9
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 #10
Source File: RabbitMqUtilsTest.java    From roboconf-platform with Apache License 2.0 6 votes vote down vote up
@Test
public void testConfigureFactory_nullIp() throws Exception {

	ConnectionFactory factory = new ConnectionFactory();
	String username = "toto";
	String password= "123456789";

	Map<String,String> configuration = new HashMap<> ();
	configuration.put( RABBITMQ_SERVER_IP, null );
	configuration.put( RABBITMQ_SERVER_USERNAME, username );
	configuration.put( RABBITMQ_SERVER_PASSWORD, password );

	RabbitMqUtils.configureFactory( factory, configuration );
	Assert.assertEquals( username, factory.getUsername());
	Assert.assertEquals( password, factory.getPassword());
}
 
Example #11
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 #12
Source File: RMQSourceTest.java    From flink with Apache License 2.0 6 votes vote down vote up
@Test
public void throwExceptionIfConnectionFactoryReturnNull() throws Exception {
	RMQConnectionConfig connectionConfig = Mockito.mock(RMQConnectionConfig.class);
	ConnectionFactory connectionFactory = Mockito.mock(ConnectionFactory.class);
	Connection connection = Mockito.mock(Connection.class);
	Mockito.when(connectionConfig.getConnectionFactory()).thenReturn(connectionFactory);
	Mockito.when(connectionFactory.newConnection()).thenReturn(connection);
	Mockito.when(connection.createChannel()).thenReturn(null);

	RMQSource<String> rmqSource = new RMQSource<>(
		connectionConfig, "queueDummy", true, new StringDeserializationScheme());
	try {
		rmqSource.open(new Configuration());
	} catch (RuntimeException ex) {
		assertEquals("None of RabbitMQ channels are available", ex.getMessage());
	}
}
 
Example #13
Source File: AMQPObservableQueue.java    From conductor with Apache License 2.0 6 votes vote down vote up
AMQPObservableQueue(final ConnectionFactory factory, final Address[] addresses, final boolean useExchange,
		final AMQPSettings settings, final int batchSize, final int pollTimeInMS) {
	if (factory == null) {
		throw new IllegalArgumentException("Connection factory is undefined");
	}
	if (addresses == null || addresses.length == 0) {
		throw new IllegalArgumentException("Addresses are undefined");
	}
	if (settings == null) {
		throw new IllegalArgumentException("Settings are undefined");
	}
	if (batchSize <= 0) {
		throw new IllegalArgumentException("Batch size must be greater than 0");
	}
	if (pollTimeInMS <= 0) {
		throw new IllegalArgumentException("Poll time must be greater than 0 ms");
	}
	this.factory = factory;
	this.addresses = addresses;
	this.useExchange = useExchange;
	this.settings = settings;
	this.batchSize = batchSize;
	this.setPollTimeInMS(pollTimeInMS);
}
 
Example #14
Source File: C.java    From java-study with Apache License 2.0 6 votes vote down vote up
public static void main(String[] argv) throws Exception {
		// 创建连接工厂
		ConnectionFactory factory = new ConnectionFactory();
//		设置RabbitMQ地址
		factory.setHost("127.0.0.1");
//		创建一个新的连接
		Connection connection = factory.newConnection();
//		创建一个频道
		Channel channel = connection.createChannel();
//		声明要关注的队列 -- 在RabbitMQ中,队列声明是幂等性的(一个幂等操作的特点是其任意多次执行所产生的影响均与一次执行的影响相同),也就是说,如果不存在,就创建,如果存在,不会对已经存在的队列产生任何影响。
		channel.queueDeclare(QUEUE_NAME, false, false, false, null);
		System.out.println("C [*] Waiting for messages. To exit press CTRL+C");
//		DefaultConsumer类实现了Consumer接口,通过传入一个频道,告诉服务器我们需要那个频道的消息,如果频道中有消息,就会执行回调函数handleDelivery
		Consumer consumer = new DefaultConsumer(channel) {
			@Override
			public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
				String message = new String(body, "UTF-8");
				System.out.println("C [x] Received '" + message + "'");
			}
		};
//		自动回复队列应答 -- RabbitMQ中的消息确认机制
		channel.basicConsume(QUEUE_NAME, true, consumer);
	}
 
Example #15
Source File: AmqpForwardAttributeTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Test
public void serviceShouldPublishAttributeContentWhenAttributeInMailAndIsAMap() throws Exception {
    mailet.init(mailetConfig);
    Channel channel = mock(Channel.class);
    Connection connection = mock(Connection.class);
    when(connection.createChannel()).thenReturn(channel);
    ConnectionFactory connectionFactory = mock(ConnectionFactory.class);
    when(connectionFactory.newConnection()).thenReturn(connection);
    mailet.setConnectionFactory(connectionFactory);
    Mail mail = mock(Mail.class);
    when(mail.getAttribute(MAIL_ATTRIBUTE)).thenReturn(ATTRIBUTE_CONTENT);
    BasicProperties expectedProperties = new AMQP.BasicProperties();

    mailet.service(mail);

    ArgumentCaptor<BasicProperties> basicPropertiesCaptor = ArgumentCaptor.forClass(BasicProperties.class);
    verify(channel).basicPublish(eq(EXCHANGE_NAME), eq(ROUTING_KEY), basicPropertiesCaptor.capture(), eq(ATTACHMENT_CONTENT));
    assertThat(basicPropertiesCaptor.getValue()).isEqualToComparingFieldByField(expectedProperties);
}
 
Example #16
Source File: RabbitUtil.java    From datacollector with Apache License 2.0 6 votes vote down vote up
public static ConnectionFactory createConnectionFactory(BaseRabbitConfigBean conf) throws StageException {
  RabbitCxnFactoryBuilder builder =
      new RabbitCxnFactoryBuilder(
          conf.uri,
          conf.credentialsConfig.username.get(),
          conf.credentialsConfig.password.get(),
          conf.rabbitmqProperties,
          conf.tlsConfig.getSslContext()
      ).setConnectionTimeout(conf.advanced.connectionTimeout)
          .setAutomaticRecoveryEnabled(conf.advanced.automaticRecoveryEnabled)
          .setNetworkRecoveryInterval(conf.advanced.networkRecoveryInterval)
          .setHeartbeatInterval(conf.advanced.heartbeatInterval)
          .setHandshakeTimeout(conf.advanced.handshakeTimeout)
          .setShutdownTimeout(conf.advanced.shutdownTimeout)
          .setFrameMax(conf.advanced.frameMax)
          .setChannelMax(conf.advanced.channelMax);
  return builder.build();
}
 
Example #17
Source File: ClientSend1.java    From java-study with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args)
    throws java.io.IOException, TimeoutException, KeyManagementException, NoSuchAlgorithmException, URISyntaxException{
        ConnectionFactory factory=new ConnectionFactory(); //创建连接工厂
//        factory.setHost("localhost");
//        factory.setVirtualHost("my_mq");
//        factory.setUsername("zhxia");
//        factory.setPassword("123456");
        factory.setUri("amqp://guest:[email protected]:5672");//获取url
        Connection connection=factory.newConnection(); //创建连接
        Channel channel=connection.createChannel();//创建信道
        channel.queueDeclare(queue_name, durable, false, false, null); //声明消息队列,且为可持久化的
        String message="Hello world"+Math.random();
        //将队列设置为持久化之后,还需要将消息也设为可持久化的,MessageProperties.PERSISTENT_TEXT_PLAIN
        channel.basicPublish("", queue_name, MessageProperties.PERSISTENT_TEXT_PLAIN,message.getBytes());
        System.out.println("Send message:"+message);
        channel.close();
        connection.close();
    }
 
Example #18
Source File: ConnectionConfiguration.java    From rabbitmq-cdi with MIT License 6 votes vote down vote up
@Override
public Connection createConnection(ConnectionFactory connectionFactory)
    throws IOException, TimeoutException {
  connectionFactory.setUsername(username);
  connectionFactory.setPassword(password);
  connectionFactory.setRequestedHeartbeat(requestedConnectionHeartbeatTimeout);
  connectionFactory.setConnectionTimeout(connectTimeout);
  if (secure) {
    final SSLContext sslContext;
    try {
      sslContext = sslContextFactory.createSSLContext();
    } catch (NoSuchAlgorithmException e) {
      throw new IllegalStateException("error during connect, fatal system configuration", e);
    }
    connectionFactory.setSslContextFactory(name -> sslContext);
  }
  if (virtualHost != null) {
    connectionFactory.setVirtualHost(virtualHost);
  }
  if (brokerHosts.isEmpty()) {
    throw new IllegalArgumentException("No broker host defined");
  }
  return connectionFactory.newConnection(new ArrayList<>(brokerHosts));
}
 
Example #19
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 #20
Source File: Recv.java    From java-study with Apache License 2.0 5 votes vote down vote up
public static void main(String[] argv) throws Exception {

    ConnectionFactory factory = new ConnectionFactory();
   // factory.setHost("localhost");
   //  factory.setHost("127.0.0.1");
    factory.setUri("amqp://guest:[email protected]:5672");//获取url
   // 打开连接和创建频道,与发送端一样  
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
 // 声明队列,主要为了防止消息接收者先运行此程序,队列还不存在时创建队列。  
    channel.queueDeclare(QUEUE_NAME, false, false, false, null);
    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
  // 创建队列消费者  
    QueueingConsumer consumer = new QueueingConsumer(channel);
    // 指定消费队列
    channel.basicConsume(QUEUE_NAME, true, consumer);
    while (true) {  //消费者程序运行开着 如果生产者新增了数据会自动获取
    	Thread.sleep(500);
    	 List aa=new ArrayList();
    	 // nextDelivery是一个阻塞方法(内部实现其实是阻塞队列的take方法)  
      QueueingConsumer.Delivery delivery = consumer.nextDelivery();
      String message = new String(delivery.getBody());
      aa.add(message);
      System.out.println("你好吗!"+" [x] Received '" + message + "'"+aa);
    }
   
  }
 
Example #21
Source File: RabbitMQClient_4_x_IT.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Test
public void testPull_autorecovery() throws Exception {
    ConnectionFactory connectionFactory = getConnectionFactory();
    connectionFactory.setAutomaticRecoveryEnabled(true);

    testRunner.runPullTest();
}
 
Example #22
Source File: RabbitMQClient_4_x_IT.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Test
public void testPush_autorecovery() throws Exception {
    ConnectionFactory connectionFactory = getConnectionFactory();
    connectionFactory.setAutomaticRecoveryEnabled(true);

    testRunner.runPushTest();
}
 
Example #23
Source File: RabbitProducer.java    From java-study with Apache License 2.0 5 votes vote down vote up
public static void main(String[] argv) throws Exception {
   //创建连接连接到RabbitMQ 
  ConnectionFactory factory = new ConnectionFactory();
  // 设置ip
  factory.setHost("127.0.0.1");
  /*   //设置端口
  factory.setPort(15672);
  //设置用户名
  factory.setUsername("guest");
  //设置密码
  factory.setPassword("guest");
 //设置url(包括ip、端口、用户名、密码)
  factory.setUri("amqp://guest:guest@localhost:15672");
*/	
  // 创建一个连接  
  Connection connection = factory.newConnection();
  // 创建一个频道 
  Channel channel = connection.createChannel();
  // 指定一个队列  
  channel.queueDeclare(QUEUE_NAME, false, false, false, null);
  Map<String,Object> map=new HashMap<String,Object>();  
    map.put("java", "hello");
    map.put("RabbitMQ", "Hello");
  //发送的消息
  String message = JSON.toJSONString(map); 
  // 往队列中发出一条消息 
  channel.basicPublish("", QUEUE_NAME, null, message.getBytes()); 
  System.out.println(" [x] Sent '" + message + "'");
  // 关闭频道和连接  
  channel.close();
  connection.close();   
}
 
Example #24
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 #25
Source File: RabbitMQClient.java    From jweb-cms with GNU Affero General Public License v3.0 5 votes vote down vote up
private Connection createConnection(ConnectionFactory factory) {
    try {
        return factory.newConnection();
    } catch (Exception e) {
        throw new ApplicationException(e);
    }
}
 
Example #26
Source File: RabbitMQClient_5_x_IT.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Test
public void testPull_nio_autorecovery() throws Exception {
    ConnectionFactory connectionFactory = getConnectionFactory();
    connectionFactory.setAutomaticRecoveryEnabled(true);
    connectionFactory.useNio();

    testRunner.runPullTest();
}
 
Example #27
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 #28
Source File: RPCClient.java    From rabbitmq with GNU General Public License v2.0 5 votes vote down vote up
public RPCClient() throws Exception {
	ConnectionFactory factory = new ConnectionFactory();
	factory.setHost("localhost");
	connection = factory.newConnection();
	channel = connection.createChannel();

	replyQueueName = channel.queueDeclare().getQueue();
	consumer = new QueueingConsumer(channel);
	channel.basicConsume(replyQueueName, true, consumer);
}
 
Example #29
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 #30
Source File: RabbitMqConnFactoryUtil.java    From springboot-learn with MIT License 5 votes vote down vote up
/**
 * 获取rabbit连接方式二
 */
public static Connection getRabbitConn2()
        throws KeyManagementException, NoSuchAlgorithmException, URISyntaxException, IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    // 连接格式:amqp://userName:password@hostName:portNumber/virtualHost
    String uri = String.format("amqp://%s:%s@%s:%d%s", "guest", "guest",
            "192.168.242.131", 5672, "/");
    factory.setUri(uri);
    factory.setVirtualHost("/");
    Connection conn = factory.newConnection();
    return conn;
}