rabbitmq 学习-3-初试1

本例是一个简单的异步发送消息实例
1,发送端
@Test(groups = { "sunjun" })
public class RabbitmqTest {
    private static Connection connection;
    static {
        ConnectionParameters params = new ConnectionParameters();
        ConnectionFactory factory = new ConnectionFactory(params);
        try {
            connection = factory.newConnection("192.168.18.21",
                    AMQP.PROTOCOL.PORT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void testSend() {
        try {
            Channel channel = connection.createChannel();
            System.out.println(channel.toString());
            Assert.assertNotNull(channel);
            byte[] messageBodyBytes = "hello world".getBytes();
            channel.basicPublish("exchangeName", "routingKey",
                    MessageProperties.PERSISTENT_TEXT_PLAIN, messageBodyBytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
2,接收端
@Test(groups = { "sunjun" })
public class RabbitmqTestB {
    private static Connection connection;
    static {
        ConnectionParameters params = new ConnectionParameters();
        ConnectionFactory factory = new ConnectionFactory(params);
        try {
            connection = factory.newConnection("localhost", AMQP.PROTOCOL.PORT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void testReceive() {
        try {
            Channel channel = connection.createChannel();
            System.out.println(channel.toString());
            Assert.assertNotNull(channel);
            channel.exchangeDeclare("exchangeName", "direct");
            channel.queueDeclare("queueName");
            channel.queueBind("queueName", "exchangeName", "routingKey");
            boolean noAck = false;
            GetResponse response = channel.basicGet("queueName", true);
            if (response == null) {
                System.out.println("No message retrieved.");
            } else {
                AMQP.BasicProperties props = response.getProps();
                byte[] body = response.getBody();
                System.out.println(new String(body));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
先执行下发送端,再执行下接收端,输出:hello world
ok

 

本文摘自:http://sunjun041640.blog.163.com/blog/#m=0&t=1&c=fks_087069084081083065085095084095086083087065082094085065

转载于:https://www.cnblogs.com/iwteih/archive/2010/10/19/1855503.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值