【学习笔记】rabbitmq 简易项目搭建

本文介绍如何使用Java和Eclipse开发环境通过Maven项目与RabbitMQ进行交互。包括配置Maven依赖、创建发送与接收消息的示例代码,并解决权限错误等问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

mq安装在上一个帖子中已经结束,这次准备使用java进行一个例子的编写。
使用的时eclipse+jdk1.7

1.创建一个maven项目

1.1配置pom.xml

然后执行下载相关联的包

<dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.rabbitmq/amqp-client -->
    <dependency>
        <groupId>com.rabbitmq</groupId>
        <artifactId>amqp-client</artifactId>
        <version>4.0.3</version>
        <scope>test</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.21</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.21</version>
    </dependency>
  </dependencies>

中间遇到了一个问题

Exception in thread "main" java.io.IOException
    at com.rabbitmq.client.impl.AMQChannel.wrap(AMQChannel.java:126)
    at com.rabbitmq.client.impl.AMQChannel.wrap(AMQChannel.java:122)
    at com.rabbitmq.client.impl.AMQChannel.exnWrappingRpc(AMQChannel.java:144)
    at com.rabbitmq.client.impl.AMQConnection.start(AMQConnection.java:390)
    at com.rabbitmq.client.impl.recovery.RecoveryAwareAMQConnectionFactory.newConnection(RecoveryAwareAMQConnectionFactory.java:64)
    at com.rabbitmq.client.impl.recovery.AutorecoveringConnection.init(AutorecoveringConnection.java:99)
    at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:944)
    at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:903)
    at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:861)
    at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:1013)
    at com.mq.MqTest.main(MqTest.java:30)
Caused by: com.rabbitmq.client.ShutdownSignalException: connection error; protocol method: #method<connection.close>(reply-code=530, reply-text=NOT_ALLOWED - access to vhost '/' refused for user 'mqtest', class-id=10, method-id=40)
    at com.rabbitmq.utility.ValueOrException.getValue(ValueOrException.java:66)
    at com.rabbitmq.utility.BlockingValueOrException.uninterruptibleGetValue(BlockingValueOrException.java:36)
    at com.rabbitmq.client.impl.AMQChannel$BlockingRpcContinuation.getReply(AMQChannel.java:494)
    at com.rabbitmq.client.impl.AMQChannel.privateRpc(AMQChannel.java:288)
    at com.rabbitmq.client.impl.AMQChannel.exnWrappingRpc(AMQChannel.java:138)
    ... 8 more

需要在http://localhost:15672/#/users/mqtest 下方(mqtest是自建的用户)set 一个permissions 即可

下面贴代码

发送类:MqTestSend.java


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

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

/**    
 *      
 * 类名称:MqTestSend   
 * 类描述:发送消息    
 * 创建人:xxx    
 *     
 */
public class MqTestSend {

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

        //创建链接工厂
        ConnectionFactory connFac = new ConnectionFactory() ;  

        //默认链接的主机名,RabbitMQ-Server安装在本机,所以可以直接用127.0.0.1 
        connFac.setHost("127.0.0.1");  
        //mq用户
        connFac.setUsername("mqtest");
        //mq密码
        connFac.setPassword("123456");

        //创建链接   
        Connection conn = connFac.newConnection() ;  

        //创建信息管道  
        Channel channel = conn.createChannel() ;  

        // 创建一个名为queue01的队列,防止队列不存在   
        String queueName = "singleMessage" ;  

        //进行信息声明        1.队列名,2.是否持久化,3是否局限与链接,4不再使用是否删除,5其他的属性
        channel.queueDeclare(queueName, false, false, false, null) ; 
        String msg = "Hello World121112!_";  

        //发送消息  
        // 在RabbitMQ中,消息是不能直接发送到队列,它需要发送到交换器(exchange)中。
        // 第一参数空表示使用默认exchange,第二参数表示发送到的queue,第三参数是发送的消息是(字节数组)
        channel.basicPublish("", queueName , null , msg.getBytes());  

        System.out.println("发送  message[" + msg + "] to "+ queueName +" success!");  

        //关闭管道
        channel.close();  
        //关闭连接
        conn.close();   
    }  
}

接收类:MqTestReceive.java

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

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.ConsumerCancelledException;
import com.rabbitmq.client.QueueingConsumer;
import com.rabbitmq.client.QueueingConsumer.Delivery;
import com.rabbitmq.client.ShutdownSignalException;

/**    
 *      
 * 类名称:MqTestReceive   
 * 类描述:接受消息    
 * 创建人:xxx   
 *     
 */

public class MqTestReceive {

    public static void main(String[] args) throws IOException, ShutdownSignalException,
    ConsumerCancelledException, InterruptedException, TimeoutException {  

        // 创建链接工厂
        ConnectionFactory connFac = new ConnectionFactory() ;  

        //默认链接的主机名,RabbitMQ-Server安装在本机,所以可以直接用127.0.0.1 
        connFac.setHost("127.0.0.1");  

        //创建链接    
        Connection conn = connFac.newConnection() ;  

        //创建信息管道  
        Channel channel = conn.createChannel() ;  

        //定义Queue名称  
        String queueName = "singleMessage";  
        //1.队列名2.是否持久化,3是否局限与链接,4不再使用是否删除,5其他的属性
        channel.queueDeclare(queueName, false, false, false, null) ;  

        //上面的部分,与Test01是一样的  

        //声明一个消费者,配置好获取消息的方式  
        QueueingConsumer consumer = new QueueingConsumer(channel) ;  
        channel.basicConsume(queueName, true, consumer) ;  

        //循环获取消息  
        while(true){  

            //循环获取信息  
            //指向下一个消息,如果没有会一直阻塞
            Delivery delivery = consumer.nextDelivery() ;  

            String msg = new String(delivery.getBody()) ;    

            System.out.println("接收 message[" + msg + "] from " + queueName);  

            channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);  
        }  
    }
}

在eclipse中,QueueingConsumer显示为过时的,后续又去查询了下,意思为在3.0版本之前是正常的,后续版本进行了修改。

MqTestReceive2.java


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

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.ConsumerCancelledException;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import com.rabbitmq.client.ShutdownSignalException;

/**    
 *      
 * 类名称:MqTestReceive2   
 * 类描述:接受消息    
 * 创建人:xxx   
 *     
 */

public class MqTestReceive2 {

    public static void main(String[] args) throws IOException, ShutdownSignalException,
    ConsumerCancelledException, InterruptedException, TimeoutException {  

        // 创建链接工厂
        ConnectionFactory connFac = new ConnectionFactory() ;  

        //默认链接的主机名,RabbitMQ-Server安装在本机,所以可以直接用127.0.0.1 
        connFac.setHost("127.0.0.1");  

        //创建链接    
        Connection conn = connFac.newConnection() ;  

        //创建信息管道  
        final Channel channel = conn.createChannel() ;  

        //定义Queue名称  
        String queueName = "singleMessage";  
        //1.队列名,2.是否持久化,3是否局限与链接,4不再使用是否删除,5其他的属性
        channel.queueDeclare(queueName, 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 routingKey = envelope.getRoutingKey();//队列Queue
                 String contentType = properties.getContentType();
                 long deliveryTag = envelope.getDeliveryTag();
                 channel.basicAck(deliveryTag, false);
                 String message = new String(body, "UTF-8");
                 System.out.println("routingKey:"+routingKey+"   contentType:"+contentType+"   msg:"+message);

             }
        };

        channel.basicConsume(queueName, false,  consumer);
    }
}

剩下的如接收分发可以在参考链接的代码查看,我就部贴出来了,还会继续研究

参考
RabbitMQ的项目示例

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值