消息队列

2018-09-27  本文已影响0人  尼尔君
package com.boolib;

import com.rabbitmq.client.*;

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

public class RabbitMQ1 {



}



class Send{
    private final static String QUEUE_NAME="hello";

    public static void main(String[] args) {
        try {
            send("aaaa");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }


    public static void send(String msg) 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);



        channel.basicPublish("",QUEUE_NAME,null,msg.getBytes());

        channel.close();

        connection.close();

    }
}


class Resv{

    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);

        Consumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                super.handleDelivery(consumerTag, envelope, properties, body);

                String msg=new String(body,"UTF-8"); System.out.println("Received message is:"+msg);

            };

            };

        channel.basicConsume(QUEUE_NAME,true,consumer);





    }










}

上一篇 下一篇

猜你喜欢

热点阅读