com.rabbitmq.client.Channel Java Examples

The following examples show how to use com.rabbitmq.client.Channel. 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: 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 #2
Source File: MetricsCollectorTest.java    From rabbitmq-mock with Apache License 2.0 6 votes vote down vote up
@Test
void metrics_collector_is_invoked_on_basic_nack() throws IOException, TimeoutException {
    MockConnectionFactory mockConnectionFactory = new MockConnectionFactory();
    SimpleMeterRegistry registry = new SimpleMeterRegistry();
    mockConnectionFactory.setMetricsCollector(new MicrometerMetricsCollector(registry));

    try (MockConnection connection = mockConnectionFactory.newConnection();
         Channel channel = connection.createChannel(42)) {
        String queueName = channel.queueDeclare().getQueue();
        channel.basicPublish("", queueName, null, "".getBytes());
        GetResponse getResponse = channel.basicGet(queueName, false);

        assertThat(registry.get("rabbitmq.rejected").counter().count()).isEqualTo(0);
        channel.basicNack(getResponse.getEnvelope().getDeliveryTag(), false, false);
        assertThat(registry.get("rabbitmq.rejected").counter().count()).isEqualTo(1);
    }
}
 
Example #3
Source File: AMQPPublisher.java    From nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Publishes message with provided AMQP properties (see
 * {@link BasicProperties}) to a pre-defined AMQP Exchange.
 *
 * @param bytes bytes representing a message.
 * @param properties instance of {@link BasicProperties}
 * @param exchange the name of AMQP exchange to which messages will be published.
 *            If not provided 'default' exchange will be used.
 * @param routingKey (required) the name of the routingKey to be used by AMQP-based
 *            system to route messages to its final destination (queue).
 */
void publish(byte[] bytes, BasicProperties properties, String routingKey, String exchange) {
    this.validateStringProperty("routingKey", routingKey);
    exchange = exchange == null ? "" : exchange.trim();
    if (exchange.length() == 0) {
        processLog.info("The 'exchangeName' is not specified. Messages will be sent to default exchange");
    }
    processLog.info("Successfully connected AMQPPublisher to " + this.connectionString + " and '" + exchange
            + "' exchange with '" + routingKey + "' as a routing key.");

    final Channel channel = getChannel();
    if (channel.isOpen()) {
        try {
            channel.basicPublish(exchange, routingKey, true, properties, bytes);
        } catch (Exception e) {
            throw new IllegalStateException("Failed to publish to Exchange '" + exchange + "' with Routing Key '" + routingKey + "'.", e);
        }
    } else {
        throw new IllegalStateException("This instance of AMQPPublisher is invalid since its publishingChannel is closed");
    }
}
 
Example #4
Source File: ComplexUseCasesTests.java    From rabbitmq-mock with Apache License 2.0 6 votes vote down vote up
@Test
void expired_message_should_be_consumable_after_being_dead_lettered() throws IOException, TimeoutException, InterruptedException {
    try (Connection conn = new MockConnectionFactory().newConnection()) {
        try (Channel channel = conn.createChannel()) {
            channel.exchangeDeclare("rejected-ex", BuiltinExchangeType.FANOUT);
            channel.queueDeclare("rejected", true, false, false, null);
            channel.queueBindNoWait("rejected", "rejected-ex", "unused", null);
            queue("fruits").withMessageTtl(10L).withDeadLetterExchange("rejected-ex").declare(channel);

            List<String> messages = new ArrayList<>();
            channel.basicConsume("rejected", new DefaultConsumer(channel) {
                @Override
                public void handleDelivery(String consumerTag,
                                           Envelope envelope,
                                           AMQP.BasicProperties properties,
                                           byte[] body) {
                    messages.add(new String(body));
                }
            });

            channel.basicPublish("", "fruits", null, "banana".getBytes());
            TimeUnit.MILLISECONDS.sleep(100L);
            assertThat(messages).hasSize(1);
        }
    }
}
 
Example #5
Source File: RabbitMqUtilsTest.java    From roboconf-platform with Apache License 2.0 6 votes vote down vote up
@Test
public void testCloseConnection() throws Exception {
	Assume.assumeTrue( rabbitMqIsRunning );

	Channel channel = RabbitMqTestUtils.createTestChannel();
	Assert.assertTrue( channel.isOpen());
	Assert.assertTrue( channel.getConnection().isOpen());

	// Close it
	RabbitMqUtils.closeConnection( channel );
	Assert.assertFalse( channel.isOpen());
	Assert.assertFalse( channel.getConnection().isOpen());

	// Make sure closing an already closed channel does not throw an exception
	RabbitMqUtils.closeConnection( channel );
	Assert.assertFalse( channel.isOpen());
	Assert.assertFalse( channel.getConnection().isOpen());
}
 
Example #6
Source File: ProducerExchangeConsumer_Topic.java    From util4j with Apache License 2.0 6 votes vote down vote up
public void consumer2() throws Exception {
	//1、获取连接
       Connection connection =RabbitMqConnectionFactoy.getConnection();
       //2、声明通道
       Channel channel = connection.createChannel();
       //3、声明队列
       channel.queueDeclare(QUEUE_NAME2, false, false, false, null);
       //绑定队列到交换机
       channel.queueBind(QUEUE_NAME2, EXCHANGE_NAME,"test.#");//基数偶数都接收
       //同一时刻服务器只会发送一条消息给消费者(如果设置为N,则当客户端堆积N条消息后服务端不会推送给客户端了)
       //channel.basicQos(1);//每次只从服务器取1个处理
       //4、定义队列的消费者
       DeliverCallback deliverCallback = (consumerTag, delivery) -> {
           String message = new String(delivery.getBody(), "UTF-8");
           System.out.println("-->消费者2号,收到消息,msg :"+message+",header:"+delivery.getProperties().getHeaders().toString());
           channel.basicAck( delivery.getEnvelope().getDeliveryTag(), false);
       };
       channel.basicConsume(QUEUE_NAME2, autoAck, deliverCallback, consumerTag -> { });
}
 
Example #7
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 #8
Source File: MetricsCollectorTest.java    From rabbitmq-mock with Apache License 2.0 6 votes vote down vote up
@Test
void metrics_collector_is_invoked_on_basic_reject() throws IOException, TimeoutException {
    MockConnectionFactory mockConnectionFactory = new MockConnectionFactory();
    SimpleMeterRegistry registry = new SimpleMeterRegistry();
    mockConnectionFactory.setMetricsCollector(new MicrometerMetricsCollector(registry));

    try (MockConnection connection = mockConnectionFactory.newConnection();
         Channel channel = connection.createChannel(42)) {
        String queueName = channel.queueDeclare().getQueue();
        channel.basicPublish("", queueName, null, "".getBytes());
        GetResponse getResponse = channel.basicGet(queueName, false);

        assertThat(registry.get("rabbitmq.rejected").counter().count()).isEqualTo(0);
        channel.basicReject(getResponse.getEnvelope().getDeliveryTag(), false);
        assertThat(registry.get("rabbitmq.rejected").counter().count()).isEqualTo(1);
    }
}
 
Example #9
Source File: ChannelTest.java    From rabbitmq-mock with Apache License 2.0 6 votes vote down vote up
@Test
void exchangeBind_binds_two_exchanges() throws IOException, TimeoutException {
    try (Connection conn = new MockConnectionFactory().newConnection()) {
        try (Channel channel = conn.createChannel()) {
            assertThat(channel.exchangeDeclare("ex-from", BuiltinExchangeType.FANOUT)).isNotNull();
            assertThat(channel.exchangeDeclare("ex-to", BuiltinExchangeType.FANOUT)).isNotNull();
            assertThat(channel.queueDeclare()).isNotNull();

            assertThat(channel.exchangeBind("ex-to", "ex-from", "test.key")).isNotNull();
            assertThat(channel.queueBind("", "ex-to", "queue.used")).isNotNull();

            channel.basicPublish("ex-from", "unused", null, "test message".getBytes());
            GetResponse response = channel.basicGet("", false);
            assertThat(response).isNotNull();
            assertThat(new String(response.getBody())).isEqualTo("test message");
        }
    }
}
 
Example #10
Source File: AMQPConsumer.java    From reactive with Creative Commons Zero v1.0 Universal 6 votes vote down vote up
public void execute(String mode) throws Exception {
	
	Channel channel = AMQPCommon.connect();
	QueueingConsumer consumer = new QueueingConsumer(channel);
	channel.basicConsume("trade.request.q", true, consumer);
	
	if (mode.equalsIgnoreCase("stable")) {lower = 300; upper = 1200;}
	if (mode.equalsIgnoreCase("better")) {lower = 300; upper = 800;}
	if (mode.equalsIgnoreCase("worse")) {lower = 800; upper = 1900;}
	if (mode.equalsIgnoreCase("erratic")) {lower = 200; upper = 5000;}

	while (true) {
		QueueingConsumer.Delivery message = consumer.nextDelivery();
		String msg = new String(message.getBody());
		System.out.println("trade order received: " + msg);
		int response = lower + (int) (Math.random() * (upper-lower));
		System.out.println("trade placed, duration = " + response);
		String newMsg = "response";
		byte[] bmsg = newMsg.getBytes();
		Thread.sleep(response);
		channel.basicPublish("", "trade.response.q", null, bmsg);
	}
}
 
Example #11
Source File: ReceiveService.java    From seed with Apache License 2.0 6 votes vote down vote up
@RabbitListener(queues="${spring.rabbitmq.queues}", containerFactory="jadyerRabbitListenerContainerFactory")
public void receive(UserMsg userMsg, Channel channel, Message message){
    try {
        LogUtil.getLogger().info("收到消息-->[{}]", ReflectionToStringBuilder.toString(userMsg));
        //确认消费成功(第一个参数:消息编号。第二个参数:是否确认多条消息,false为确认当前消息,true为确认deliveryTag编号以前的所有消息)
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }catch(Exception e){
        LogUtil.getLogger().error("消息处理异常,消息ID={}, 消息体=[{}]", message.getMessageProperties().getCorrelationId(), JSON.toJSONString(userMsg), e);
        try {
            //拒绝当前消息,并把消息返回原队列(第三个参数:是否将消息放回队列,true表示放回队列,false表示丢弃消息)
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            //basicReject只能拒绝一条消息,而basicNack能够拒绝多条消息
            //channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        } catch (IOException e1) {
            LogUtil.getLogger().error("消息basicNack时发生异常,消息ID={}", message.getMessageProperties().getCorrelationId(), e);
        }
    }
}
 
Example #12
Source File: Worker.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.setUri("amqp://guest:[email protected]:5672");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    
    channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);//queue的持久化需要在声明时指定durable=True
    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
    //保证在接收端一个消息没有处理完时不会接收另一个消息
   channel.basicQos(1);
  //  channel.basicQos(0, 1, false); //这样RabbitMQ就会使得每个Consumer在同一个时间点最多处理一个Message。换句话说,在接收到该Consumer的ack前,他它不会将新的Message分发给它。
    
    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(TASK_QUEUE_NAME, false, consumer);
    
    while (true) {
      QueueingConsumer.Delivery delivery = consumer.nextDelivery();
      String message = new String(delivery.getBody());
      
      System.out.println(" [x] Received '" + message + "'");
      doWork(message);
      System.out.println(" [x] Done");

      channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
    }         
  }
 
Example #13
Source File: ChannelTest.java    From rabbitmq-mock with Apache License 2.0 5 votes vote down vote up
@RepeatedTest(31)
void basicConsume_concurrent_queue_access() throws IOException, TimeoutException, InterruptedException {
    try (Connection conn = new MockConnectionFactory().newConnection()) {
        try (Channel channel = conn.createChannel()) {
            String queueName = channel.queueDeclare().getQueue();

            BlockingQueue<String> messages = new LinkedBlockingQueue<>();
            channel.basicConsume("", new DefaultConsumer(channel) {
                @Override
                public void handleDelivery(String consumerTag,
                                           Envelope envelope,
                                           AMQP.BasicProperties properties,
                                           byte[] body) {
                    messages.offer(new String(body));
                }
            });

            int totalMessages = 101;
            for (int i = 1; i <= totalMessages; i++) {
                channel.basicPublish("", queueName, null, "test message".getBytes());
            }
            for (int i = 1; i <= totalMessages; i++) {
                assertThat(messages.poll(200L, TimeUnit.MILLISECONDS)).isNotNull();
            }
        }
    }
}
 
Example #14
Source File: ExtensionTest.java    From rabbitmq-mock with Apache License 2.0 5 votes vote down vote up
@Test
void non_long_message_ttl_in_publishers_is_not_used() throws IOException, TimeoutException, InterruptedException {
    try (Connection conn = new MockConnectionFactory().newConnection()) {
        try (Channel channel = conn.createChannel()) {
            channel.queueDeclare("fruits", true, false, false, null);
            AMQP.BasicProperties properties = new AMQP.BasicProperties.Builder()
                .expiration("test")
                .build();
            channel.basicPublish("", "fruits", properties, "banana".getBytes());
            TimeUnit.MILLISECONDS.sleep(100L);
            GetResponse getResponse = channel.basicGet("fruits", true);
            assertThat(getResponse).isNotNull();
        }
    }
}
 
Example #15
Source File: RabbitMQPublisherActorTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected void verifyPublishedMessage() throws Exception {
    final Channel channel = mock(Channel.class);

    // omit first channel message
    probe.expectMsgClass(ChannelMessage.class);
    final ChannelMessage channelMessage = probe.expectMsgClass(ChannelMessage.class);

    channelMessage.onChannel().apply(channel);

    final ArgumentCaptor<AMQP.BasicProperties> propertiesCaptor =
            ArgumentCaptor.forClass(AMQP.BasicProperties.class);
    final ArgumentCaptor<byte[]> bodyCaptor = ArgumentCaptor.forClass(byte[].class);

    Mockito.verify(channel, timeout(1000)).basicPublish(eq("exchange"), eq("outbound"), propertiesCaptor.capture(),
            bodyCaptor.capture());

    assertThat(propertiesCaptor.getValue().getHeaders().get("thing_id"))
            .isEqualTo(TestConstants.Things.THING_ID.toString());
    assertThat(propertiesCaptor.getValue().getHeaders().get("suffixed_thing_id")).isEqualTo(
            TestConstants.Things.THING_ID + ".some.suffix");
    assertThat(propertiesCaptor.getValue().getHeaders().get("prefixed_thing_id")).isEqualTo(
            "some.prefix." + TestConstants.Things.THING_ID);
    assertThat(propertiesCaptor.getValue().getHeaders().get("eclipse")).isEqualTo("ditto");
    assertThat(propertiesCaptor.getValue().getHeaders().get("device_id"))
            .isEqualTo(TestConstants.Things.THING_ID.toString());
}
 
Example #16
Source File: RabbitMQSink.java    From rabbitmq-flume-plugin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private Channel createRabbitMQChannel() throws EventDeliveryException {
    try {
        return connection.createChannel();
    } catch (IOException ex) {
        closeRabbitMQConnection();
        throw new EventDeliveryException(ex.toString());
    }
}
 
Example #17
Source File: ConnectionHandler.java    From lyra with Apache License 2.0 5 votes vote down vote up
/** Gets a recovery channel, creating one if necessary. */
@Override
Channel getRecoveryChannel() throws IOException {
  if (recoveryChannel == null || !recoveryChannel.isOpen())
    recoveryChannel = delegate.createChannel(RECOVERY_CHANNEL_NUM);
  return recoveryChannel;
}
 
Example #18
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 #19
Source File: ExtensionTest.java    From rabbitmq-mock with Apache License 2.0 5 votes vote down vote up
@Test
void message_ttl_for_queue_keeps_messages_while_expiration_not_reached() throws IOException, TimeoutException {
    try (Connection conn = new MockConnectionFactory().newConnection()) {
        try (Channel channel = conn.createChannel()) {
            queue("fruits").withMessageTtl(700).declare(channel);
            channel.basicPublish("", "fruits", null, "banana".getBytes());
            GetResponse getResponse = channel.basicGet("fruits", true);
            assertThat(getResponse).isNotNull();
        }
    }
}
 
Example #20
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 #21
Source File: RabbitmqIT.java    From uavstack with Apache License 2.0 5 votes vote down vote up
private void doCap(int rc, Channel channel, Consumer consumer, Method method, Throwable e) {

            if (null == targetServer) {
                Map<String, Object> conn = channel.getConnection().getServerProperties();
                String cluster_name = (null == conn.get("cluster_name")) ? "unknown"
                        : conn.get("cluster_name").toString();
                String version = (null == conn.get("version")) ? "unknown" : conn.get("version").toString();
                targetServer = cluster_name + "@" + version;
            }

            Map<String, Object> params = new HashMap<String, Object>();

            params.put(CaptureConstants.INFO_CLIENT_TARGETSERVER, targetServer);
            params.put(CaptureConstants.INFO_CLIENT_RESPONSECODE, rc);

            if (logger.isDebugable()) {
                logger.debug("Invoke END: rc=" + rc + "," + targetServer, null);
            }

            UAVServer.instance().runMonitorCaptureOnServerCapPoint(CaptureConstants.CAPPOINT_APP_CLIENT,
                    Monitor.CapturePhase.DOCAP, params);

            if (method.getName().equals("handleDelivery")) {
                params.put(CaptureConstants.INFO_APPSERVER_CONNECTOR_REQUEST_URL, url);
                params.put(CaptureConstants.INFO_CLIENT_APPID, applicationId);
                params.put(InvokeChainConstants.CLIENT_IT_CLASS, consumer.getClass().getName());
                // 调用链只关心一个方法
                params.put(InvokeChainConstants.CLIENT_IT_METHOD, "handleDelivery");
                params.put(CaptureConstants.INFO_CLIENT_RESPONSECODE, rc);
                if (rc == -1) {
                    params.put(CaptureConstants.INFO_CLIENT_RESPONSESTATE, e.toString());
                }

                // invoke chain
                UAVServer.instance().runSupporter("com.creditease.uav.apm.supporters.InvokeChainSupporter", "runCap",
                        InvokeChainConstants.CHAIN_APP_SERVICE, InvokeChainConstants.CapturePhase.DOCAP, params,
                        RabbitmqConsumerAdapter.class, null);
            }
        }
 
Example #22
Source File: AMQPObservableQueueTest.java    From conductor with Apache License 2.0 5 votes vote down vote up
Channel mockChannelForQueue(Channel channel, boolean isWorking, boolean exists, String name,
		List<GetResponse> queue) throws IOException {
	// queueDeclarePassive
	final AMQImpl.Queue.DeclareOk queueDeclareOK = new AMQImpl.Queue.DeclareOk(name, queue.size(), 1);
	if (exists) {
		Mockito.when(channel.queueDeclarePassive(eq(name))).thenReturn(queueDeclareOK);
	} else {
		Mockito.when(channel.queueDeclarePassive(eq(name))).thenThrow(new IOException("Queue " + name + " exists"));
	}
	// queueDeclare
	OngoingStubbing<AMQP.Queue.DeclareOk> declareOkOngoingStubbing = Mockito.when(channel.queueDeclare(eq(name),
			Mockito.anyBoolean(), Mockito.anyBoolean(), Mockito.anyBoolean(), Mockito.anyMap()))
			.thenReturn(queueDeclareOK);
	if (!isWorking) {
		declareOkOngoingStubbing.thenThrow(new IOException("Cannot declare queue " + name),
				new RuntimeException("Not working"));
	}
	// messageCount
	Mockito.when(channel.messageCount(eq(name))).thenReturn(1l * queue.size());
	// basicGet
	OngoingStubbing<String> getResponseOngoingStubbing = Mockito
			.when(channel.basicConsume(eq(name), Mockito.anyBoolean(), (Consumer) Mockito.any(Consumer.class))).thenAnswer(new ReturnsElementsOf(queue));
	if (!isWorking) {
		getResponseOngoingStubbing.thenThrow(new IOException("Not working"), new RuntimeException("Not working"));
	}
	// basicPublish
	if (isWorking) {
		Mockito.doNothing().when(channel).basicPublish(eq(StringUtils.EMPTY), eq(name),
				Mockito.any(AMQP.BasicProperties.class), Mockito.any(byte[].class));
	} else {
		Mockito.doThrow(new IOException("Not working")).when(channel).basicPublish(eq(StringUtils.EMPTY), eq(name),
				Mockito.any(AMQP.BasicProperties.class), Mockito.any(byte[].class));
	}
	return channel;
}
 
Example #23
Source File: ChannelTest.java    From rabbitmq-mock with Apache License 2.0 5 votes vote down vote up
@Test
void commit_without_select_throws() throws IOException, TimeoutException {
    try (Connection conn = new MockConnectionFactory().newConnection()) {
        try (Channel channel = conn.createChannel()) {
            assertThatExceptionOfType(IllegalStateException.class)
                .isThrownBy(() -> channel.txCommit())
                .withMessage("No started transaction (make sure you called txSelect before txCommit");
        }
    }
}
 
Example #24
Source File: BindingsRestApiTest.java    From ballerina-message-broker with Apache License 2.0 5 votes vote down vote up
@Test(dataProvider = "bindingData")
public void testCreateBindingWithFilters(String queueName, String bindingPattern)
        throws IOException, TimeoutException {
    Channel channel = amqpConnection.createChannel();
    channel.queueDeclare(queueName, false, false, false, new HashMap<>());

    String exchangeName = "amq.topic";
    String filter = "CorrelationId = 'testId123'";
    HttpPost httpPost = new HttpPost(apiBasePath + "/queues/" + queueName + "/bindings");
    ClientHelper.setAuthHeader(httpPost, username, password);
    BindingCreateRequest createRequest = new BindingCreateRequest().bindingPattern(bindingPattern)
                                                                   .exchangeName(exchangeName)
                                                                   .filterExpression(filter);

    String payloadString = objectMapper.writeValueAsString(createRequest);
    StringEntity stringEntity = new StringEntity(payloadString, ContentType.APPLICATION_JSON);
    httpPost.setEntity(stringEntity);

    CloseableHttpResponse response = client.execute(httpPost);

    Assert.assertEquals(response.getStatusLine().getStatusCode(), HttpStatus.SC_CREATED);

    BindingCreateResponse responseMessage = HttpClientHelper.getResponseMessage(response,
                                                                                BindingCreateResponse.class);

    Assert.assertEquals(responseMessage.getMessage(), "Binding created.");

    HashMap<String, Object> arguments = new HashMap<>();
    arguments.put(Binding.JMS_SELECTOR_ARGUMENT.toString(), filter);
    channel.queueUnbind(queueName, exchangeName, bindingPattern, arguments);
    channel.close();
}
 
Example #25
Source File: ReactorRabbitMQChannelPool.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Override
public void destroyObject(PooledObject<Channel> pooledObject) throws Exception {
    Channel channel = pooledObject.getObject();
    if (channel.isOpen()) {
        channel.close();
    }
}
 
Example #26
Source File: RabbitMqIO.java    From beam with Apache License 2.0 5 votes vote down vote up
@Setup
public void setup() throws Exception {
  connectionHandler = new ConnectionHandler(spec.uri());
  connectionHandler.start();

  Channel channel = connectionHandler.getChannel();

  if (spec.exchange() != null && spec.exchangeDeclare()) {
    channel.exchangeDeclare(spec.exchange(), spec.exchangeType());
  }
  if (spec.queue() != null && spec.queueDeclare()) {
    channel.queueDeclare(spec.queue(), true, false, false, null);
  }
}
 
Example #27
Source File: RabbitMQMessagingService.java    From elasticactors with Apache License 2.0 5 votes vote down vote up
@Override
public void addChannelListener(final Channel channel,final ChannelListener channelListener) {
    Set<ChannelListener> listeners = this.channelListenerRegistry.get(channel);
    if(listeners == null) {
        listeners = Collections.newSetFromMap(new ConcurrentHashMap<>());
        if(this.channelListenerRegistry.putIfAbsent(channel,listeners) != null) {
            // was already created
            listeners = this.channelListenerRegistry.get(channel);
        }
    }
    listeners.add(channelListener);
}
 
Example #28
Source File: RabbitMqClientDemo.java    From xian with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUsername(XianConfig.get("rabbitmqUserName"));
    factory.setPassword(XianConfig.get("rabbitmqPwd"));
    factory.setVirtualHost("/");
    factory.setHost("production-internet-mq.apaycloud.com");
    factory.setPort(5672);
    Connection conn = factory.newConnection();
    Channel channel = conn.createChannel();


    String exchangeName = "yy-exchange";
    String routingKey = "yy-routingKey";
    String queueName = "yy-queueName";

    channel.exchangeDeclare(exchangeName, "direct", true);
    channel.queueDeclare(queueName, true, false, false, null);
    channel.queueBind(queueName, exchangeName, routingKey);

    byte[] messageBodyBytes = "Hello, world2!".getBytes();
    channel.basicPublish(exchangeName, routingKey, null, messageBodyBytes);


    Thread.sleep(1000 * 60);

    channel.close();
    conn.close();
}
 
Example #29
Source File: RabbitTemplateExtend.java    From summerframework with Apache License 2.0 5 votes vote down vote up
@Override
public void doSend(Channel channel, String exchange, String routingKey, Message message, boolean mandatory,
    CorrelationData correlationData) throws Exception {

    try {
        PublishTraceLog traceLog =
            new PublishTraceLog(this, channel, exchange, routingKey, message, mandatory, correlationData);
        traceLog.log();
    } catch (Throwable e) {
        LOGGER.warn(e.getMessage(), e);
    }
    try {
        Map<String, Long> delayParam = DELAY_QUEUE_CONTENT.get();
        if (delayParam != null && delayParam.size() == 1) {
            String sourceQueue = delayParam.keySet().iterator().next();
            Long interval = delayParam.get(sourceQueue);
            if (interval > 0) {
                String delayQueue = sourceQueue + DeadLetterConstant.DEFAULT_DELAY_QUEUENAME_PREFIX;
                String delayRouteKey = routingKey + DeadLetterConstant.DEFAULT_DELAY_QUEUENAME_PREFIX;
                deadLetterQueueCreator.createDeadLetterQueue(exchange, routingKey, delayRouteKey, sourceQueue,
                    delayQueue, interval);
                String delayExchange = DeadLetterConstant.DEFAULT_DEADLETTEREXCHANGE_NAME;
                super.doSend(channel, delayExchange, delayRouteKey, message, mandatory, correlationData);
                return;
            }
        }
        super.doSend(channel, exchange, routingKey, message, mandatory, correlationData);
    } finally {
        DELAY_QUEUE_CONTENT.remove();
    }

}
 
Example #30
Source File: MessagePublisherFactory.java    From Insights with Apache License 2.0 5 votes vote down vote up
public static void publish(String routingKey, Object data) throws Exception{
	ConnectionFactory factory = new ConnectionFactory();
       MessageQueueDataModel messageQueueConfig = ApplicationConfigProvider.getInstance().getMessageQueue();
	factory.setHost(messageQueueConfig.getHost());
       factory.setUsername(messageQueueConfig.getUser());
	factory.setPassword(messageQueueConfig.getPassword());
       Connection connection = factory.newConnection();
       Channel channel = connection.createChannel();
       channel.exchangeDeclare(MessageConstants.EXCHANGE_NAME, MessageConstants.EXCHANGE_TYPE);
       
       String message = new GsonBuilder().disableHtmlEscaping().create().toJson(data);
       channel.basicPublish(MessageConstants.EXCHANGE_NAME, routingKey, null, message.getBytes());
       connection.close();
}