- 引入依赖:
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>3.4.1</version>
</dependency>
- 创建连接工具类
/**
* 连接rabbitMQ的工具类,正式生产环境中不会用到
* 仅测试MQ时使用,本项目以springboot的方式整合了rabbitMQ
*
* @author hetao
* @Date 2019-03-03
*/
public class RabbitConnectUtils {
private static final String HOST = "127.0.0.1";
private static final String USERNAME = "admin";
private static final String PASSWORD = "admin";
private static final String V_HOST = "v_host";
private static final Integer PORT = 5672;
/**
* 获取connection对象
*
* @return Connection
*/
public static Connection getRabbitConnection() throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost(HOST);
factory.setPort(PORT);
factory.setUsername(USERNAME);
factory.setPassword(PASSWORD);
factory.setVirtualHost(V_HOST);
return factory.newConnection();
}
}
- 写一个controller用于发送消息:
@RestController
@RequestMapping("rabbit")
public class RabbitServiceController extends BaseController {
private static final String HELLO_QUEUE = "hello_queue";
/**
* netty服务器端的第一个实践
* 相当于helloworld
* @return
*/
@RequestMapping("hello")
public ResultMsgInfo netty1(String message){
try{
Connection connection = RabbitConnectUtils.getRabbitConnection();
Channel channel = connection.createChannel();
//声明队列
channel.queueDeclare(HELLO_QUEUE,false,false,false,null);
channel.basicPublish("",HELLO_QUEUE,null,message.getBytes());
logger.info("发送消息到队列:{},消息内容:{}.",HELLO_QUEUE,message);
channel.close();
connection.close();
}catch (Exception e){
e.printStackTrace();
return ResultMsgInfo.error();
}
return ResultMsgInfo.success();
}
}
查看rabbitMQ管理界面:
发现队列已经被发布
- 队列消费:
将消费消息写到andromeda工程中,
/**
* 简单直接的循环
*/
public void getRabbitMessage(){
logger.info("消息监听器初始化成功");
try{
Connection connection = RabbitConnectUtils.getRabbitConnection();
Channel channel = connection.createChannel();
// 声明队列
channel.queueDeclare(HELLO_QUEUE, false, false, false, null);
// 定义队列的消费者
QueueingConsumer consumer = new QueueingConsumer(channel);
// 监听队列
channel.basicConsume(HELLO_QUEUE, true, consumer);
// 获取消息
while (true) {
QueueingConsumer.Delivery delivery = consumer.nextDelivery();
String message = new String(delivery.getBody());
System.out.println(" [x] Received '" + message + "'");
}
}catch (Exception e){
e.printStackTrace();
}
}
控制台打印:
[x] Received '我是rabbit直接队列' [x] Received '我是rabbit直接队列223'