2.2rabbitMq基础操作

rabbitMq基础操作 并整合 springboot

github:https://github.com/Plumblumpb/messageQueue-.git
rabbitMq文章(可以先观看):https://blog.csdn.net/c_royi/article/details/86630777

 rabbitMq基础操作

pom.xml文件

<dependency>
   <groupId>com.rabbitmq</groupId>
   <artifactId>amqp-client</artifactId>
   <version>5.4.3</version>
</dependency>
  1.queue模式


生产者

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

/**
 * @Auther: cpb
 * @Date: 2019/1/24 16:01
 * @Description:
 */
public class Producer {
    private final static String QUEUE_NAME = "helloMytest";

    public static void main(String[] args) throws IOException {
        try {
            /**
             * 创建连接连接到MabbitMQ
             */
            ConnectionFactory factory = new ConnectionFactory();
            // 设置MabbitMQ所在主机ip或者主机名
            factory.setHost("localhost");            //factory.setUsername("lp");//factory.setPassword("");// factory.setPort(2088);
            // 创建一个连接
            Connection connection = factory.newConnection();
            // 创建一个频道
            Channel channel = connection.createChannel();
            // 发送的消息
            String message = "hello 你好";

            // 指定一个队列【参数说明:参数一:队列名称,参数二:是否持久化;参数三:是否独占模式;参数四:消费者断开连接时是否删除队列;参数五:消息其他参数】
            channel.queueDeclare(QUEUE_NAME, false, false, false, null);
            // 往队列中发出一条消息【参数说明:参数一:交换机名称;参数二:路由键名称,参数三:消息的其他属性-routing headers,此属性为MessageProperties.PERSISTENT_TEXT_PLAIN用于设置纯文本消息存储到硬盘;参数四:消息主体】
            for(int i = 0 ; i<10 ; i++) {
                channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
            }
            System.out.println(" 消息队列信息:" + message );
            // 关闭频道和连接
            channel.close();
            connection.close();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }
}

消费者

import com.rabbitmq.client.*;
import java.io.IOException;


/**
 * @Auther: cpb
 * @Date: 2019/1/24 15:53
 * @Description:
 */
public class Customer {
    private static final String QUEUE_NAME ="helloMytest";

    public static void main(String[] argv) throws Exception {
        //建立连接和通道
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        //consumer消费完一条信息后producer才能发送。prefetch
        channel.basicQos(1);
        //声明要消费的队列【参数说明:参数一:队列名称,参数二:是否持久化;参数三:是否独占模式;参数四:消费者断开连接时是否删除队列;参数五:消息其他参数】
        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 message = new String(body, "UTF-8");
                System.out.println(" [x] Received '" + message + "'");
            }
        };
        //【参数说明:参数一:队列名称,参数二:ack,表示消费者接受完参数mq才能删除消息;参数三:消费者回调函数】
        channel.basicConsume(QUEUE_NAME, true, consumer);
    }
}
  2.topic模式

exchange类型为:fanout交换器
在这里插入图片描述
生产者


import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

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

/**
 * @Auther: cpb
 * @Date: 2019/1/24 16:01
 * @Description:
 */
public class Producer {
    private static final String EXCHANGE_NAME = "logs";

    public static void main(String[] argv) {

        try {
            ConnectionFactory factory = new ConnectionFactory();
            factory.setHost("localhost");
            Connection connection = factory.newConnection();
            Channel channel = connection.createChannel();
            //exchange:交换机名称,type:类型,durable:消息是否启用持久化,autoDelete:是否自动删除,internal,argument
            channel.exchangeDeclare(EXCHANGE_NAME, "fanout");

            String message = "测试topic模式";
            //exchange:交换机名称,routing :路由键,
            channel.basicPublish(EXCHANGE_NAME, "", null, message.getBytes());
            System.out.println(" [x] Sent '" + message + "'");

            channel.close();
            connection.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }
}

消费者

import com.rabbitmq.client.*;

import java.io.IOException;


/**
 * @Auther: cpb
 * @Date: 2019/1/24 15:53
 * @Description:
 */
public class Customer {
    private static final String EXCHANGE_NAME = "logs";

    public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        //声明交换机名称及其类型
        channel.exchangeDeclare(EXCHANGE_NAME, "fanout");
        //创建随机队列名称
        String queueName = channel.queueDeclare().getQueue();
        //绑定交换机和队列之间的关系;destination:队列名称,source:交换机名称,routing:路由键,map:arguments
        channel.queueBind(queueName, EXCHANGE_NAME, "");

        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 + "'");
            }
        };
        channel.basicConsume(queueName, true, consumer);
    }
}
  3.routing模式

exchange类型:direct交换器
在这里插入图片描述
生产者

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

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

/**
 * @Auther: cpb
 * @Date: 2019/1/24 16:01
 * @Description:
 */
public class Producer {
    private static final String EXCHANGE_NAME = "direct_logs";

    public static void main(String[] argv) {
        try {
            ConnectionFactory factory = new ConnectionFactory();
            factory.setHost("localhost");
            Connection connection = factory.newConnection();
            Channel channel = connection.createChannel();

            channel.exchangeDeclare(EXCHANGE_NAME, "direct");

            String routing = "delete";
            String message = "测试 delete";

            String routing1 = "insert";
            String message2 = "测试 insert";
            channel.basicPublish(EXCHANGE_NAME, routing, null, message.getBytes());
            System.out.println(" [x] Sent '" + routing + "':'" + message + "'");
            channel.basicPublish(EXCHANGE_NAME, routing1, null, message2.getBytes());
            System.out.println(" [x] Sent '" + routing1 + "':'" + message2 + "'");

            channel.close();
            connection.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }
}

消费者

//消费者1
public class Customer1 {
    private static final String EXCHANGE_NAME = "direct_logs";

    public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        //随机生成队列名称
        String queueName = channel.queueDeclare().getQueue();
        //声明交换机名称和类型
        channel.exchangeDeclare(EXCHANGE_NAME, "direct");
        //绑定插入队列
        channel.queueBind(queueName,EXCHANGE_NAME,"insert");
        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 '" + envelope.getRoutingKey() + "':'" + message + "'");
            }
        };
        channel.basicConsume(queueName, true, consumer);
    }
}


//消费者2
public class Customer2 {
    private static final String EXCHANGE_NAME = "direct_logs";

    public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        //随机生成队列名称
        String queueName = channel.queueDeclare().getQueue();
        //声明交换机名称和类型
        channel.exchangeDeclare(EXCHANGE_NAME, "direct");
        //绑定删除队列
        channel.queueBind(queueName,EXCHANGE_NAME,"delete");


        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 '" + envelope.getRoutingKey() + "':'" + message + "'");
            }
        };
        channel.basicConsume(queueName, true, consumer);
    }
}

  4.topics模式

exchange类型:topic交换器
在这里插入图片描述
生产者

public class Producer {

    private static final String EXCHANGE_NAME = "topic_logs";

    public static void main(String[] args) throws IOException {
        try {
            ConnectionFactory factory = new ConnectionFactory();
            // 设置MabbitMQ所在主机ip或者主机名
            factory.setHost("localhost");            //factory.setUsername("lp");//factory.setPassword("");// factory.setPort(2088);
            // 创建一个连接
            Connection connection = factory.newConnection();
            // 创建一个频道
            Channel channel = connection.createChannel();
            channel.exchangeDeclare(EXCHANGE_NAME, "topic");

            String routingKey = "fruit.colour";
            String message = "Hello orange and black ";

            String routingKey1 = "animal.colour";
            String message1 = "Hello black and rabbit ";

            String routingKey2 = "animal";
            String message2 = "Hello rabbit";



            channel.queueDeclare(routingKey, false, false, false, null);
            channel.basicPublish(EXCHANGE_NAME, routingKey, null, message.getBytes());
            System.out.println(" 消息队列信息:" + message );

            channel.queueDeclare(routingKey1, false, false, false, null);
            channel.basicPublish(EXCHANGE_NAME, routingKey1, null, message1.getBytes());
            System.out.println(" 消息队列信息:" + message1 );

            channel.queueDeclare(routingKey2, false, false, false, null);
            channel.basicPublish(EXCHANGE_NAME, routingKey2, null, message2.getBytes());
            System.out.println(" 消息队列信息:" + message2 );





            // 关闭频道和连接
            channel.close();
            connection.close();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }
}

消费者

//消费者1
public class Customer1 {
    private static final String EXCHANGE_NAME = "topic_logs";

    public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        //随机生成队列名称
        String queueName = channel.queueDeclare().getQueue();
        //声明交换机名称和类型
        channel.exchangeDeclare(EXCHANGE_NAME, "topic");
        //绑定插入队列
        channel.queueBind(queueName,EXCHANGE_NAME,"animal");
        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 '" + envelope.getRoutingKey() + "':'" + message + "'");
            }
        };
        channel.basicConsume(queueName, true, consumer);
    }
}


//消费者2

public class Customer2 {
    private static final String EXCHANGE_NAME = "topic_logs";

    public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        //随机生成队列名称
        String queueName = channel.queueDeclare().getQueue();
        //声明交换机名称和类型
        channel.exchangeDeclare(EXCHANGE_NAME, "topic");
        //绑定删除队列
        channel.queueBind(queueName,EXCHANGE_NAME,"*.colour");


        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 '" + envelope.getRoutingKey() + "':'" + message + "'");
            }
        };
        channel.basicConsume(queueName, true, consumer);
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值