我通过修改EMS 8.0“sample”文件夹中的“tibjmsMsgProducer.java”创建了以下代码.查看此文件夹中的所有Java示例以获取进一步的参考.
此代码使用默认用户和密码将简单的硬编码文本消息发布到本地EMS.目标主题是“topic1”(在最后一行).
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
public class tibjmsMsgTopicProducer {
static String serverUrl = "localhost";
static String userName = "admin";
static String password = "admin";
public static void sendTopicMessage(String topicName, String messageStr) {
Connection connection = null;
Session session = null;
MessageProducer msgProducer = null;
Destination destination = null;
try {
TextMessage msg;
System.out.println("Publishing to destination '" + topicName
+ "'\n");
ConnectionFactory factory = new com.tibco.tibjms.TibjmsConnectionFactory(
serverUrl);
connection = factory.createConnection(userName, password);
/* create the session */
session = connection
.createSession(javax.jms.Session.AUTO_ACKNOWLEDGE);
/* create the destination */
destination = session.createTopic(topicName);
/* create the producer */
msgProducer = session.createProducer(null);
/* publish messages */
/* create text message */
msg = session.createTextMessage();
/* set message text */
msg.setText(messageStr);
/* publish message */
msgProducer.send(destination, msg);
System.out.println("Published message: " + messageStr);
/* close the connection */
connection.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
/*-----------------------------------------------------------------------
* main
*----------------------------------------------------------------------*/
public static void main(String[] args) {
tibjmsMsgTopicProducer.sendTopicMessage("topic1",
"This is the message content !");
}
}
注意:您还可以使用EMS with Spring-JMS来获得更多“企业级”解决方案.上面的代码更简单.
注2:我把方法设为“静态”.这仅用于演示目的. JMS中的连接成本很高,因此通常我们会尝试重用它们.有关更好地设置Java类的信息,请参阅所有TIBCO提供的示例.如果可以,实例化并重用连接.此外,J2EE或Spring解决方案将支持内置的连接池.