java中怎么发布_如何使用Java将消息发布到EMS主题

我通过修改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解决方案将支持内置的连接池.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值