RabbitMQ案例二之WorkQueue

这是一个生产者多个消费者的情况


NetTask.java表示是一个生产者,向队列发送很多信息

package yy.rabbitstudy.queue;

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

import com.fasterxml.jackson.databind.deser.std.FromStringDeserializer;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

public class NetTask {

    private final static String QUEUE_NAME = "hello";

    public static void main(String[] args) {
        args=new String[]{"FirstMessage..","SecondMessage...","ThirdMessage..","FourthMessage..","FifthMessage..."};
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = null;
        Channel channel = null;
        try {
            //获取连接
            connection = factory.newConnection();
            //创建通道
            channel = connection.createChannel();
            //打开队列位置
            channel.queueDeclare(QUEUE_NAME, false, false, false, null);
            for (String string : args) {
                
                String message = getMessage(new String[]{string});
                //把数据发布到队列
                channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
                System.out.println("[x] Sent" + message + "");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        } finally {
            if (channel != null) {
                try {
                    channel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (TimeoutException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
        


    }
    
    
    private static String getMessage(String[] strings){
        if(strings.length<1)return "Hello World";
        return joinString(strings, " ");
    }
    
    private static String joinString(String[] strings,String delimiter){
        int length=strings.length;
        if(length==0)return "";
        StringBuilder words=new StringBuilder(strings[0]);
        for(int i=1;i<length;i++){
            words.append(delimiter).append(strings[i]);
        }
        return words.toString();
    }

}
worker.java表示是消费者,运行多个worker。表示多个消费者

package yy.rabbitstudy.queue;

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

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

public class Worker {

    private final static String QUEUE_NAME="hello";
    public static void main(String[] args) throws IOException, TimeoutException {
        
        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");
       
        //把通道交给消费者
        Consumer consumer = 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(" [x] Received '" + message + "'");
              try {
                doWord(message);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally{
                System.out.println("[x] Done");
            }
            }
          };
          channel.basicConsume(QUEUE_NAME, true, consumer);

    }
    
    private static void doWord(String task) throws InterruptedException{
        for(char ch:task.toCharArray()){
            if(ch=='.')Thread.sleep(1000);
        }
    }


}

最后的运行结果如下:

NetTask(producer)的情况如下:
[x] SentFirstMessage..
[x] SentSecondMessage...
[x] SentThirdMessage..
[x] SentFourthMessage..
[x] SentFifthMessage...
Worker1的运行结果如下:
[*] Waiting for messages. to exit press CTRL+C
 [x] Received 'FirstMessage..'
[x] Done
 [x] Received 'ThirdMessage..'
[x] Done
 [x] Received 'FifthMessage...'
[x] Done
Worker2的运行结果如下:
[*] Waiting for messages. to exit press CTRL+C
 [x] Received 'SecondMessage...'
[x] Done
 [x] Received 'FourthMessage..'
[x] Done

最后总结:

queue是使worker得到均等的message,所以轮流分配message,其中,如果一个comsumer死了之后呢。它应得到的task就会消失

 


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值