使用 JAVA 在 JMS 队列中发布消息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24936259/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 15:50:20  来源:igfitidea点击:

Posting a message in JMS queue using JAVA

javajmstibcotibco-ems

提问by Ragesh Kr

I am new to JMS, after a long re search i googled out a code to connect to JMS and post a msg.

我是 JMS 的新手,经过长时间的重新搜索,我在谷歌上搜索了一个代码来连接到 JMS 并发布一条 msg。

The problem is i need to post the message in a remote queue, But i am not sure how to establish connection to it and post the message.

问题是我需要将消息发布到远程队列中,但我不确定如何与其建立连接并发布消息。

SERVER TYPE: TIBCO EMS
SERVER HOST: **.*****.net
PORT: * **USername: user
passsword: user123
Queue: *.*....Order.Management..1

服务器类型:TIBCO EMS
服务器主机**.*****.net
端口* **用户:用户
密码:user123
队列*。*. .. 。订单管理。.1

I would like to establish connection, post a simple msg and retrieve it back. Kindly help! thanks in advance

我想建立连接,发布一个简单的消息并将其取回。请帮助!提前致谢

CODE WHICH I GOT FROM INTERNET

我从互联网上得到的代码

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Hashtable;
import javax.jms.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class emm {


         // Defines the JNDI context factory.
         public final static String JNDI_FACTORY="com.tibco.tibjms.naming.TibjmsInitialContextFactory";

         // Defines the JMS context factory.
         public final static String JMS_FACTORY="jms/TestConnectionFactory";

         // Defines the queue.
         public final static String QUEUE="CPW.GBR.POR.Public.Request.Order.Management.UpdateProvisioningStatus.1";

         private QueueConnectionFactory qconFactory;
         private ConnectionFactory conFactory;
         private QueueConnection qcon;
         private QueueSession qsession;
         private QueueSender qsender;
         private Queue queue;
         private TextMessage msg;

         /**
          * Creates all the necessary objects for sending
          * messages to a JMS queue.
          *
          * @param ctx JNDI initial context
          * @param queueName name of queue
          * @exception NamingException if operation cannot be performed
          * @exception JMSException if JMS fails to initialize due to internal error
          */
         public void init(Context ctx, String queueName)
            throws NamingException, JMSException
         {

            qconFactory = (QueueConnectionFactory) ctx.lookup(JMS_FACTORY);
            qcon = qconFactory.createQueueConnection();
            qsession = qcon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
            queue = (Queue) ctx.lookup(queueName);
            qsender = qsession.createSender(queue);
            msg = qsession.createTextMessage();
            qcon.start();
         }

         /**
          * Sends a message to a JMS queue.
          *
          * @param message  message to be sent
          * @exception JMSException if JMS fails to send message due to internal error
          */
         public void send(String message) throws JMSException {
            msg.setText(message);
            qsender.send(msg);
         }

         /**
          * Closes JMS objects.
          * @exception JMSException if JMS fails to close objects due to internal error
          */
         public void close() throws JMSException {
            qsender.close();
            qsession.close();
            qcon.close();
         }
        /** main() method.
         *
         * @param args WebLogic Server URL
         * @exception Exception if operation fails
         */
         public static void main(String[] args) throws Exception {
            if (args.length != 1) {
             System.out.println("Usage: java examples.jms.queue.QueueSend WebLogicURL");
             return;
            }
            InitialContext ic = getInitialContext(args[0]);
            emm qs = new emm();
            qs.init(ic, QUEUE);
            readAndSend(qs);
            qs.close();
         }

         private static void readAndSend(emm qs)
            throws IOException, JMSException
         {
            BufferedReader msgStream = new BufferedReader(new InputStreamReader(System.in));
            String line=null;
            boolean quitNow = false;
            do {
             System.out.print("Enter message (\"quit\" to quit): \n");
             line = msgStream.readLine();
             if (line != null && line.trim().length() != 0) {
               qs.send(line);
               System.out.println("JMS Message Sent: "+line+"\n");
               quitNow = line.equalsIgnoreCase("quit");
             }
            } while (! quitNow);

         }

         private static InitialContext getInitialContext(String url)
            throws NamingException
         {
            Hashtable env = new Hashtable();
            env.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY);
            env.put(Context.PROVIDER_URL, url);
            return new InitialContext(env);
         }
        }

采纳答案by Ragesh Kr

Finally from different sources i found the best possible to way for this. This code will definitely work. I have tried this out and is running currently on my machine

最后,我从不同的来源找到了最好的方法。这段代码肯定会起作用。我已经试过了,目前正在我的机器上运行

import java.util.Properties;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueReceiver;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.*;

public class JMSExample {

    static String serverUrl = "tcp://10.101.111.101:10001"; // values changed
    static String userName = "user";
    static String password = "pwd";

     static QueueConnection connection;
     static QueueReceiver queueReceiver;
     static Queue queue;

    static TextMessage message;

    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);


            session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);



            destination = session.createQueue(topicName);


            msgProducer = session.createProducer(null);



            msg = session.createTextMessage();

            msg.setStringProperty("SourceId", userName);
            msg.setStringProperty("BusinessEvent", password);


            msg.setText(messageStr);


            msgProducer.send(destination, msg);



            System.out.println("Published message: " + messageStr);


            connection.close();

        } catch (JMSException e) {
            e.printStackTrace();
        }
    }



    public static void main(String[] args) throws JMSException {
        // TODO Auto-generated method stub

        JMSExample.sendTopicMessage("***.***.***.**.**.Order.Management.***.1",
                "Hi");
        //System.out.println(getMessage());

    }

回答by rapha?λ

As i mentioned some code for inspiration (SLIGHTLY improved your code. Not something i would want to see in production!)

正如我提到的一些灵感代码(稍微改进了你的代码。不是我想在生产中看到的东西!

// Use the domain-agnostic API
private Connection connection;ery 
private Session session;
private MessageProducer producer;
private Queue queue;

public void init(Context ctx, String queueName) {

    try {
        ConnectionFactory cnf = (QueueConnectionFactory) ctx.lookup(JMS_FACTORY);
        queue = (Queue) ctx.lookup(queueName);


        connection = cnf.createConnection("user", "user123");
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        producer = session.createProducer(queue);

        connection.start();
    } catch (NamingException e) {
        throw new RuntimeException(e);
    } catch (JMSException e) {
        throw new RuntimeException(e);
    }
}

And make your send like this (don't reuse the same Messageobject, but create a new one for each message you are sending)

并像这样发送(不要重复使用相同的Message对象,而是为您发送的每条消息创建一个新对象)

public void send(String message) throws JMSException {
    TextMessage msg = session.createTextMessage();
    msg.setText(message);
    producer.send(msg);
}

Put a try..finally around the code in your main method:

尝试..finally 围绕您的主要方法中的代码:

    try {
        readAndSend(qs);
    } finally {
        qs.close();
    }

The code you are using is not very good (understatement). It is programmed too brittle for a production system. You should not use state the way this program does.

您使用的代码不是很好(轻描淡写)。对于生产系统来说,它的编程太脆弱了。你不应该像这个程序那样使用 state。

Also there is no need to use the domain specific JMS API. You can use the domain (queue/topic) agnostic one.

也不需要使用特定于域的 JMS API。您可以使用域(队列/主题)不可知论者。

When you run the program pass in the JNDI URL for your TIBCO server.

运行程序时,请传入 TIBCO 服务器的 JNDI URL。