Domanda

Hi I have created the below class to read messages off a jibco jms queue. In a different class I create an instance of this class and try to getMessage() into a stirng. I have placed a message in the queue, My application gets stuck as I call the getMessage() method... Any idea ? or an improvement I could add to below class?

public class EMSReceiver {

    private QueueConnection connection;
    private QueueReceiver queueReceiver;
    private Queue queue;

    private TextMessage message;

    public EMSReceiver(String initialContextFactory, String userName, String password, String serverUrl, String confact, String q){
        try {

            Properties env = new Properties();
            env.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);
            env.put(Context.SECURITY_PRINCIPAL, userName);
            env.put(Context.SECURITY_CREDENTIALS, password);
            env.put(Context.PROVIDER_URL, serverUrl);

            InitialContext jndi = new InitialContext(env);

            QueueConnectionFactory connectionFactory = (QueueConnectionFactory) jndi.lookup(confact);
            QueueConnection connection = connectionFactory.createQueueConnection(userName, password);
            QueueSession session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
            this.queue = (Queue) jndi.lookup(q);
            this.queueReceiver = session.createReceiver(queue);

            connection.start();

        }
        catch (JMSException e) {
            e.printStackTrace();
            System.exit(0);
        } catch (NamingException e) {
            e.printStackTrace();
        }
    }

    public String getMessage() throws JMSException{

        try {
            this.message = (TextMessage) queueReceiver.receive();
        } catch (JMSException e) {
            System.out.println("Could not retrieve the message.");
            e.printStackTrace();
        }
        return message.getText();

    }
È stato utile?

Soluzione

The queueReceiver.receive() method will wait till it receives a message in the queue. If you don't want to wait, use receiveNoWait() or receive(long timeout). The documentation for this can be found here: https://javaee-spec.java.net/nonav/javadocs/javax/jms/QueueReceiver.html.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top