Java Code Examples for com.rabbitmq.client.Connection#createChannel()

The following examples show how to use com.rabbitmq.client.Connection#createChannel() . 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: 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 2
Source File: Events.java    From rabbitmqexample with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {


        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Down Stream server ip (localhost):");
        String server_ip = br.readLine();
        if (server_ip.equalsIgnoreCase("")) {
            server_ip = "localhost";
        }

        ConnectionFactory factory_down = new ConnectionFactory();
        factory_down.setHost(server_ip);
        factory_down.setUsername("test");
        factory_down.setPassword("test");
        factory_down.setVirtualHost("poc");
        Connection connection_down = factory_down.newConnection();
        System.out.println("Connected to Down Stream node: " + server_ip);
        final Channel channel_down = connection_down.createChannel();
        final String exchange = "service";
        channel_down.exchangeDeclare(exchange, "topic", true);
        channel_down.basicPublish(exchange, "r1.gis", MessageProperties.PERSISTENT_BASIC, "better".getBytes());

    }
 
Example 3
Source File: ProducerExchangeConsumer_Direct.java    From util4j with Apache License 2.0 6 votes vote down vote up
public void consumer1() throws Exception {
	//1、获取连接
       Connection connection =RabbitMqConnectionFactoy.getConnection();
       //2、声明通道
       Channel channel = connection.createChannel();
       //3、声明队列
       channel.queueDeclare(QUEUE_NAME1, false, false, false, null);
       //绑定队列到交换机
       channel.queueBind(QUEUE_NAME1, EXCHANGE_NAME,ROUTER_KEY_1);
       //同一时刻服务器只会发送一条消息给消费者(如果设置为N,则当客户端堆积N条消息后服务端不会推送给客户端了)
       //channel.basicQos(1);//每次处理1个
       //4、定义队列的消费者
       //定义消费者
       DefaultConsumer consumer = new DefaultConsumer(channel) {
           @Override
           public void handleDelivery(String consumerTag, Envelope envelope,BasicProperties properties, byte[] body)
                   throws IOException {
               //获取并转成String
               String message = new String(body, "UTF-8");
               System.out.println("-->消费者1号,收到消息,msg :"+message+",header:"+properties.getHeaders().toString());
               channel.basicAck(envelope.getDeliveryTag(), false);
           }
       };
       channel.basicConsume(QUEUE_NAME1, autoAck,consumer);
}
 
Example 4
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 5
Source File: NewTask.java    From rabbitmq with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] argv) throws java.io.IOException, Exception {

		ConnectionFactory factory = new ConnectionFactory();
		factory.setHost("localhost");
		Connection connection = factory.newConnection();
		Channel channel = connection.createChannel();
		channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);
//		�ַ���Ϣ
		for(int i = 0 ; i < 5; i++){
			String message = "Hello World! " + i;
			channel.basicPublish("", TASK_QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes());
			System.out.println(" [x] Sent '" + message + "'");
		}
		channel.close();
		connection.close();
	}
 
Example 6
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_qos_exchange";
	String routingKey = "qos.save";
	
	String msg = "Hello RabbitMQ QOS Message";
	
	for(int i =0; i<5; i ++){
		channel.basicPublish(exchange, routingKey, true, null, msg.getBytes());
	}
	
}
 
Example 7
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 8
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 9
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 10
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 11
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 directExchangeName = "direct_exchange_name";
    String directRoutingKey = "direct_routingKey";
    String directMsg = "direct hello world";

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

    // 关闭链接
    channel.close();
    connection.close();
}
 
Example 12
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 13
Source File: Configure.java    From rabbitmqexample with Apache License 2.0 5 votes vote down vote up
public static void bind_user_queue(Connection connection, String user_name) throws Exception {
    Channel channel = connection.createChannel();
    channel.queueDeclare(get_queue_name_private(user_name), true, false, false, null);
    channel.queueDeclare(get_queue_name_public(user_name), true, false, false, null);
    channel.queueBind(get_queue_name_private(user_name), EXCHANGE_CHAT, user_name.toLowerCase());
    channel.queueBind(get_queue_name_public(user_name), EXCHANGE_CHAT, "public");
    channel.close();
}
 
Example 14
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 15
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 16
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 17
Source File: Consumer4TopicExchange.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_topic_exchange";
	String exchangeType = "topic";
	String queueName = "test_topic_queue";
	String routingKey = "user.#";
	//String routingKey = "user.*";
	// 1 声明交换机 
	channel.exchangeDeclare(exchangeName, exchangeType, true, false, false, null);
	// 2 声明队列
	channel.queueDeclare(queueName, false, false, false, null);
	// 3 建立交换机和队列的绑定关系:
	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 18
Source File: RabbitMqTestCase.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
@Test
public void test() throws Exception {
    EmbeddedRabbitMqConfig configuration = new EmbeddedRabbitMqConfig.Builder()
            // 时间过短会启动失败
            .rabbitMqServerInitializationTimeoutInMillis(60000)
            // 时间过短会停止失败
            .defaultRabbitMqCtlTimeoutInMillis(60000)

            .build();
    EmbeddedRabbitMq rabbitMq = new EmbeddedRabbitMq(configuration);
    try {
        rabbitMq.start();

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

        Connection connection = connectionFactory.newConnection();
        Assert.assertTrue(connection.isOpen());
        Channel channel = connection.createChannel();
        Assert.assertTrue(channel.isOpen());
        channel.close();
        Assert.assertFalse(channel.isOpen());
        connection.close();
        Assert.assertFalse(connection.isOpen());
    } finally {
        rabbitMq.stop();
    }
}
 
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: RabbitMqIOTest.java    From beam with Apache License 2.0 4 votes vote down vote up
@Test
public void testWriteExchange() throws Exception {
  final int maxNumRecords = 1000;
  List<RabbitMqMessage> data =
      RabbitMqTestUtils.generateRecords(maxNumRecords).stream()
          .map(RabbitMqMessage::new)
          .collect(Collectors.toList());
  p.apply(Create.of(data))
      .apply(
          RabbitMqIO.write()
              .withUri("amqp://guest:guest@localhost:" + port)
              .withExchange("WRITE", "fanout"));

  final List<String> received = new ArrayList<>();
  ConnectionFactory connectionFactory = new ConnectionFactory();
  connectionFactory.setUri("amqp://guest:guest@localhost:" + port);
  Connection connection = null;
  Channel channel = null;
  try {
    connection = connectionFactory.newConnection();
    channel = connection.createChannel();
    channel.exchangeDeclare("WRITE", "fanout");
    String queueName = channel.queueDeclare().getQueue();
    channel.queueBind(queueName, "WRITE", "");
    Consumer consumer = new RabbitMqTestUtils.TestConsumer(channel, received);
    channel.basicConsume(queueName, true, consumer);

    p.run();

    while (received.size() < maxNumRecords) {
      Thread.sleep(500);
    }

    assertEquals(maxNumRecords, received.size());
    for (int i = 0; i < maxNumRecords; i++) {
      assertTrue(received.contains("Test " + i));
    }
  } finally {
    if (channel != null) {
      channel.close();
    }
    if (connection != null) {
      connection.close();
    }
  }
}