初步学习rabbitmq笔记

 

启动rabbitmq插件:rabbitmq-plugins enable rabbitmq_management

启动rabbitmq:rabbitmq-server

访问页面端口:15672

第一种模型(直连):

生产者生产消息:

@Test
    public void testSendMessage() throws IOException, TimeoutException {
        //创建mq工厂的连接
        ConnectionFactory connectionFactory=new ConnectionFactory();
        //设置虚拟主机
        connectionFactory.setVirtualHost("/v-virtual");
        //设置端口
        connectionFactory.setPort(5672);
        //设置rabbitmq的ip
        connectionFactory.setHost("192.168.3.49");
        //设置账户密码
        connectionFactory.setUsername("v");
        connectionFactory.setPassword("123");
        //连接mq
        Connection connection = connectionFactory.newConnection();
        //创建通道
        Channel channel = connection.createChannel();
        //通道绑定对应的消息队列
        //参数1:队列名称 不存在自动创建
        //参数2:用来定义是否需要持久化 true需要 false 不需要, 如true 关mq写入磁盘 false则不写入
        //参数3:是否独占队列  true独占 false 不独占, 独占则其他消息不能进入该队列
        //参数4:是否在被消费完后自动删除队列
        //参数5:附加参数
        //说明:当参数2为true时 关闭mq服务,队列不会被删除.
        channel.queueDeclare("hello",false,false,false,null);
        //发布消息
        //参数1:交换机名称
        //参数2:队列名称
        //参数3:消息传送的也额外设置
        //参数4:传送的消息内容
        //说明:当第三个参数设置为MessageProperties.PERSISTENT_TEXT_PLAIN时,消息不会被删除.前提是开启持久化
        channel.basicPublish("","hello",null,"哈哈,mq被创建了".getBytes());
        System.out.println("消息发布成功了----------------->");
        //关闭渠道
        channel.close();
        //关闭连接
        connection.close();
    }

消费者消费信息:

 public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory connectionFactory=new ConnectionFactory();
        connectionFactory.setPassword("123");
        connectionFactory.setUsername("v");
        connectionFactory.setHost("192.168.3.49");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/v-virtual");
        Connection connection = connectionFactory.newConnection();
        Channel channel = connection.createChannel();
        //绑定队列
        channel.queueDeclare("hallo",false,false,false,null);
        //消费指定队列的信息
        /**
         *参数:
         *    1.指定要消费的队列
         *    2.开启消息自动确认机制
         *    3.消费时回调的接口
         *    
         */
        channel.basicConsume("hello", true, new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String s, Envelope envelope, AMQP.BasicProperties basicProperties, byte[] bytes) throws IOException {
                System.out.println("-------------->消费消息->"+new String(bytes));
            }
        });

    }

 

创建工具类:


    private static ConnectionFactory connectionFactory;

    //类加载时运行一次
    static {
        connectionFactory=new ConnectionFactory();
        connectionFactory.setVirtualHost("/v-virtual");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("v");
        connectionFactory.setPassword("123");
        connectionFactory.setHost("192.168.3.49");
    }
    //创建mq连接
    public static Connection getRabbitMqConnection(){
        try {
            return connectionFactory.newConnection();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
        return  null;
    }
    //关闭mq资源
    public static void closeRabbitMqConnection(Channel channel,Connection connection){
        try {
            if (channel!=null)channel.close();
            if (connection!=null)connection.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }

rabbitmq----work模型:一对多

生产者:

 public static void main(String[] args) throws IOException {
        Connection rabbitMqConnection = RabbitMQUtils.getRabbitMqConnection();
        Channel channel = rabbitMqConnection.createChannel();
        //声明队列
        channel.queueDeclare("work",false,false,false,null);
        for (int i = 0; i <30 ; i++) {
            channel.basicPublish("","work",null,(i+"生产者生产了消息").getBytes());
        }
        //发送消息
        RabbitMQUtils.closeRabbitMqConnection(channel,rabbitMqConnection);
    }

消费者1:

    Connection rabbitMqConnection = RabbitMQUtils.getRabbitMqConnection();
        //创建渠道
        Channel channel = rabbitMqConnection.createChannel();

        channel.queueDeclare("work",false,false,false,null);

        channel.basicConsume("work",true,new DefaultConsumer(channel){

            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("我Consumer1拿到信息了,内容为:-->"+new String(body));
            }
        });

消费者2:

public static void main(String[] args) throws IOException {
        Connection rabbitMqConnection = RabbitMQUtils.getRabbitMqConnection();
        //创建渠道
        Channel channel = rabbitMqConnection.createChannel();

        channel.queueDeclare("work",false,false,false,null);

        channel.basicConsume("work",true,new DefaultConsumer(channel){

            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("我Consumer2拿到信息了,内容为:-->"+new String(body));
            }
        });
    }

运行结果:

结论:当有多个消费者时,mq会平均分配生产信息

能者多劳(不平均分配):consumer(在所有消费者里改)

    Connection rabbitMqConnection = RabbitMQUtils.getRabbitMqConnection();
        //创建渠道
        final Channel channel = rabbitMqConnection.createChannel();
        channel.basicQos(1);//每次只能消费一个消息   
        channel.queueDeclare("work",false,false,false,null);
        //false 不开启消息自动确认
        channel.basicConsume("work",false,new DefaultConsumer(channel){

            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("我Consumer2拿到信息了,内容为:-->"+new String(body));
                //手动确认 参数1:手动确认标识,参数2 false每次确认一个
                channel.basicAck(envelope.getDeliveryTag(),false);
            }
        });
    }

rabbitmq---fanout(广播模型):

消费者:

  public static void main(String[] args) throws IOException {

        Connection rabbitMqConnection = RabbitMQUtils.getRabbitMqConnection();

        Channel channel = rabbitMqConnection.createChannel();

        //t通道绑定交换机
        channel.exchangeDeclare("logs","fanout");

        //创建临时队列
        String queueName = channel.queueDeclare().getQueue();

        //将交换机与临时队列进行绑定
        channel.queueBind(queueName,"logs","");

        //消费消息
        channel.basicConsume(queueName, true, new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("消费者1-消费信息:"+new String(body));
            }
        });
    }

生产者:

   //创建连接
        Connection rabbitMqConnection = RabbitMQUtils.getRabbitMqConnection();

        //创建通道
        Channel channel = rabbitMqConnection.createChannel();

        //将通道声明指定交换机 参数1:交换机名字 参数2:fanout 广播类型
        channel.exchangeDeclare("logs","fanout");

        //发送消息
        channel.basicPublish("logs","",null,"fanout 发送信息成功".getBytes());

        //关闭资源
        RabbitMQUtils.closeRabbitMqConnection(channel,rabbitMqConnection);

结论:当生产者生产消息时,被绑定的相同的交换机会把信息发给消费者

rabbitmq---路由模式(对指定的消费者发信息)

消费者1:

  // 创建连接
        Connection rabbitMqConnection = RabbitMQUtils.getRabbitMqConnection();
        //创建通道
        Channel channel = rabbitMqConnection.createChannel();
        //定义交换机名字
        String exchangeName="logs_direct";
        //申明交换机
        channel.exchangeDeclare(exchangeName, "direct");
        //申明一个临时队列
        String queueName = channel.queueDeclare().getQueue();
        //队列与交换机绑定
        channel.queueBind(queueName, exchangeName, "info");
        //消费消息
        channel.basicConsume(queueName, true,new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("消费者1"+new String(body));
            }
        });

    }

 消费者2:

 // 创建连接
        Connection rabbitMqConnection = RabbitMQUtils.getRabbitMqConnection();
        //创建通道
        Channel channel = rabbitMqConnection.createChannel();
        //定义交换机名字
        String exchangeName="logs_direct";
        //申明交换机  参数2 direct 路由模式
        channel.exchangeDeclare(exchangeName, "direct");
        //申明一个临时队列
        String queueName = channel.queueDeclare().getQueue();
        //队列与交换机绑定
        channel.queueBind(queueName, exchangeName, "info");
        channel.queueBind(queueName, exchangeName, "error");
        channel.queueBind(queueName, exchangeName, "warning");
        //消费消息
        channel.basicConsume(queueName, true,new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("消费者2"+new String(body));
            }
        });

    }

生产者:

    // 创建连接
        Connection rabbitMqConnection = RabbitMQUtils.getRabbitMqConnection();
        //创建通道
        Channel channel = rabbitMqConnection.createChannel();
        //定义交换机名字
        String exchangeName="logs_direct";
        //申明交换机
        channel.exchangeDeclare(exchangeName, "direct");
        String routingKey="error";
        //生产消息
        channel.basicPublish(exchangeName,routingKey,null,("这是生产者发送的信息.名称为:"+routingKey).getBytes());
        //关闭资源
        RabbitMQUtils.closeRabbitMqConnection(channel,rabbitMqConnection);

结论:发送指定消息时 可以根据路由的不同进行发送

rabbitmq---动态路由模式:(通配符路由):

生产者:

  //获取连接
        Connection rabbitMqConnection = RabbitMQUtils.getRabbitMqConnection();
        //创建渠道
        Channel channel = rabbitMqConnection.createChannel();
        //交换机名字
        String exchangeName="topics";
        //定义一个交换机  参数二 topic 动态路由模型
        channel.exchangeDeclare(exchangeName, "topic");
        String routingKey="user.hah";
        //发送消息  参数1 交换机名字 参数2:路由名字
        channel.basicPublish(exchangeName, routingKey, null, ("生产者已经生产消息,消息为:"+routingKey).getBytes());

        RabbitMQUtils.closeRabbitMqConnection(channel, rabbitMqConnection);

消费者1:

     //创建连接
        Connection rabbitMqConnection = RabbitMQUtils.getRabbitMqConnection();
        //创建通道
        Channel channel = rabbitMqConnection.createChannel();
        //定义交换机名称
        String exchangName="topics";
        //定义交换机
        channel.exchangeDeclare(exchangName, "topic");
        //创建临时队列
        String queue = channel.queueDeclare().getQueue();
        //绑定交换机与队列 路由绑定
        channel.queueBind(queue,exchangName,"*.user");
        //消费消息
        channel.basicConsume(queue,true, new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("消费者1-->消费消息为:"+new String(body));
            }
        });

消费者2:

 //创建连接
        Connection rabbitMqConnection = RabbitMQUtils.getRabbitMqConnection();
        //创建通道
        Channel channel = rabbitMqConnection.createChannel();
        //定义交换机名称
        String exchangName="topics";
        //定义交换机
        channel.exchangeDeclare(exchangName, "topic");
        //创建临时队列
        String queue = channel.queueDeclare().getQueue();
        //绑定交换机与队列 路由绑定
        //          参数3 路由
        //          *  匹配一个词
        //          #  匹配一个或多个

        channel.queueBind(queue,exchangName,"user.#");
        //消费消息
        channel.basicConsume(queue,true, new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("消费者2-->消费消息为:"+new String(body));
            }
        });

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值