我想编写用于在任何 jms 服务器上发送消息的通用代码。所以为此我想如果我有 jndi.properties 文件,那么我们可以将服务器配置放在这个文件中,我们可以通过代码访问这个文件,但我只能为“ActiveMQ 服务器”执行此操作。现在我面临在任何其他服务器(如 glassfish 服务器或 jboss 服务器)上发送消息的问题。有人可以帮我完成这项任务。
这是我的代码:
public class Producer
{
public Producer() throws JMSException, NamingException,IOException
{
InputStream is = getClass().getResourceAsStream("my.jndi.properties");
Properties jndiParamaters = new Properties();
jndiParamaters.load(is);
Context jndi = new InitialContext(jndiParamaters);
ConnectionFactory conFactory = (ConnectionFactory) jndi.lookup("connectionFactory");
Connection connection;
connection = conFactory.createConnection();
try
{
connection.start();
Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
Destination destination = (Destination) jndi.lookup("Myqueue");
MessageProducer producer = session.createProducer(destination);
TextMessage message = session.createTextMessage("Hello World!");
producer.send(message);
System.out.println("Sent message '" + message.getText() + "'");
}
finally
{
connection.close();
}
}
public static void main(String[] args) throws JMSException
{
try
{
BasicConfigurator.configure();
new Producer();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
谢谢