RabbitMQ六种工作模式01

01: Work Queue工作队列模式

 

 

 

 

 

 

 

 

//接口所有的属性都是静态常量属性
public interface RabbitContent {

    //队列
    String QEUEU_HELLO = "hello";
    String QUEUE_WORKING ="working";
    String QUEUE_BAIDU ="baidu";
    String QUEUE_SINA ="sina";


    //交换机
    String CHANGE_WEATHER="weather";
    String CHANGE_ROUTING="weather_routing";
    String CHANGE_TOPIC="weather_topic";
}

 SMS:

public class SMS implements Serializable {
    private static final long serialVersionUID = 3185271845751784313L;
    private String name;
    private String phone;
    private String content;
//+  get/set  无参带参构造方法
}
WorkProducer:
package cpm.pb.working;


import com.google.gson.Gson;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import cpm.pb.test.utils.RabbitContent;
import cpm.pb.test.utils.RabbitUtils;

import java.io.IOException;

public class WorkProducer {

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

        channel.queueDeclare(RabbitContent.QUEUE_WORKING, false, false, false, null);

        //在这里面我们共发送200条消息
        for(int i = 1; i <=200; i++) {
            SMS  sms = new SMS("admin"+i, "12345678976"+i, "购票成功");
            //把对象转换成字符串
            //JSONlib   fastJson   Jankson, gson
            String s = new Gson().toJson(sms);
            //System.out.println(s);
            //发送消息
            channel.basicPublish("", RabbitContent.QUEUE_WORKING, null, s.getBytes());
        }
        System.out.println("消息发送成功...");
        channel.close();
        connection.close();
    }
}

运行:

 消费者1:

SMSOrder1:

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

        channel.queueDeclare(RabbitContent.QUEUE_WORKING, false, false, false, null);

        channel.basicQos(1);    //排队


        channel.basicConsume(RabbitContent.QUEUE_WORKING, false, new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("SMSOrder1收到消息: " + new String(body));

                //签收
                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        });

    }
}

赋值三个  三个消费者  SMSOrder1:  SMSOrder2: SMSOrder3

分别运行:

 让每个消费者  做延迟:

 try {
                    Thread.sleep(20);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                channel.basicAck(envelope.getDeliveryTag(), false);

每个消费者会消费不同的消息:

发布(publish)/订阅(Subscribe)模式:

 

 

 

 

 

Weather.Java:

/**
 * 气象局[供应商和应用商操作]
 */
public class Weather {
    public static void main(String[] args) throws Exception {
        //这里我们不创建队列
        //只创建交换机
        Connection connection = RabbitUtils.getConnection();
        Channel channel = connection.createChannel();

        //创建Fanout类型的交换机
        channel.exchangeDeclare(RabbitContent.CHANGE_WEATHER, BuiltinExchangeType.FANOUT,false,false,false, null);

        //发送消息我们把数据送入先关的交换机
        channel.basicPublish(RabbitContent.CHANGE_WEATHER, "",null, "北京38°晴转阴".getBytes());

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

 Baidu.java:

public class Baidu {
    public static void main(String[] args) throws Exception {
        //这里我们不创建队列
        //只创建交换机
        Connection connection = RabbitUtils.getConnection();
        Channel channel = connection.createChannel();

        channel.queueDeclare(RabbitContent.QUEUE_BAIDU,false,false, false, null);

        //交换机和队列进行绑定*****************
        channel.queueBind(RabbitContent.QUEUE_BAIDU, RabbitContent.CHANGE_WEATHER,"");
        channel.basicConsume(RabbitContent.QUEUE_BAIDU, false, new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("百度收到消息:" + new String(body));
                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        });
    }
}

Sina.java:

public class Sina {
    public static void main(String[] args) throws Exception {
        //这里我们不创建队列
        //只创建交换机
        Connection connection = RabbitUtils.getConnection();
        Channel channel = connection.createChannel();

        channel.queueDeclare(RabbitContent.QUEUE_SINA,false,false, false, null);

        //交换机和队列进行绑定
        channel.queueBind(RabbitContent.QUEUE_SINA, RabbitContent.CHANGE_WEATHER, "");

        channel.basicConsume(RabbitContent.QUEUE_SINA, false, new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("新浪收到消息:" + new String(body));
                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        });
    }
}

 路由Routing模式:

 

 

 

 手动添加一个交换机

 

 Baidu.java:

public class Baidu {
    public static void main(String[] args) throws Exception {
        //这里我们不创建队列
        //只创建交换机
        Connection connection = RabbitUtils.getConnection();
        Channel channel = connection.createChannel();

        channel.queueDeclare(RabbitContent.QUEUE_BAIDU,false,false, false, null);

        channel.queueBind(RabbitContent.QUEUE_BAIDU, RabbitContent.CHANGE_ROUTING, "china.henan.zhengzhou.20991011");

        channel.basicConsume(RabbitContent.QUEUE_BAIDU, false, new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("百度收到了消息:" + new String(body));
                channel.basicAck(envelope.getDeliveryTag(),false);
            }
        });
    }
}

Sina.java:

public class Sina {
    public static void main(String[] args) throws Exception {
        //这里我们不创建队列
        //只创建交换机
        Connection connection = RabbitUtils.getConnection();
        Channel channel = connection.createChannel();

        channel.queueDeclare(RabbitContent.QUEUE_SINA,false,false, false, null);

        channel.queueBind(RabbitContent.QUEUE_SINA, RabbitContent.CHANGE_ROUTING, "us.cal.la.20991012");

        channel.basicConsume(RabbitContent.QUEUE_SINA, false, new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("新浪收到了消息:" + new String(body));
                channel.basicAck(envelope.getDeliveryTag(),false);
            }
        });
    }
}

 

 主题Topic模式(常用):

 

 

 TopicProducer.java:

public class TopicProducer {
    public static void main(String[] args) throws Exception {
        //这里我们不创建队列
        //只创建交换机
        Connection connection = RabbitUtils.getConnection();
        Channel channel = connection.createChannel();

        Map<String, String> area = new LinkedHashMap<String, String>();
        area.put("china.hebei.shijiazhuang.20991011", "中国河北石家庄20991011天气数据");
        area.put("china.shandong.qingdao.20991011", "中国山东青岛20991011天气数据");
        area.put("china.henan.zhengzhou.20991011", "中国河南郑州20991011天气数据");
        area.put("us.cal.la.20991011", "美国加州洛杉矶20991011天气数据");

        area.put("china.hebei.shijiazhuang.20991012", "中国河北石家庄20991012天气数据");
        area.put("china.shandong.qingdao.20991012", "中国山东青岛20991012天气数据");
        area.put("china.henan.zhengzhou.20991012", "中国河南郑州20991012天气数据");
        area.put("us.cal.la.20991012", "美国加州洛杉矶20991012天气数据");


        //发送数据
        Iterator<Map.Entry<String, String>> iterator = area.entrySet().iterator();
        while(iterator.hasNext()) {
            Map.Entry<String, String> next = iterator.next();
            //发送数据
            channel.basicPublish(RabbitContent.CHANGE_TOPIC, next.getKey(), true, null, next.getValue().getBytes());
        }

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


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

    }

}

Baidu.java:

public class Baidu {
    public static void main(String[] args) throws Exception {
        //这里我们不创建队列
        //只创建交换机
        Connection connection = RabbitUtils.getConnection();
        Channel channel = connection.createChannel();

        channel.queueDeclare(RabbitContent.QUEUE_BAIDU,false,false, false, null);

        channel.queueBind(RabbitContent.QUEUE_BAIDU, RabbitContent.CHANGE_TOPIC, "china.#");

        channel.basicConsume(RabbitContent.QUEUE_BAIDU, false, new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("百度收到了消息:" + new String(body));
                channel.basicAck(envelope.getDeliveryTag(),false);
            }
        });
    }
}

Sina.java:

public class Sina {
    public static void main(String[] args) throws Exception {
        //这里我们不创建队列
        //只创建交换机
        Connection connection = RabbitUtils.getConnection();
        Channel channel = connection.createChannel();

        channel.queueDeclare(RabbitContent.QUEUE_SINA,false,false, false, null);

        channel.queueBind(RabbitContent.QUEUE_SINA, RabbitContent.CHANGE_TOPIC, "us.*.*.*");

        channel.basicConsume(RabbitContent.QUEUE_SINA, false, new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("新浪收到了消息:" + new String(body));
                channel.basicAck(envelope.getDeliveryTag(),false);
            }
        });

    }
}

 MQ的消息确认机制 Confirm&return 与消费者没有关系

 

 

 

 TopicProducer.java:

public class TopicProducer {
    public static void main(String[] args) throws Exception {
        //这里我们不创建队列
        //只创建交换机
        Connection connection = RabbitUtils.getConnection();
        Channel channel = connection.createChannel();

        Map<String, String> area = new LinkedHashMap<String, String>();
        area.put("china.hebei.shijiazhuang.20991011", "中国河北石家庄20991011天气数据");
        area.put("china.shandong.qingdao.20991011", "中国山东青岛20991011天气数据");
        area.put("china.henan.zhengzhou.20991011", "中国河南郑州20991011天气数据");
        area.put("us.cal.la.20991011", "美国加州洛杉矶20991011天气数据");

        area.put("china.hebei.shijiazhuang.20991012", "中国河北石家庄20991012天气数据");
        area.put("china.shandong.qingdao.20991012", "中国山东青岛20991012天气数据");
        area.put("china.henan.zhengzhou.20991012", "中国河南郑州20991012天气数据");
        area.put("us.cal.la.20991012", "美国加州洛杉矶20991012天气数据");

        channel.confirmSelect();  //开启监听事件

        channel.addConfirmListener(new ConfirmListener() {

            //消息被mq接受,状态
            @Override
            public void handleAck(long deliveryTag, boolean multiple) throws IOException {
                System.out.println("消息被mq接受:" + deliveryTag + "-----" + multiple);
            }

            //消息被mq举手的状态
            @Override
            public void handleNack(long deliveryTag, boolean multiple) throws IOException {
                System.out.println("消息被mq拒收:" + deliveryTag + "-----" + multiple);
            }
        });


        //消息返回操作
        channel.addReturnListener(new ReturnCallback() {
            @Override
            public void handle(Return msg) {
                System.out.println("返回消息的状态吗" + msg.getReplyCode());
                System.out.println("返回消息的文本信息" + msg.getReplyText());
                System.out.println("返回消息的交换机" + msg.getExchange());
                System.out.println("返回消息的路由" + msg.getRoutingKey());
                System.out.println("返回消息为" + new String(msg.getBody()));
            }
        });

        //发送数据
        Iterator<Map.Entry<String, String>> iterator = area.entrySet().iterator();
        while(iterator.hasNext()) {
            Map.Entry<String, String> next = iterator.next();
            //发送数据
            channel.basicPublish(RabbitContent.CHANGE_TOPIC, next.getKey(), true, null, next.getValue().getBytes());
        }

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


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

    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值