栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 前沿技术 > 大数据 > 大数据系统

Rabittmq 发布 接收消息

Rabittmq 发布 接收消息

当然首先第一步就是连接上 确保自己端口开放 (5672(消息端口)和 15672(web界面端口))
我这个是虚拟机中安装好的
导入依赖


      com.rabbitmq
      amqp-client
      5.4.3
 

创建连接工具类

package com.Utils;

import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;


public class ConnectionUtils {
    public static Connection  getConnection() throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.127.132");
        factory.setPort(5672);
        factory.setUsername("guest");
        factory.setPassword("guest");
        factory.setVirtualHost("/");

        return factory.newConnection();
    }
}

最普通的模式

先试着发送消息

package com.han;

import com.Utils.ConnectionUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import org.junit.Test;

public class publish {

    public static void main(String[] args) throws Exception {
        Connection connection = ConnectionUtils.getConnection();

        Channel channel = connection.createChannel();
        
        channel.queueDeclare("queue7" ,false,false,false,null);

        String message = "卧槽了";
        channel.basicPublish("" ,"queue7" ,null ,message.getBytes());

        System.out.println("消息发送成功");

        channel.close();
        connection.close();





    }
}

然后接收消息

package com.han;

import com.Utils.ConnectionUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.*;

import java.io.IOException;

public class ReceiveMsg {
    public static void main(String[] args) throws Exception{
        Connection connection = ConnectionUtils.getConnection();
        Channel channel = connection.createChannel();

        Consumer consumer  = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                //body就是从队列中获取的数据
                String msg = new String(body);
                System.out.println("接收到数据:"+msg);
            }
        };

        channel.basicConsume("queue7",true,consumer);

    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/758038.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号