用Rabbit MQ 实现一对一聊天简单案例分享

实现原理:

使用rabbitmq 的 Routing路由模式,定义两个queue队列和routing key,两个class类,分别创建两个线程实现发送消息和监听接收消息。
直接上代码:
Class A:

package com.fs.rabbit;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.Scanner;
import java.util.concurrent.TimeoutException;

public class liaotian1 {
    public static void main(String[] args) throws IOException, TimeoutException {
       //从工具类获取一个连接;工具类在文章下面,一个简单的封装;
        final Connection connection = Utils.getConnection();
        //线程 t1 用来生产 发送消息:
        final Thread t1 =new Thread(new Runnable() {
            public void run() {
                Channel channel = null;
                try {
                   channel = connection.createChannel();
                  //声明“交换机” 和模式:direct  
                  channel.exchangeDeclare("direct_exchange","direct");
                  
                  //声明,绑定队列和routing key              
                  channel.queueDeclare("direct_queue1",true,false,false,null);                  channel.queueBind("direct_queue1","direct_exchange","1");
                }catch (Exception e){
                    e.printStackTrace();
                }
                while (true){
                    Scanner scanner =new Scanner(System.in);
                    System.out.println("请输入消息");
                    String msg = scanner.nextLine();
                    try {
                        channel.basicPublish("direct_exchange","1",null,msg.getBytes());

                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    System.out.println("A发出的消息:"+msg);
                }
            }
        });
        //线程2 监听消息;
        Thread t2 =new Thread(new Runnable() {
            public void run() {
                Channel channel = null;
                try {
                    channel=connection.createChannel();
                   channel.exchangeDeclare("direct_exchange","direct");
                    channel.queueDeclare("direct_queue2", true, false, false, null);
                    channel.queueBind("direct_queue2","direct_exchange","2");

                    DefaultConsumer defaultConsumer = new DefaultConsumer(channel) {
                        /***
                         * @param consumerTag   消息者标签,在channel.basicConsume时候可以指定
                         * @param envelope      消息包的内容,可从中获取消息id,消息routingkey,交换机,消息和重传标志(收到消息失败后是否需要重新发送)
                         * @param properties    属性信息
                         * @param body           消息
                         * @throws IOException
                         */
                        @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("A接收的消息:" + message);
                        }
                    };
                    channel.basicConsume("direct_queue2",true,defaultConsumer);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
        t1.start();
        t2.start();
    }
}

复制一个相同的class b ,修改queue 队列 名称和routing key

package com.fs.rabbit;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.Scanner;
import java.util.concurrent.TimeoutException;

public class liaotian2 {
    public static void main(String[] args) throws IOException, TimeoutException {
        final Connection connection = Utils.getConnection();
        final Thread t1 =new Thread(new Runnable() {
            public void run() {
                Channel channel = null;
                try {
                   channel = connection.createChannel();
                    channel.exchangeDeclare("direct_exchange","direct");
                    channel.queueDeclare("direct_queue2",true,false,false,null);
                    channel.queueBind("direct_queue2","direct_exchange","2");
                }catch (Exception e){
                    e.printStackTrace();
                }
                while (true){
                    Scanner scanner =new Scanner(System.in);
                    System.out.println("请输入消息");
                    String msg = scanner.nextLine();
                    try {
                        channel.basicPublish("direct_exchange","2",null,msg.getBytes());

                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    System.out.println("B发出的消息:"+msg);
                }
            }
        });
        Thread t2 =new Thread(new Runnable() {
            public void run() {
                Channel channel = null;
                try {
                    channel=connection.createChannel();
                    channel.exchangeDeclare("direct_exchange","direct");
                    channel.queueDeclare("direct_queue1", true, false, false, null);
                    channel.queueBind("direct_queue1","direct_exchange","1");

                    DefaultConsumer defaultConsumer = new DefaultConsumer(channel) {
                        @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("B接收的消息:" + message);
                        }
                    };
                    channel.basicConsume("direct_queue1",true,defaultConsumer);

                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
        t1.start();
        t2.start();
    }
}

下面这个是工具类,根据自己本机实际情况修改:

public class Utils {
    /***
     * 创建连接对象
     * @return
     * @throws IOException
     * @throws TimeoutException
     */
    public static Connection getConnection() throws IOException,TimeoutException{
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("localhost");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/fs");
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        Connection connection = connectionFactory.newConnection();
        return connection;
    }
}

分别启动两个 类;在控制台输入消息发送,查看另一个控制台是否收到;
A:
在这里插入图片描述
B:
在这里插入图片描述就这样。

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值