简单入门Demo -消息生产 与消费

  • ConnectionFactory:获取连接工厂
  • Connection:一个连接
  • Channel:数据通信信道,可发送和接收信息
  • Queue:具体的消息存储队列
  • Producer& Consumer 生产和消费者
public class Procuder {
    public static void main(String[] args) throws IOException, TimeoutException {
        //创建一个ConnectionFactory
        ConnectionFactory connectionFactory =new ConnectionFactory();
        connectionFactory.setHost("***");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("***");
        connectionFactory.setPassword("***");
        connectionFactory.setVirtualHost("/");
        //通过连接工厂创建连接
        Connection connections = connectionFactory.newConnection();
        //通过Connection创建一个Channel
        Channel channel =connections.createChannel();
        //通过Channel 发送数据
        String msg=  "Hellow RabbitMQ";
        for(int i=0;i<5;i++){
            channel.basicPublish("","test001",null,msg.getBytes());
        }
    }
}
public class Consumer {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        //创建一个ConnectionFactory
        ConnectionFactory connectionFactory =new ConnectionFactory();
        connectionFactory.setHost("****");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("***");
        connectionFactory.setPassword("***");
        connectionFactory.setVirtualHost("/");
        //通过连接工厂创建连接
        Connection connections = connectionFactory.newConnection();
        //通过Connection创建一个Channel
        Channel channel =connections.createChannel();
        String quename="test001";
        //申明一个队列
        channel.queueDeclare(quename,true,false,false,null);
        //创建消费者
        QueueingConsumer queueingConsumer =new QueueingConsumer(channel);
        //设置channel
        channel.basicConsume(quename,true,queueingConsumer);

        while(true){
            //获取消息
            QueueingConsumer.Delivery deliver = queueingConsumer.nextDelivery();
            String msg =new String(deliver.getBody());
            System.out.println("消费端:" +msg);
            Envelope envelope =deliver.getEnvelope();
        }


    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值