Java使用RabbitMQ(二)--发送和接收信息

发送和接收信息

发送方:

public class BaseTest2 {
    public static String queueName="q1";

    public static ConnectionFactory factory;
    public static Connection getConnection(String username,String password,String host,int port,String virtualhost) {
        if (factory==null){
            factory=getFactory(username,password,host,port,virtualhost);
        }
        try {
            return factory.newConnection();
        } catch (Exception e) {
            throw new RuntimeException("创建rabbit client 连接失败"+e);
        }
    }

    private synchronized static ConnectionFactory getFactory(String username, String password, String host, int port, String virtualhost) {
        if (factory!=null)
            return factory;
        ConnectionFactory factory=new ConnectionFactory();
        factory.setUsername(username);
        factory.setPassword(password);
        factory.setVirtualHost(virtualhost);
        factory.setHost(host);
        factory.setPort(port);

        return factory;
    }
    private static String getMessage(String[] strings){
        if (strings.length < 1)
            return "Hello World!";
        return joinStrings(strings, " ");
    }

    private static String joinStrings(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();
    }
    private static void doWork(String task) throws InterruptedException {
        for (char ch: task.toCharArray()) {
            if (ch == '.') Thread.sleep(1000);
        }
    }
    public static void main(String[] args) {
        try(Connection connection=getConnection("guest","guest","localhost",5672,"/");
            Channel channel=connection.createChannel()) {

//            channel.exchangeDeclare("交换机","direct",true);
             channel.queueDeclare(queueName,false,false,false,null);

            String message=getMessage(new String[]{"a","b","c"});
            channel.basicPublish("",queueName,null,message.getBytes("utf-8"));

//            Thread.sleep(2000);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (TimeoutException e) {
            throw new RuntimeException("连接超时"+e);
        }
    }
}

接收方:

public class BasicTest3 {
    public static void main(String[] args) {
        try(Connection connection=BaseTest2.getConnection("guest","guest","localhost",5672,"/");
            Channel channel=connection.createChannel()) {

//            channel.exchangeDeclare("交换机","direct",true);
            channel.queueDeclare(BaseTest2.queueName,false,false,false,null);

            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");
                    try {
                        doWork(message);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        System.out.println(message+" [x] Done");
                    }
//                    channel.basicAck(envelope.getDeliveryTag(),false);
                }
            };
            channel.basicConsume(BaseTest2.queueName,false, consumer);
            Thread.sleep(2000);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
    private static String getMessage(String[] strings){
        if (strings.length < 1)
            return "Hello World!";
        return joinStrings(strings, " ");
    }

    private static String joinStrings(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();
    }
    private static void doWork(String task) throws InterruptedException {
        for (char ch: task.toCharArray()) {
            if (ch == '.') Thread.sleep(1000);
        }
    }
}

在消费方,channel.basicConsume(BaseTest2.queueName,false, consumer);
false是指不自动确认(自动确认的话,rabbit中存的消息会被消费掉。)
为true时,会被自动消费,然后别人就收不到这条消息了。

修改下 生产者的代码:

 public static void main(String[] args) {
        try(Connection connection=getConnection("guest","guest","localhost",5672,"/");
            Channel channel=connection.createChannel()) {

//            channel.exchangeDeclare("交换机","direct",true);
             channel.queueDeclare(queueName,false,false,false,null);
            String message=getMessage(new String[]{"a","b","c"});
            int i=0;
            while (true){
                Thread.sleep(1000);
                channel.basicPublish("",queueName,null,(i+++message).getBytes("utf-8"));
            }

//            Thread.sleep(2000);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (TimeoutException e) {
            throw new RuntimeException("连接超时"+e);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

生产者循环生产新的消息

然后开2个消费者,运行结果如下:

10a b c [x] Done
12a b c [x] Done
14a b c [x] Done
16a b c [x] Done
18a b c [x] Done

另一个消费者:

11a b c [x] Done
13a b c [x] Done
15a b c [x] Done
17a b c [x] Done

可以看出,是rabbit交替发送的。每个消费者获取的消息是平均的 ,这也叫循环。

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页