1.pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
2.配置文件application.yml
#rabbitmq配置
rabbitmq:
host: #ip
port: 5672 #端口
username: #账号
password: #密码
#rabbitMQ队列名信息
queue:
name: queue_name
exchange: queue_exchange
binding: queue.key.#
3.config配置
import org.springframework.amqp.core.*;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RabbitMQConfig {
@Value("${queue.name}")
private String QUEUE_NAME1 ;
@Value("${queue.exchange}")
private String EXCHANGE_NAME;
@Value("${queue.binding}")
private String BINDING_KEY ;
// 创建队列
@Bean
public Queue createACN1Queue() {
return new Queue(QUEUE_NAME1);
}
// 创建一个 topic 类型的交换器
@Bean
public TopicExchange exchange() {
return new TopicExchange(EXCHANGE_NAME);
}
// 使用路由键(routingKey)把队列(Queue1)绑定到交换器(Exchange)
@Bean
public Binding binding1() {
return BindingBuilder.bind(createACN1Queue()).to(exchange()).with(BINDING_KEY);
}
}
4.消息生产
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@Service
public class RabbitMQSendServer {
@Autowired
private RabbitTemplate rabbitTemplate;
@Value("${queue.exchange}")
private String EXCHANGE_NAME;
@Value("${queue.binding}")
private String BINDING_KEY ;
public void topicSend(String msg) {
System.out.println("==========发送消息到交换器");
this.rabbitTemplate.convertAndSend(EXCHANGE_NAME, BINDING_KEY, msg);
}
}
5.消息消费
import com.allianz.ecallserver.websocket.EcallWebSocket;
import org.apache.log4j.Logger;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
@Component
public class RabbitMQConsumerServer {
private static Logger LOG = Logger.getLogger(RabbitMQConsumerServer.class);
//这里的队列名称要和.yml文件的queue.name一致(应用发布模式时注意)
private static final String queueName="queue_name";
@RabbitListener(queues = queueName)//这里queueName必须是常量
public void acnQueueConsumer(String message){
try {
LOG.debug("这是获取到的坐席登录ID:"+message);
} catch (Exception e) {
LOG.error("===============消费MQ消息到websocket时发生异常\n"+e);
}
}
}