I wrote a Publisher class in java in order to send messages over a topic.
package com.jms.jms_ps;
import java.util.Properties;
import javax.naming.*;
import javax.jms.*;
/**
*
* @author achref
*/
public class Publisher {
Context ctx;
TopicConnectionFactory connectionFactory;
Topic topic;
TopicConnection connection;
TopicSession session;
TopicPublisher publisher;
Publisher() throws NamingException{
Properties props = new Properties();
props.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.activemq.jndi.ActiveMQInitialContextFactory");
props.setProperty(Context.PROVIDER_URL, "tcp://localhost:61616");
ctx = new InitialContext(props);
connectionFactory = (TopicConnectionFactory) ctx.lookup("ConnectionFactory");
topic = (Topic) ctx.lookup("dynamicTopics/myTopic");
}
void sendTextMessage(String msg) throws JMSException{
connection = connectionFactory.createTopicConnection();
session = connection.createTopicSession(true, 0);
publisher = session.createPublisher(topic);
TextMessage message = session.createTextMessage();
message.setText(msg);
connection.start();
publisher.publish(message);
connection.close();
}
}
The problem is every time I try to send a message it doesn't add to my topic (Messages Enqueued
is equal to zero) and therefore a subscriber receives nothing.
ActiveMQ console
CodePudding user response:
You are sending a message in a transacted mode, but not committing the transaction. Ack mode = 0 is Session.TRANSACTED. You need to invoke session.commit() to permit the broker to deliver messages to the topic, or choose a different Acknowledgement mode for your use case.