rabbitmq幾個常用的功能和注意的問題

簡單模式

在這裏插入圖片描述

public class Send {
    private final static String QUEUE_NAME = "hello";
    public static void main(String[] argv) throws Exception {
        //創建鏈接 獲取到channel
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        //聲明隊列
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        String message = "Hello World!";
        //發送消息
        channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
        System.out.println(" [x] Sent '" + message + "'");
        //關閉資源
        channel.close();
        connection.close();
    }
}
public class Recv {

  private final static String QUEUE_NAME = "hello";

  public static void main(String[] argv) throws Exception {
   //創建鏈接 獲取到channel
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
	//聲明隊列
    channel.queueDeclare(QUEUE_NAME, false, false, false, null);
    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
	//
	DeliverCallback deliverCallback = (consumerTag, delivery) -> {
    String message = new String(delivery.getBody(), "UTF-8");
    System.out.println(" [x] Received '" + message + "'");
};
//監聽隊列(參數爲:隊列名稱,是否自動應答,“對數據 處理的方法”)
channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> { });
  }
}

work 工作模式(輪詢共同完成同一任務)

在這裏插入圖片描述

public class Send {
    private final static String QUEUE_NAME = "hello";
    public static void main(String[] argv) throws Exception {
        //創建鏈接 獲取到channel
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        //聲明隊列
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        //發送消息
		 String msg = "第" + i + "消息";
         channel.basicPublish("", QUEUE_NAME, null, msg.getBytes());
        //關閉資源
        channel.close();
        connection.close();
    }
}
public class Recv {

  private final static String QUEUE_NAME = "hello";

  public static void main(String[] argv) throws Exception {
   //創建鏈接 獲取到channel
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
	//聲明隊列
    channel.queueDeclare(QUEUE_NAME, false, false, false, null);
   
	//
 //定義一個消費者
        DefaultConsumer defaultConsumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String msg = new String(body, "utf-8");
                System.out.println("消費者1=>" + msg);
                //休眠2秒
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        boolean autoAck = true;
        channel.basicConsume(QUEUE_NAME, autoAck, defaultConsumer);
  }
}

work fair公平模式(能者多勞共同完成同一任務)

public class Sent {
    private static final String QUEUE_NAME = "test_work_fair_queue";

    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        //獲取連接
        Connection connection = ConnectUtil.getConnection();
        //獲取channel
        Channel channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        /**
         * 每一個消費者發送確認消息之前,消息隊列不發送下一個消息到消費者,依次值處理一個消息,
         * 限制發送給同一個消費者不得超過一條消息
         */
        int prefetchCount = 1;
        channel.basicQos(prefetchCount);

        for (int i = 0; i < 50; i++) {
            String msg = "第" + i + "消息";
            //消息發送
            System.out.println(msg);
            channel.basicPublish("", QUEUE_NAME, null, msg.getBytes());
            Thread.sleep(i * 30);
        }
        channel.close();
        connection.close();
    }
}

public class Receive1 {
    private static final String QUEUE_NAME = "test_work_fair_queue";
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        newApi();
    }
    private static void newApi() throws IOException, TimeoutException, InterruptedException {
        //獲取連接
        Connection connection = ConnectUtil.getConnection();
        //獲取channel
        Channel channel = connection.createChannel();
        //聲明隊列
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        //保證依次只分發一個
        channel.basicQos(1);
        //定義一個消費者
        DefaultConsumer defaultConsumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String msg = new String(body, "utf-8");
                System.out.println("消費者1=>" + msg);
                //休眠2秒
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    channel.basicAck(envelope.getDeliveryTag(),false);
                }
            }
        };
        boolean autoAck = false;// work fair   需要關閉自動應答模式

        channel.basicConsume(QUEUE_NAME, autoAck, defaultConsumer);
    }
}

public class Receive2 {
    private static final String QUEUE_NAME = "test_work_fair_queue";

    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        //獲取連接
        Connection connection = ConnectUtil.getConnection();
        //獲取channel
        Channel channel = connection.createChannel();
        //聲明隊列
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        channel.basicQos(1);//保證依次只接收一個消息
        DefaultConsumer defaultConsumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String msg = new String(body, "UTF-8");
                System.out.println("消費者2=>" + msg);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    //手動回執消息
                    channel.basicAck(envelope.getDeliveryTag(),false);
                }
            }
        };
        boolean autoAck = false;// work fair 關閉自動應答
        channel.basicConsume(QUEUE_NAME, autoAck, defaultConsumer);
    }
}

訂閱模式publish/subscribe 交換機類型fanout(根據路由key)

在這裏插入圖片描述

  • 發送
 channel.exchangeDeclare(EXCHANGE_NAME, "fanout");
        for (int i = 0; i < 50; i++) {
            //定義消息
            String msg = "fanout_message=>" + i;
            System.out.println(msg);
            //發送消息
            channel.basicPublish(EXCHANGE_NAME, "", null, msg.getBytes());
        }
  • 接收
public class Reveice1 {
    private static final String QUEUE_NAME = "test_queue_fanout_email";
    private static final String EXCHANGE_NAME = "test_exchange_fanout";
    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = ConnectUtil.getConnection();
        Channel channel = connection.createChannel();
        //隊列聲明
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        //綁定隊列到交換機
        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "");
        //保證依次只分發一個
        channel.basicQos(1);
        //定義一個消費者
        DefaultConsumer defaultConsumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String msg = new String(body, "utf-8");
                System.out.println("Reveice1=>" + msg);
                //休眠2秒
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    channel.basicAck(envelope.getDeliveryTag(), false);
                }
            }
        };
        boolean autoAck = false;// work fair   需要關閉自動應答模式
        channel.basicConsume(QUEUE_NAME, autoAck, defaultConsumer);
    }
}
public class Reveice2 {
    private static final String QUEUE_NAME = "test_queue_fanout_sms";
    private static final String EXCHANGE_NAME = "test_exchange_fanout";
    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = ConnectUtil.getConnection();
        Channel channel = connection.createChannel();
        //隊列聲明
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        //綁定隊列到交換機
        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "");
        channel.basicQos(1);//保證一次只分發一個
        DefaultConsumer defaultConsumer=new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String msg = new String(body, "utf-8");
                System.out.println("Reveice2=>"+msg);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    channel.basicAck(envelope.getDeliveryTag(),false);
                }
            }
        };
        boolean autoAck = false;//關閉自動應答
        channel.basicConsume(QUEUE_NAME, autoAck, defaultConsumer);
    }
}

訂閱模式routing 交換機類型direct()

在這裏插入圖片描述

public class Send {
    private static final String EXCHANGE_NAME = "test_exchange_direct";
    static List list = new LinkedList();
    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = ConnectUtil.getConnection();
        Channel channel = connection.createChannel();
        channel.exchangeDeclare(EXCHANGE_NAME, "direct");
        list.add("info");
        list.add("error");
        list.add("warning");
        for (Object s : list) {
            String msg = (String) s;
            System.out.println(msg);
            String routingKey = (String) s;
            channel.basicPublish(EXCHANGE_NAME, routingKey, null, msg.getBytes());
        }

        /*String msg = "hello direct";
        String routingKey = "error";
        channel.basicPublish(EXCHANGE_NAME,routingKey,null,msg.getBytes());
   */
    }
}
public class Revice1 {
    private static final String EXCHANGE_NAME = "test_exchange_direct";
    private static final String QUEUE_NAME = "test_queue_direct1";
    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = ConnectUtil.getConnection();
        Channel channel = connection.createChannel();
        //這個地方寫錯了 聲明隊列  中的參數寫成了交換機
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        channel.basicQos(1);
        //queueBind 寫成了exechangeBind
        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "error");

        DefaultConsumer defaultConsumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String msg = new String(body, "utf-8");
                System.out.println(msg);
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    channel.basicAck(envelope.getDeliveryTag(),false);
                }
            }
        };
        boolean autoAck=false;
        channel.basicConsume(QUEUE_NAME, autoAck, defaultConsumer);
    }
}

topic模式(*#正則表達的方式)

在這裏插入圖片描述

public class Send {

    private final static String EXCHANGE_NAME = "test_exechange_topic";
    public static void main(String[] args) throws IOException, TimeoutException {

        Connection connection = ConnectUtil.getConnection();
        Channel channel = connection.createChannel();
        channel.exchangeDeclare(EXCHANGE_NAME, "topic");

        String msg = "test_exechange_topic";

        Map map = new HashMap();
        map.put("goods.add", "商品添加……");
        map.put("goods.delete", "商品刪除……");
        map.put("goods.update", "商品修改……");
        map.put("goods.select", "商品查詢……");
        map.put("goods.update.add", "商品add and update……");

        for (Object s:map.keySet()
             ) {
            String key = (String) s;
            String msg_ = (String) map.get(key);
            System.out.println(key + "<===>" + msg_);
            channel.basicPublish(EXCHANGE_NAME,key,false,null,msg_.getBytes());

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

public class Receive1 {
    private final static String EXCHANGE_NAME = "test_exechange_topic";
    private final static String QUEUE_NAME = "test_queue_topic1";
    public static void main(String[] args) throws IOException, TimeoutException {

        Connection connection = ConnectUtil.getConnection();
        Channel channel = connection.createChannel();
        //聲明隊列
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "#.add");
        channel.basicQos(1);


        DefaultConsumer defaultConsumer=new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String msg = new String(body, "UTF-8");
                System.out.println("test_queue_topic1==>"+msg);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    channel.basicAck(envelope.getDeliveryTag(),false);
                }

            }
        };

        boolean autoAck = false;
        channel.basicConsume(QUEUE_NAME, autoAck, defaultConsumer);


    }
}
public class Receive2 {
    private final static String EXCHANGE_NAME = "test_exechange_topic";
    private final static String QUEUE_NAME = "test_queue_topic2";
    public static void main(String[] args) throws IOException, TimeoutException {

        Connection connection = ConnectUtil.getConnection();
        Channel channel = connection.createChannel();
        //聲明隊列
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "goods.*");
        channel.basicQos(1);


        DefaultConsumer defaultConsumer=new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String msg = new String(body, "UTF-8");
                System.out.println("test_queue_topic2==>"+msg);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    channel.basicAck(envelope.getDeliveryTag(),false);
                }

            }
        };

        boolean autoAck = false;
        channel.basicConsume(QUEUE_NAME, autoAck, defaultConsumer);


    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章