1.首先理解下rabbitmq的基础概念(exchange和queue的关系):
2.然后登陆服务器的rabbitmq管理页面:http://localhost:15672/#/
在管理页面新建exchange和绑定queue(虽然在程序中也可以):
RabbitMQ 在 web 页面 创建 exchange, queue, routing key - huanggy - 博客园
3.新增rabbitmq配置文件,在yml或者properties里配置rabbitmq的登录信息:
package payment.utils.rabbitMq.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.SerializerMessageConverter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
@Configuration
public class RabbitMqParamConfig {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
//初始化参数类
@Value("${rabbitmq_host}")
private String host;
@Value("${rabbitmq_port}")
private int port;
@Value("${rabbitmq_username}")
private String username;
@Value("${rabbitmq_password}")
private String password;
//创建交换机 topic 模式
public static final String EXCHANGE_A = "exchange_A";
//创建队列
//1.与日志服务交互队列
public static final String QUEUE ="queue_notify";
//routingKey
public static final String ROUTINGKEY_A = "spring-boot-routingKey_A.#";
@Bean
public CachingConnectionFactory connectionFactory() {
CachingConnectionFactory connectionFactory = new CachingConnectionFactory(host, port);
connectionFactory.setUsername(username);
connectionFactory.setPassword(password);
connectionFactory.setVirtualHost("/");
connectionFactory.setPublisherConfirms(true);
return connectionFactory;
}
//必须是prototype类型
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public RabbitTemplate rabbitTemplate() {
logger.info("开始构建RabbitTemplate");
RabbitTemplate template = new RabbitTemplate(connectionFactory());
template.setMandatory(true);
template.setMessageConverter(new SerializerMessageConverter());
return template;
}
}
4.在pom文件里新增必要依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
</dependency>
注意,若项目为springboot1.0的话,启动会报错
下面是我遇到的三个报错:
Could not autowire. No beans of 'RabbitTemplate' type found.
java.lang.ClassNotFoundException: com.rabbitmq.client.QueueingConsumer$Delivery
java.lang.ClassNotFoundException: com.rabbitmq.client.ShutdownListener
这是因为pom里没有指定rabbitmq的版本导致的:
那版本是多少呢?点开spring-boot-starter-amqp,再点开spring-rabbit
可见需要的版本为3.5.7,加上对应版本即可
最后附上rabbit发送方代码:
CorrelationData correlationId = new CorrelationData(UUID.randomUUID().toString().replaceAll("-", "").toUpperCase());
rabbitTemplate.convertAndSend(EXCHANGE_A, ROUTINGKEY_A, jsonStr, correlationId);