Search in sources :

Example 1 with Envelope

use of com.rabbitmq.client.Envelope in project uavstack by uavorg.

the class DoTestRabbitmqProxy method main.

public static void main(String[] args) {
    ConsoleLogger cl = new ConsoleLogger("test");
    cl.setDebugable(true);
    UAVServer.instance().setLog(cl);
    UAVServer.instance().putServerInfo(CaptureConstants.INFO_APPSERVER_VENDOR, ServerVendor.TOMCAT);
    RabbitmqHookProxy p = new RabbitmqHookProxy("test", Collections.emptyMap());
    p.doInstallDProxy(null, "testApp");
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUsername("guest");
    factory.setPassword("guest");
    factory.setHost("127.0.0.1");
    factory.setPort(5672);
    try {
        conn = factory.newConnection();
        channel = conn.createChannel();
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        channel.queueDeclare("aaa", false, false, false, null);
        new Thread(new Runnable() {

            @Override
            public void run() {
                String message = "Hello World!";
                while (true) {
                    try {
                        channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8"));
                        // System.out.println(" [x] Sent '" + message + "'");
                        channel.basicPublish("", "aaa", null, "aaame".getBytes("UTF-8"));
                        // System.out.println(" [x] Sent 'aaame'");
                        Thread.sleep(1000);
                    } catch (UnsupportedEncodingException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }).start();
        Connection connection = factory.newConnection();
        Channel recvchannel = connection.createChannel();
        recvchannel.queueDeclare(QUEUE_NAME, false, false, false, null);
        recvchannel.queueDeclare("aaa", false, false, false, null);
        Consumer consumer = new DefaultConsumer(recvchannel) {

            @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 + "'1");
            }
        };
        recvchannel.basicConsume(QUEUE_NAME, true, consumer);
        String consumerTag = recvchannel.basicConsume("aaa", true, consumer);
        try {
            Thread.sleep(50000);
            recvchannel.basicCancel(consumerTag);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (TimeoutException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
Also used : DefaultConsumer(com.rabbitmq.client.DefaultConsumer) Channel(com.rabbitmq.client.Channel) Connection(com.rabbitmq.client.Connection) RabbitmqHookProxy(com.creditease.uav.hook.rabbitmq.RabbitmqHookProxy) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) Envelope(com.rabbitmq.client.Envelope) ConnectionFactory(com.rabbitmq.client.ConnectionFactory) DefaultConsumer(com.rabbitmq.client.DefaultConsumer) Consumer(com.rabbitmq.client.Consumer) ConsoleLogger(com.creditease.monitor.log.ConsoleLogger) TimeoutException(java.util.concurrent.TimeoutException)

Example 2 with Envelope

use of com.rabbitmq.client.Envelope in project rabbitmq-jms-client by rabbitmq.

the class SimpleServerConnectionIT method testRabbitConnection.

@Test
public void testRabbitConnection() throws Exception {
    final Channel channel = this.getConnection().createChannel();
    try {
        channel.exchangeDeclare("exchangeName", "direct", true);
        String queueName = channel.queueDeclare().getQueue();
        channel.queueBind(queueName, "exchangeName", "routingKey");
        byte[] messageBodyBytes = "Hello, world!".getBytes();
        channel.basicPublish("exchangeName", "routingKey", null, messageBodyBytes);
        boolean autoAck = false;
        channel.basicConsume(queueName, autoAck, "myConsumerTag", new DefaultConsumer(channel) {

            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                long deliveryTag = envelope.getDeliveryTag();
                // (process the message components here
                // ...)
                System.out.println("Received Message:" + new String(body));
                channel.basicAck(deliveryTag, false);
            }
        });
        Thread.sleep(1000);
    } finally {
        channel.exchangeDelete("exchangeName");
        channel.close();
    }
}
Also used : DefaultConsumer(com.rabbitmq.client.DefaultConsumer) AMQP(com.rabbitmq.client.AMQP) Channel(com.rabbitmq.client.Channel) IOException(java.io.IOException) Envelope(com.rabbitmq.client.Envelope) Test(org.junit.jupiter.api.Test)

Example 3 with Envelope

use of com.rabbitmq.client.Envelope in project rabbitmq-queue-management by gessnerfl.

the class MessageMapperTest method shouldMapAmqpBasicProperties.

@Test
public void shouldMapAmqpBasicProperties() {
    String contentType = "contentType";
    String contentEncoding = "contentEncoding";
    String headerKey = "headerKey";
    String headerValue = "headerValue";
    Map<String, Object> headers = new HashMap<>();
    headers.put(headerKey, headerValue);
    Integer deliveryMode = 12;
    Integer priority = 13;
    String correlationId = "correlationId";
    String replyTo = "replyTo";
    String expiration = "expiration";
    String messageId = "messageId";
    Date timestamp = new Date();
    String type = "type";
    String userId = "userId";
    String appId = "appId";
    String clusterId = "clusterId";
    AMQP.BasicProperties basicProperties = mock(AMQP.BasicProperties.class);
    when(basicProperties.getContentType()).thenReturn(contentType);
    when(basicProperties.getContentEncoding()).thenReturn(contentEncoding);
    when(basicProperties.getHeaders()).thenReturn(headers);
    when(basicProperties.getDeliveryMode()).thenReturn(deliveryMode);
    when(basicProperties.getPriority()).thenReturn(priority);
    when(basicProperties.getCorrelationId()).thenReturn(correlationId);
    when(basicProperties.getReplyTo()).thenReturn(replyTo);
    when(basicProperties.getExpiration()).thenReturn(expiration);
    when(basicProperties.getMessageId()).thenReturn(messageId);
    when(basicProperties.getTimestamp()).thenReturn(timestamp);
    when(basicProperties.getType()).thenReturn(type);
    when(basicProperties.getUserId()).thenReturn(userId);
    when(basicProperties.getAppId()).thenReturn(appId);
    when(basicProperties.getClusterId()).thenReturn(clusterId);
    Envelope envelope = mock(Envelope.class);
    GetResponse getResponse = mockResponse(envelope, basicProperties);
    Message result = sut.map(getResponse);
    BasicProperties basicPropertiesOfResult = result.getProperties();
    assertNotNull(basicPropertiesOfResult);
    assertEquals(contentType, basicPropertiesOfResult.getContentType());
    assertEquals(contentEncoding, basicPropertiesOfResult.getContentEncoding());
    assertThat(basicPropertiesOfResult.getHeaders().keySet(), Matchers.hasSize(1));
    assertThat(basicPropertiesOfResult.getHeaders(), Matchers.hasKey(headerKey));
    assertEquals(headerValue, basicPropertiesOfResult.getHeaders().get(headerKey));
    assertEquals(deliveryMode, basicPropertiesOfResult.getDeliveryMode());
    assertEquals(priority, basicPropertiesOfResult.getPriority());
    assertEquals(correlationId, basicPropertiesOfResult.getCorrelationId());
    assertEquals(replyTo, basicPropertiesOfResult.getReplyTo());
    assertEquals(expiration, basicPropertiesOfResult.getExpiration());
    assertEquals(messageId, basicPropertiesOfResult.getMessageId());
    assertEquals(timestamp, basicPropertiesOfResult.getTimestamp());
    assertEquals(type, basicPropertiesOfResult.getType());
    assertEquals(userId, basicPropertiesOfResult.getUserId());
    assertEquals(appId, basicPropertiesOfResult.getAppId());
    assertEquals(clusterId, basicPropertiesOfResult.getClusterId());
}
Also used : Message(de.gessnerfl.rabbitmq.queue.management.model.Message) AMQP(com.rabbitmq.client.AMQP) BasicProperties(de.gessnerfl.rabbitmq.queue.management.model.BasicProperties) LongString(com.rabbitmq.client.LongString) Envelope(com.rabbitmq.client.Envelope) GetResponse(com.rabbitmq.client.GetResponse) Test(org.junit.Test)

Example 4 with Envelope

use of com.rabbitmq.client.Envelope in project spring_boot by hryou0922.

the class RpcClient method execute.

public static void execute(String host, String userName, String password, String message) {
    // 配置连接工厂
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(host);
    // 需要在管理后台增加一个hry帐号
    factory.setUsername(userName);
    factory.setPassword(password);
    Connection connection = null;
    Channel channel = null;
    try {
        // 建立TCP连接
        connection = factory.newConnection();
        // 在TCP连接的基础上创建通道
        channel = connection.createChannel();
        // 定义临时队列,并返回生成的队列名称
        String replyQueueName = channel.queueDeclare().getQueue();
        // 唯一标志本次请求
        String corrId = UUID.randomUUID().toString();
        // 生成发送消息的属性
        AMQP.BasicProperties props = new AMQP.BasicProperties.Builder().correlationId(// 唯一标志本次请求
        corrId).replyTo(// 设置回调队列
        replyQueueName).build();
        // 发送消息,发送到默认交换机
        channel.basicPublish("", RPC_QUEUE_NAME, props, message.getBytes("UTF-8"));
        System.out.println(" [RpcClient] Requesting : " + message);
        // 阻塞队列,用于存储回调结果
        final BlockingQueue<String> response = new ArrayBlockingQueue<String>(1);
        // 定义消息的回退方法
        channel.basicConsume(replyQueueName, true, new DefaultConsumer(channel) {

            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                if (properties.getCorrelationId().equals(corrId)) {
                    response.offer(new String(body, "UTF-8"));
                }
            }
        });
        // 获取回调的结果
        String result = response.take();
        System.out.println(" [RpcClient] Result:'" + result + "'");
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            // 空值判断,为了代码简洁略
            channel.close();
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Also used : DefaultConsumer(com.rabbitmq.client.DefaultConsumer) Channel(com.rabbitmq.client.Channel) Connection(com.rabbitmq.client.Connection) IOException(java.io.IOException) Envelope(com.rabbitmq.client.Envelope) TimeoutException(java.util.concurrent.TimeoutException) IOException(java.io.IOException) ConnectionFactory(com.rabbitmq.client.ConnectionFactory) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) AMQP(com.rabbitmq.client.AMQP)

Example 5 with Envelope

use of com.rabbitmq.client.Envelope in project spring-integration by spring-projects.

the class AmqpMessageSourceTests method testNackOrRequeue.

private void testNackOrRequeue(boolean requeue) throws IOException, TimeoutException {
    Channel channel = mock(Channel.class);
    willReturn(true).given(channel).isOpen();
    Envelope envelope = new Envelope(123L, false, "ex", "rk");
    BasicProperties props = new BasicProperties.Builder().build();
    GetResponse getResponse = new GetResponse(envelope, props, "bar".getBytes(), 0);
    willReturn(getResponse).given(channel).basicGet("foo", false);
    Connection connection = mock(Connection.class);
    willReturn(true).given(connection).isOpen();
    willReturn(channel).given(connection).createChannel();
    ConnectionFactory connectionFactory = mock(ConnectionFactory.class);
    willReturn(connection).given(connectionFactory).newConnection((ExecutorService) isNull(), anyString());
    CachingConnectionFactory ccf = new CachingConnectionFactory(connectionFactory);
    AmqpMessageSource source = new AmqpMessageSource(ccf, "foo");
    Message<?> received = source.receive();
    verify(connection).createChannel();
    StaticMessageHeaderAccessor.getAcknowledgmentCallback(received).acknowledge(requeue ? Status.REQUEUE : Status.REJECT);
    verify(channel).basicReject(123L, requeue);
    verify(connection).createChannel();
    ccf.destroy();
    verify(channel).close();
    verify(connection).close(30000);
}
Also used : CachingConnectionFactory(org.springframework.amqp.rabbit.connection.CachingConnectionFactory) ConnectionFactory(com.rabbitmq.client.ConnectionFactory) BasicProperties(com.rabbitmq.client.AMQP.BasicProperties) Channel(com.rabbitmq.client.Channel) Connection(com.rabbitmq.client.Connection) CachingConnectionFactory(org.springframework.amqp.rabbit.connection.CachingConnectionFactory) Envelope(com.rabbitmq.client.Envelope) GetResponse(com.rabbitmq.client.GetResponse)

Aggregations

Envelope (com.rabbitmq.client.Envelope)31 DefaultConsumer (com.rabbitmq.client.DefaultConsumer)20 AMQP (com.rabbitmq.client.AMQP)18 IOException (java.io.IOException)17 Channel (com.rabbitmq.client.Channel)16 Test (org.junit.Test)12 Connection (com.rabbitmq.client.Connection)11 ConnectionFactory (com.rabbitmq.client.ConnectionFactory)10 TimeoutException (java.util.concurrent.TimeoutException)9 GetResponse (com.rabbitmq.client.GetResponse)8 BasicProperties (com.rabbitmq.client.AMQP.BasicProperties)6 LongString (com.rabbitmq.client.LongString)5 Consumer (com.rabbitmq.client.Consumer)4 BasicProperties (de.gessnerfl.rabbitmq.queue.management.model.BasicProperties)4 Message (de.gessnerfl.rabbitmq.queue.management.model.Message)4 KeyManagementException (java.security.KeyManagementException)3 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)3 UUID (java.util.UUID)3 CountDownLatch (java.util.concurrent.CountDownLatch)3 Path (javax.ws.rs.Path)3