public void send(TextMessage msgText){
Connection connection = null;
try {
InitialContext ctx = new InitialContext();
ConnectionFactory factory = (ConnectionFactory) ctx.lookup("jndi/jmsConn");
connection = factory.createConnection();
Destination dest = (Destination) ctx.lookup("jndi/dest");
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer sender = session.createProducer(dest);
sender.send(msgText);
} catch (NamingException e) {
e.printStackTrace();
} catch (JMSException e) {
e.printStackTrace();
} finally{
try {
connection.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
}
1.6 接收消息
同步接收:MessageConsumer#receive(),当目标地址中没有消息时,主程序阻塞,也可以设定超时时间。
异步接收:向MessageConsumer注册一个MessageListener,在注册之前必须先将Connection启动,Connection#start(),MessageConsumer#setMessageListener(this)。
void onMessage(Message message);
Note:发送或接收完消息,必须断开连接!
2. 消息重复接收问题
问题:客户端接收地址消息-->MOM因故障关闭-->客户端发送回执消息失败-->MOM重启-->客户端再次接收同一条消息
Solution1:采用JTA全局事务,将数据库操作和JMS操作纳入到同一个全局事务,但这也性能影响很大;
Solution2:客户端自身提供消息重复性检查功能,接收消息后进行消息处理的逻辑仅工作在本地数据源事务中。