rabbitMQ的简单使用

一、rabbitMQ的初相识

生产端代码

` public void testSendMessage() throws IOException, TimeoutException {

    //创建连接mq的连接工厂对象
    ConnectionFactory connectionFactory = new ConnectionFactory();
    //设置连接mq主机和端口号
    connectionFactory.setHost("127.0.0.1");
    connectionFactory.setPort(5672);
    //设置访问虚拟主机和用户名和密码
    connectionFactory.setVirtualHost("ems");
    connectionFactory.setUsername("ems");
    connectionFactory.setPassword("123");
    //获取连接对象
    Connection connection = connectionFactory.newConnection();
    //获取连接中通道
    Channel channel =  connection.createChannel();
    //通道绑定对应消息队列
    //参数1:队列名称 如果队列不存在自动创建
    //参数2:用来定义队列特性是否要持久化 true 持久化队列
    //参数3:exclusive 是否独占队列
    //参数4:autoDelete 是否在消费完成后自动删除队列
    //参数5:额外附加参数
    channel.queueDeclare("hello",true,false,false,null);

    //发布消息
    //参数1:交换机名称  参数2:队列名称 参数3:传递消息的额外设置 (可以这是持久化) 参数4:消息具体内容
    channel.basicPublish("","hello", MessageProperties.PERSISTENT_TEXT_PLAIN,"hello rabbitmq!".getBytes());

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

}`

消费端代码

`public static void main(String[] args) throws IOException, TimeoutException {
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost("127.0.0.1");
connectionFactory.setPort(5672);
connectionFactory.setVirtualHost("ems");
connectionFactory.setUsername("ems");
connectionFactory.setPassword("123");
Connection connection = connectionFactory.newConnection();
//创建通道
Channel channel = connection.createChannel();
//绑定通道对象
channel.queueDeclare("hello",false,false,false,null);
//消费消息
//参数1:队列名称
//参数2:开始消息的自动确认机制
//参数3:消费时的回调接口
channel.basicConsume("hello", true, new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("hello:"+ new String(body) );
}
});

    channel.close();
    connection.close();
}`
posted @ 2021-04-15 08:53  大司徒  阅读(81)  评论(0编辑  收藏  举报