rabbitMQ基础篇

先介绍所须要包:          

         

<dependency>
    <groupId>com.rabbitmq</groupId>
    <artifactId>amqp-client</artifactId>
    <version>4.0.2</version>
</dependency>
<dependency>
         <groupId>org.slf4j</groupId>
        <artifactId>slf4j-nop</artifactId>
         <version>1.7.2</version>
     </dependency>

<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>
0:让我们来创建一个公共的工具类(少写点代码)
public class ConnectionUtils {
    public  static Connection getConnection() throws IOException, TimeoutException {
        ConnectionFactory factory=new ConnectionFactory();
        factory.setHost("212.129.148.99");  //根据自己的ip地址修改
        factory.setPort(5672);
        factory.setVirtualHost("/ncc");  //根据自己设置的配置修改
        factory.setUsername("ncc");      //根据自己设置的配置修改
        factory.setPassword("123456789");//根据自己设置的配置修改
        Connection   connection = factory.newConnection();
        return connection;
    }
   
}

下面所有的模式都是用生产者(发送消息)和消费者(接受并处理消息)的模式进行演示

1:简单队列

//生产者
public class send {
    private static final String Queue_Name="Test_simple_queue";
    public  static void main(String args[]) throws IOException, TimeoutException {
        Connection connection = ConnectionUtils.getConnection();
        Channel channel = connection.createChannel();

        channel.queueDeclare(Queue_Name,false,false,false,null);
        String msg="123";
        channel.basicPublish("",Queue_Name,null,msg.getBytes());
        channel.close();
        connection.close();
    }
}

//消费者
//新的api
//o1简单队列
public class newRecv {
    private static final String Queue_Name="Test_simple_queue";
    public  static void main(String args[]) throws IOException, TimeoutException {
        Connection connection = ConnectionUtils.getConnection();//创建连接
        Channel channel = connection.createChannel();           //获取通道

        DefaultConsumer consumer=new DefaultConsumer(channel){ //创建consumer并读取数据
            @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);
            }
        };

       channel.basicConsume(Queue_Name,true,consumer);    //监听队列


    }}
2:轮询分发
//生产者
public class send {
    private static String QUEUE_Name="work_queue";

    public static void main(String args[]) throws IOException, TimeoutException, IOException, TimeoutException, InterruptedException {
        Connection connection = ConnectionUtils.getConnection();//创建连接
        Channel channel = connection.createChannel();           //获取通道
       
        channel.queueDeclare(QUEUE_Name,false,false,false,null);//声明一个队列
        for(int i=0;i<50;i++){
            String msg="hello"+i;
            channel.basicPublish("",QUEUE_Name,null,msg.getBytes());  //发送消息
            Thread.sleep(i*20);
            System.out.println(msg);
        }
        channel.close();
        connection.close();
    }
}

//消费者1
public class recv1 {
    private static String QUEUE_Name="work_queue";
    public  static void main(String args[]) throws IOException, TimeoutException, IOException {
        Connection connection = ConnectionUtils.getConnection();//创建连接
        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 {
                String msg=new String(body,"utf-8");
                System.out.println(msg);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        };
        channel.basicConsume(QUEUE_Name,true,consumer);                       //监听队列  //true表示自动应答
    }
}


//消费者2

public class recv2 {
    private static String QUEUE_Name="work_queue";

    public  static void main(String args[]) throws IOException, TimeoutException, IOException {
        Connection connection = ConnectionUtils.getConnection();//创建连接
        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 {
                String msg=new String(body,"utf-8");
                System.out.println(msg);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        };
        channel.basicConsume(QUEUE_Name,true,consumer);                       //监听队列
    }
}
3:公平分发
//生产者
/*
公平分发也叫能者多劳
只需修改工作队列的一些代码即可实现
生产者
1,设置每个消费者同一时间内最多能处理几个消息
        int pretechCount=1;
        channel.basicQos(pretechCount);//使得每个Consumer在同一个时间点最多处理1个Message(就是消费者在返回消息给生产者之前,他不会给消费者再次分配消息)
消费者
1,消费者也要设置确认机制channel.basicQos(pretechCount);
2,设置消费者的ack手动回执处理完成消息
  channel.basicAck(envelope.getDeliveryTag(),false);      ///手动回执消息//
3,关闭自动应答模式
 channel.basicConsume(QUEUE_Name,ack,consumer);                       //监听队列  //true表示自动应答
 */
public class send {

    private static String Queue_Name="fair_dispatch";

    public  static void main(String args[]) throws IOException, TimeoutException, IOException, TimeoutException, InterruptedException {
        Connection connection = getConnection();//创建连接
        Channel channel = connection.createChannel();//获取通道

        channel.queueDeclare(Queue_Name,false,false,false,null);

        int pretechCount=1;
        channel.basicQos(pretechCount);//使得每个Consumer在同一个时间点最多处理1个Message

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


//消费者1
public class recv1 {
    private static String QUEUE_Name="fair_dispatch";
    public  static void main(String args[]) throws IOException, TimeoutException, IOException {
        Connection connection = ConnectionUtils.getConnection();//创建连接
        Channel channel = connection.createChannel();           //获取通道

        channel.queueDeclare(QUEUE_Name,false,false,false,null);   //声明队列

        channel.basicQos(1);      //保证每次之分发一个//

        Consumer consumer=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(1000);
                    channel.basicAck(envelope.getDeliveryTag(),false);      ///手动回执消息//
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        };
        //需要关闭自动应答//
        Boolean ack=false;
        channel.basicConsume(QUEUE_Name,ack,consumer);                       //监听队列  //true表示自动应答
    }
}


//消费者2
public class recv2 {
    private static String QUEUE_Name="fair_dispatch";

    public  static void main(String args[]) throws IOException, TimeoutException, IOException {
        Connection connection = ConnectionUtils.getConnection();//创建连接
        Channel channel = connection.createChannel();           //获取通道

        Boolean durable=false;
        channel.queueDeclare(QUEUE_Name,durable,false,false,null);   //声明队列   在声明队列的时候后面的durable就是持久化工具当设为true是就可以持久化数据
        channel.basicQos(1);      //保证每次之分发一个//
        Consumer consumer=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);
                    channel.basicAck(envelope.getDeliveryTag(),false);      ///手动回执消息//
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        };
        //需要关闭自动应答//
        Boolean ack=false;
        channel.basicConsume(QUEUE_Name,ack,consumer);                       //监听队列
    }
}
 
4:路由模式

//生产者
/*
   路由模式:
       1:声明交换机  指定路由键
       2:routingKey;设置路由键
       3:发送消息;在发送消息里设置routingKey
 */
public class send {
    private static String Exchange_Nmae="exchange_direct";

    public  static void main(String args[]) throws IOException, TimeoutException, InterruptedException {
        Connection connection = getConnection();
        Channel channel= connection.createChannel();

       channel.exchangeDeclare(Exchange_Nmae,"direct");
       String routingKey="info";

        for (int i = 0; i < 10; i++)
        {
            String message = "this is user registe message" + i;
            System.out.println("[send]:" + message);
            //发送消息
            channel.basicPublish(Exchange_Nmae, routingKey, null, message.getBytes("utf-8"));
            Thread.sleep(5 * i);
        }

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

    }
}


//消费者1
public class recv1 {
    private static String Queue_Name="queue_1";
    private static String Exchange_Name="exchange_direct";

    //psvm,快捷键
    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = ConnectionUtils.getConnection();
        Channel channel = connection.createChannel();

        //声明队列
        channel.queueDeclare(Queue_Name, false, false, false, null);
        //
        channel.basicQos(1);
        channel.exchangeDeclare(Exchange_Name, "direct");//交换机声明
        channel.queueBind(Queue_Name, Exchange_Name, "error");//这里确定路由器的路由模式

        Consumer consumer = 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);
                    channel.basicAck(envelope.getDeliveryTag(), false);      ///手动回执消息//
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        };
        //需要关闭自动应答//
        Boolean ack=false;
        channel.basicConsume(Queue_Name,ack,consumer);                       //监听队列

    }
}

//消费者2

public class recv2 {
    private static String Queue_Name="queue_2";
    private static String Exchange_Name="exchange_direct";

    //psvm,快捷键
    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = ConnectionUtils.getConnection();
        Channel channel = connection.createChannel();

        //声明队列
        channel.queueDeclare(Queue_Name, false, false, false, null);
        //
        channel.basicQos(1);
        channel.exchangeDeclare(Exchange_Name, "direct");//交换机声明
        channel.queueBind(Queue_Name, Exchange_Name, "info");//这里确定路由器的路由模式

        Consumer consumer = 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);
                    channel.basicAck(envelope.getDeliveryTag(), false);      ///手动回执消息//
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        };
        //需要关闭自动应答//
        Boolean ack=false;
        channel.basicConsume(Queue_Name,ack,consumer);                       //监听队列

    }
}

5:订阅模式

//生产者
/*
订阅模式中只需要生命交换机

若没有运行消费者,那么数据将会丢失应为没有将交换机绑定给队列

   两步:声明交换机,发送消息
 */
public class send {
    private static String Exchange_Name="exchange_name";

    public  static void main(String args[]) throws IOException, TimeoutException, InterruptedException {
        Connection connection = ConnectionUtils.getConnection();//创建连接
        Channel channel = connection.createChannel();           //获取通道

        channel.exchangeDeclare(Exchange_Name,"fanout");    //声明交换机
        for (int i = 0; i < 10; i++)
        {
            String message = "this is user registe message" + i;
            System.out.println("[send]:" + message);
            //发送消息
            channel.basicPublish(Exchange_Name, "", null, message.getBytes("utf-8"));
            Thread.sleep(5 * i);
        }

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


    }
}

//消费者1
public class recv1 {
    private static String Queue_Name="dingyue1";
    private static String Exchange_Name="exchange_name";
    public static void main(String args[]) throws IOException, TimeoutException {
        Connection connection = getConnection();//创建连接
        Channel channel = connection.createChannel();           //获取通道

        //声明交换机
        channel.exchangeDeclare(Exchange_Name,"fanout");
        //声明队列
        channel.queueDeclare(Queue_Name,false,false,false,null);
        //绑定队列
        channel.queueBind(Queue_Name,Exchange_Name,"");

        Consumer consumer=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);
                    channel.basicAck(envelope.getDeliveryTag(),false);      ///手动回执消息//
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        };
        //需要关闭自动应答//
        Boolean ack=false;
        channel.basicConsume(Queue_Name,ack,consumer);                       //监听队列
    }
}


//消费者2
public class recv2 {
    private static String Queue_Name="dingyue2";
    private static String Exchange_Name="exchange_name";
    public static void main(String args[]) throws IOException, TimeoutException {
        Connection connection = getConnection();//创建连接
        Channel channel = connection.createChannel();           //获取通道

        channel.exchangeDeclare(Exchange_Name,"fanout");
        //声明队列
        channel.queueDeclare(Queue_Name,false,false,false,null);
        //绑定队列
        channel.queueBind(Queue_Name,Exchange_Name,"");
        Consumer consumer=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);
                    channel.basicAck(envelope.getDeliveryTag(),false);      ///手动回执消息//
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        };
        //需要关闭自动应答//
        Boolean ack=false;
        channel.basicConsume(Queue_Name,ack,consumer);                       //监听队列
    }
}
6:主题模式
//生产者
/*
    1:声明交换机:路由键为topic
    2:发送消息:第二个信息为自己填充的通配符"good.add"
 */
public class send {
    private static String Exchange_name="Exchange_Name01";

    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        Connection connection= ConnectionUtils.getConnection();
        Channel channel=connection.createChannel();

        //声明路由器
        channel.exchangeDeclare(Exchange_name,"topic");//
        for (int i = 0; i < 10; i++)
        {
            String message = "this is user registe message" + i;
            System.out.println("[send]:" + message);
            //发送消息
            channel.basicPublish(Exchange_name, "good.add", null, message.getBytes("utf-8"));///
            Thread.sleep(5 * i);
        }

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

    }
}


//消费者1
/*
   使用通配符   good.*
 */
public class recv1 {
    private static String Exchange_Name="Exchange_Name01";
    private static String Queue_Name="queue01";
    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection= ConnectionUtils.getConnection();
        Channel channel=connection.createChannel();

        //声明交换机
        channel.exchangeDeclare(Exchange_Name,"topic");///
        //声明队列
        channel.queueDeclare(Queue_Name,false,false,false,null);
        //绑定队列
        channel.queueBind(Queue_Name,Exchange_Name,"good.*");//
        channel.basicQos(1);

        Consumer consumer=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);
                    channel.basicAck(envelope.getDeliveryTag(),false);      ///手动回执消息//
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        };
        //需要关闭自动应答//
        Boolean ack=false;
        channel.basicConsume(Queue_Name,ack,consumer);                       //监听队列
    }


}

//消费者2
/*
 使用通配符接受数据  *.add
 */
public class recv2 {
    private static String Exchange_Name="Exchange_Name01";
    private static String Queue_Name="queue02";
    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection= ConnectionUtils.getConnection();
        Channel channel=connection.createChannel();

        //声明交换机
        channel.exchangeDeclare(Exchange_Name,"topic");
        //声明队列
        channel.queueDeclare(Queue_Name,false,false,false,null);
        //绑定队列
        channel.queueBind(Queue_Name,Exchange_Name,"*.add");
        channel.basicQos(1);

        Consumer consumer=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);
                    channel.basicAck(envelope.getDeliveryTag(),false);      ///手动回执消息//
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        };
        //需要关闭自动应答//
        Boolean ack=false;
        channel.basicConsume(Queue_Name,ack,consumer);                       //监听队列
    }


}

 

恭喜你入了门

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值