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

The following examples show how to use com.rabbitmq.client.ConnectionFactory#newConnection() . 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: MainControllerTest.java    From IGUANA with GNU Affero General Public License v3.0 6 votes vote down vote up
public static void sendEnd(String fileName) throws IOException, TimeoutException {
	Config.getInstance(fileName);
	ConnectionFactory factory = new ConnectionFactory();
	factory.setHost("localhost");
	Connection connection = factory.newConnection();
	Channel channel = connection.createChannel();

	channel.queueDeclare(COMMON.CORE2RP_QUEUE_NAME, false, false, false, null);

	Properties p = new Properties();
	p.put(COMMON.EXPERIMENT_TASK_ID_KEY, "1/1/1");
	p.put(COMMON.RECEIVE_DATA_END_KEY, "true");
	send(channel, p);
	channel.close();
	connection.close();
}
 
Example 2
Source File: AbstractRabbitMQConnector.java    From barterli_android with Apache License 2.0 6 votes vote down vote up
/**
 * Connect to the broker and create the exchange
 * 
 * @return success
 */
protected boolean connectToRabbitMQ(final String userName,
                final String password) {
    if ((mChannel != null) && mChannel.isOpen()) {
        return true;
    }
    try {
        final ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(mServer);
        connectionFactory.setUsername(userName);
        connectionFactory.setPassword(password);
        connectionFactory.setVirtualHost(mVirtualHost);
        connectionFactory.setPort(mPort);
        connectionFactory.setRequestedHeartbeat(AppConstants.HEART_BEAT_INTERVAL);
        mConnection = connectionFactory.newConnection();
        mChannel = mConnection.createChannel();
        mChannel.exchangeDeclare(mExchange, mExchangeType.key);

        return true;
    } catch (final Exception e) {
        e.printStackTrace();
        return false;
    }
}
 
Example 3
Source File: RabbitMqConsumer.java    From flowing-retail-old with Apache License 2.0 6 votes vote down vote up
protected void connect() throws Exception {
  ConnectionFactory factory = new ConnectionFactory();
  factory.setHost("localhost");
  Connection connection = factory.newConnection();
  channel = connection.createChannel();

  String queueName = "flowing-retail-" + name;
  channel.queueDeclare(queueName, true, false, false, null);
  channel.exchangeDeclare(EXCHANGE_NAME, "fanout", true); // publish/subscribe model
  channel.queueBind(queueName, EXCHANGE_NAME, "*");

  System.out.println(" [*] Waiting for messages.");

  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(" [x] Received '" + message + "'");
      eventHandler.handleEvent(message);
    }
  };
  channel.basicConsume(queueName, true, consumer);
}
 
Example 4
Source File: RabbitMQSource.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@Override
public void open(Map<String, Object> config, SourceContext sourceContext) throws Exception {
    rabbitMQSourceConfig = RabbitMQSourceConfig.load(config);
    rabbitMQSourceConfig.validate();

    ConnectionFactory connectionFactory = rabbitMQSourceConfig.createConnectionFactory();
    rabbitMQConnection = connectionFactory.newConnection(rabbitMQSourceConfig.getConnectionName());
    logger.info("A new connection to {}:{} has been opened successfully.",
            rabbitMQConnection.getAddress().getCanonicalHostName(),
            rabbitMQConnection.getPort()
    );
    rabbitMQChannel = rabbitMQConnection.createChannel();
    rabbitMQChannel.queueDeclare(rabbitMQSourceConfig.getQueueName(), false, false, false, null);
    logger.info("Setting channel.basicQos({}, {}).",
            rabbitMQSourceConfig.getPrefetchCount(),
            rabbitMQSourceConfig.isPrefetchGlobal()
    );
    rabbitMQChannel.basicQos(rabbitMQSourceConfig.getPrefetchCount(), rabbitMQSourceConfig.isPrefetchGlobal());
    com.rabbitmq.client.Consumer consumer = new RabbitMQConsumer(this, rabbitMQChannel);
    rabbitMQChannel.basicConsume(rabbitMQSourceConfig.getQueueName(), consumer);
    logger.info("A consumer for queue {} has been successfully started.", rabbitMQSourceConfig.getQueueName());
}
 
Example 5
Source File: RabbitMqBenchmarkDriver.java    From openmessaging-benchmark with Apache License 2.0 6 votes vote down vote up
@Override
public void initialize(File configurationFile, StatsLogger statsLogger) throws IOException {
    config = mapper.readValue(configurationFile, RabbitMqConfig.class);

    ConnectionFactory connectionFactory = new ConnectionFactory();
    connectionFactory.setAutomaticRecoveryEnabled(true);
    connectionFactory.setHost(config.brokerAddress);
    connectionFactory.setUsername("admin");
    connectionFactory.setPassword("admin");

    try {
        connection = connectionFactory.newConnection();
    } catch (TimeoutException e) {
        e.printStackTrace();
    }
}
 
Example 6
Source File: Send.java    From demo_springboot_rabbitmq with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException, TimeoutException {

        //建立连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //设置连接地址
        factory.setHost("seaof-153-125-234-173.jp-tokyo-10.arukascloud.io");
        factory.setPort(31084);
        //获取连接
        Connection connection = factory.newConnection();
        //获取渠道
        Channel channel = connection.createChannel();
        //声明队列,如果不存在就新建
        //参数1队列名称;参数2是否持久化;参数3排他性队列,连接断开自动删除;参数4是否自动删除;参数5.参数
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        //发送的消息
        String message = Thread.currentThread().getName() + "Hello ";

        //参数1 交换机;参数2 路由键;参数3 基础属性;参数4 消息体
        channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
        System.out.println(Thread.currentThread().getName() + "[send]" + message);
        channel.close();
        connection.close();

    }
 
Example 7
Source File: AmqpRule.java    From james-project with Apache License 2.0 5 votes vote down vote up
private boolean isReady(ConnectionFactory factory) {
    try (Connection connection = factory.newConnection()) {
        return true;
    } catch (IOException | TimeoutException e) {
        return false;
    }
}
 
Example 8
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 topicExchangeName = "topic_exchange_name";
    String topicRoutingKey1 = "topic_routingKey.test1";
    String topicRoutingKey2 = "topic_routingKey.test2";
    String topicRoutingKey3 = "topic_routingKey.test3.test03";
    String topicMsg = "topic hello world";

    channel.basicPublish(topicExchangeName, topicRoutingKey1, null, topicMsg.getBytes());
    channel.basicPublish(topicExchangeName, topicRoutingKey2, null, topicMsg.getBytes());
    channel.basicPublish(topicExchangeName, topicRoutingKey3, null, topicMsg.getBytes());

    // 关闭链接
    channel.close();
    connection.close();
}
 
Example 9
Source File: MQConfig.java    From jseckill with Apache License 2.0 5 votes vote down vote up
@Bean("mqConnectionReceive")
public Connection mqConnectionReceive(@Autowired MQConfigBean mqConfigBean) throws IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    //用户名
    factory.setUsername(username);
    //密码
    factory.setPassword(password);
    //虚拟主机路径(相当于数据库名)
    factory.setVirtualHost(virtualHost);
    //返回连接
    return factory.newConnection(mqConfigBean.getAddressList());
}
 
Example 10
Source File: PropertiesSenderStorageTest.java    From IGUANA with GNU Affero General Public License v3.0 5 votes vote down vote up
@BeforeClass
public static void before() throws IOException, TimeoutException{
	ConnectionFactory factory = new ConnectionFactory();
	factory.setHost("localhost");
	conn = factory.newConnection();
	recv = conn.createChannel();
	recv.queueDeclare("rp2senderQueue", false, false,
			false, null);
	consumer = new DefaultReturnConsumer(recv);
	recv.basicConsume("rp2senderQueue", true, consumer);
}
 
Example 11
Source File: ChannelUtils.java    From demo_springboot_rabbitmq with Apache License 2.0 5 votes vote down vote up
private static Channel getChannel() throws IOException, TimeoutException {
    //建立连接工厂
    ConnectionFactory factory = new ConnectionFactory();
    //设置连接地址
    factory.setHost("seaof-153-125-234-173.jp-tokyo-10.arukascloud.io");
    factory.setPort(31084);
    //获取连接
    Connection connection = factory.newConnection();
    //获取渠道
    Channel channel = connection.createChannel();
    return channel;
}
 
Example 12
Source File: MockConnectionFactoryTest.java    From rabbitmq-mock with Apache License 2.0 5 votes vote down vote up
@Test
void use_alternate_factory() throws IOException, TimeoutException {
    ConnectionFactory factory = new MockConnectionFactoryWithoutAddressResolver();

    Connection connection = factory.newConnection(null, (List<Address>) null, null);

    assertThat(connection).isInstanceOf(MockConnection.class);
}
 
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: 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 15
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 qosExchangeName = "qos_exchange_name";
    String qosRoutingKey = "qos_routingKey";
    String qosMsg = "qos hello world";

    channel.basicPublish(qosExchangeName, qosRoutingKey, null, qosMsg.getBytes());
    channel.basicPublish(qosExchangeName, qosRoutingKey, null, qosMsg.getBytes());
    channel.basicPublish(qosExchangeName, qosRoutingKey, null, qosMsg.getBytes());

    // 关闭链接
    channel.close();
    connection.close();
}
 
Example 16
Source File: Consumer.java    From code with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
    //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、 获取消息
        QueueingConsumer.Delivery delivery = queueingConsumer.nextDelivery();
        String msg = new String(delivery.getBody());
        System.err.println("消费端: " + msg);
        //Envelope envelope = delivery.getEnvelope();
    }

}
 
Example 17
Source File: Consumer.java    From rabbitmq-tutorial with MIT License 5 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);

    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume("my-queue", false, consumer);

    while (true) {
        QueueingConsumer.Delivery delivery = consumer.nextDelivery();

        if (delivery != null) {
            try {
                String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
                System.out.println("Message consumed: " + message);
                // Interact with IO
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            } catch (Exception e) {
                channel.basicReject(delivery.getEnvelope().getDeliveryTag(), true);
            }
        }
    }

}
 
Example 18
Source File: RabbitMQClusterTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@BeforeEach
void setup(DockerRabbitMQCluster cluster) throws IOException, TimeoutException {
    node1ConnectionFactory = cluster.getRabbitMQ1().connectionFactory();
    resilientConnection = node1ConnectionFactory.newConnection(cluster.getAddresses());
    resilientChannel = resilientConnection.createChannel();
    ConnectionFactory node2ConnectionFactory = cluster.getRabbitMQ2().connectionFactory();
    node2Connection = node2ConnectionFactory.newConnection();
    node2Channel = node2Connection.createChannel();
}
 
Example 19
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 20
Source File: Worker.java    From neo4j-mazerunner with Apache License 2.0 4 votes vote down vote up
public void doMain(String[] args) throws Exception {

        CmdLineParser parser = new CmdLineParser(this);

        // if you have a wider console, you could increase the value;
        // here 80 is also the default
        parser.setUsageWidth(80);

        try {
            // parse the arguments.
            parser.parseArgument(args);

            if(sparkMaster == "" || hadoopHdfs == "")
                throw new CmdLineException(parser, "Options required: --hadoop.hdfs <url>, --spark.master <url>");

            ConfigurationLoader.getInstance().setHadoopHdfsUri(hadoopHdfs);
            ConfigurationLoader.getInstance().setSparkHost(sparkMaster);
            ConfigurationLoader.getInstance().setAppName(sparkAppName);
            ConfigurationLoader.getInstance().setExecutorMemory(sparkExecutorMemory);
            ConfigurationLoader.getInstance().setDriverHost(driverHost);
            ConfigurationLoader.getInstance().setRabbitmqNodename(rabbitMqHost);

        } catch( CmdLineException e ) {
            // if there's a problem in the command line,
            // you'll get this exception. this will report
            // an error message.
            System.err.println(e.getMessage());
            System.err.println("java -cp $CLASSPATH [<spark-config-options>] <main-class> [<mazerunner-args>]");
            // print the list of available options
            parser.printUsage(System.err);
            System.err.println();

            // print option sample. This is useful some time
            System.err.println("  Example: java -cp $CLASSPATH org.mazerunner.core.messaging.Worker"+parser.printExample(ALL));

            return;
        }

        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.basicQos(20);

        // Initialize spark context
        GraphProcessor.initializeSparkContext();

        QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume(TASK_QUEUE_NAME, false, consumer);

        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

        while (true) {
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            String message = new String(delivery.getBody());

            System.out.println(" [x] Received '" + message + "'");

            // Deserialize message
            Gson gson = new Gson();
            ProcessorMessage processorMessage = gson.fromJson(message, ProcessorMessage.class);

            // Run PageRank
            GraphProcessor.processEdgeList(processorMessage);

            System.out.println(" [x] Done '" + message + "'");
            channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        }
    }