控制层
//新增队列(发送TextMessage消息)
@RequestMapping("/sendTextMessage")
@ResponseBody
public String sendTextMessage(@RequestBody String data) {
// 字符串转json
Map<String, Object> map = (Map<String, Object>) JSONObject.parse(data);
String connectionFactory = map.get("connectionFactory") + "";
Map<String, String> content = (Map<String, String>) map.get("content");
String msg=null;
try {
msg = mQQueueService.sendTextMessage(connectionFactory, content);
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return msg;
}
//消费队列(获取TextMessage消息)
@RequestMapping("/achieveTextMessage")
@ResponseBody
public String achieveTextMessage(@RequestBody String data) {
// 字符串转json
Map<String, Object> map = (Map<String, Object>) JSONObject.parse(data);
String connectionFactory = map.get("connectionFactory") + "";
String key = map.get("key")+"";
String textMessage=null;
try {
textMessage = mQQueueService.achieveTextMessage(connectionFactory, key);
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return textMessage;
}
业务层
// 发送TextMessage演示
@Override
public String sendTextMessage(String connectionFactory, Map<String, String> content) throws JMSException {
ConnectionFactory cf = new ActiveMQConnectionFactory(connectionFactory);
Connection connection = cf.createConnection();
connection.start(); //
// 创建会话(需要创建事务,消息自动确认)
Session session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
// 循环创建队列
for (String key : content.keySet()) {
log.info("=====================开始为" + key + "创建排号。");
Destination destination = session.createQueue(key);
// 创建生产者,即消息发送方。
MessageProducer producer = session.createProducer(destination);
int num = Integer.parseInt(content.get(key));
for (int i = 1; i <= num; i++) {
String no = String.format("%03d", i);
TextMessage message = session.createTextMessage(no);
System.out.println(no);
// 通过消息生产者发出消息
producer.send(message);
}
log.info("=====================已经为" + key + "创建了" + num + "排号。");
}
try {
session.commit();
} finally {
session.close();
connection.close();
}
return "SUCCESS";
}
// 获取TextMessage演示
@Override
public String achieveTextMessage(String connectionFactory, String key) throws JMSException {
ConnectionFactory cf = new ActiveMQConnectionFactory(connectionFactory);
Connection connection = cf.createConnection();
connection.start();
// 确认消息被接受
final Session session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
Destination destination = session.createQueue(key);
MessageConsumer consumer = session.createConsumer(destination);
// 获取排号
TextMessage message = (TextMessage) consumer.receive();
session.commit();
String text = message.getText();
try {
return text;
} finally {
session.close();
connection.close();
}
}
新增队列
消费队列
启动ActiveMQ后台
//初始账号:admin
//初始密码:admin
http://192.168.0.113:8161/admin