现在SpringBoot那么好用,使用SpringBoot只需要简单的配置就可以继承消息队列。但是也正是由于SpringBoot太方便了,不能很好的体验RabbitMQ处理消息的整个流程。所以还是先选择了 Spring 来尝试。下面来说说我遇到的问题:
参考博客:https://www.jianshu.com/p/7032cbe79951
项目源码:https://gitee.com/ZCF1024/SpringRabbitMQ.git
代码就不贴了,直接是参考博客中的代码,需要源码的朋友上面有我的 Gitee 项目地址
错误1:
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
这个其实也不算是错误吧,只不过是日志功能没有配置好。你可以选择关闭日志功能,但是强迫症的我就必须给他配好,只需要在 pom 文件中加上这两个依赖就 OK 了
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.27</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.5</version>
</dependency>
错误2:
java.io.IOException
at com.rabbitmq.client.impl.AMQChannel.wrap(AMQChannel.java:129)
at com.rabbitmq.client.impl.AMQChannel.wrap(AMQChannel.java:125)
at com.rabbitmq.client.impl.AMQConnection.start(AMQConnection.java:375)
at com.rabbitmq.client.impl.recovery.RecoveryAwareAMQConnectionFactory.newConnection(RecoveryAwareAMQConnectionFactory.java:64)
at com.rabbitmq.client.impl.recovery.AutorecoveringConnection.init(AutorecoveringConnection.java:156)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:1106)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:1063)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:1021)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:1182)
at com.example.rabbitmq.MsgProducer.publicMsg(MsgProducer.java:22)
at com.example.rabbitmq.Operator.publishMsg(Operator.java:16)
at com.example.rabbitmq.Operator.main(Operator.java:27)
Caused by: com.rabbitmq.client.ShutdownSignalException: connection error
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:502)
at com.rabbitmq.client.impl.AMQConnection.start(AMQConnection.java:317)
... 9 more
看异常提示可以看出是连接异常,这里可能是两种原因导致的:
1. rabbitmq没有给代码中用于发送消息的用户授权,通过以下步骤进行授权
2. 代码中的端口填错,端口号用了15672,这是 RabbitMQ 后台管理页面的端口号。应该使用 5672 。
package com.example.rabbitmq;
import com.rabbitmq.client.ConnectionFactory;
/**
* @Author zcf
* @Create 2019/9/4 22:14
* @Desc
*/
public class RabbitMQUtil {
public static ConnectionFactory getConnectionFactory() {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("192.168.137.9");
factory.setPort(5672);
factory.setUsername("admin");
factory.setPassword("admin");
factory.setVirtualHost("/");
return factory;
}
}