/java/

ActiveMQ - Java - Publish and Subscribe / JMS - first touch

2016-07-12 23:28:57

To start with ActiveMQ / JMS you have to have ActiveMQ sever on your local computer.

To do that: 1. goto http://activemq.apache.org/download.html 2. download last version (for this example 5.13.3) 3. untar package wherever you want 4. goto bin directory and execute this command: (if you don't see any warnings or errors then you can assume that everything is ok)

/apache-activemq-5.13.3/bin$ ./activemq start
  1. to test if everything go well, please open http://127.0.0.1:8161/

Time for java. Publish-and-Subscribe model

With code below you will create simple java / subscriber program

pom.xml

<?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?>

<project http:="" maven-4.0.0.xsd&quot;="" maven.apache.org="" xmlns='"http://maven.apache.org/POM/4.0.0"' xmlns:xsi='"http://www.w3.org/2001/XMLSchema-instance"' xsd="" xsi:schemalocation='"http://maven.apache.org/POM/4.0.0'>
    <modelversion>4.0.0</modelversion>
    <groupid>pl.btbw</groupid>
    <artifactid>jms_example_1</artifactid>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupid>org.apache.activemq</groupid>
            <artifactid>activemq-all</artifactid>
            <version>5.13.3</version>
        </dependency>
    </dependencies>
</project>

Subscriber.java

package pl.btbw;

import javax.jms.*;
import javax.naming.InitialContext;

public class Subscriber implements MessageListener {

    public static void main(String[] args) {
        new Subscriber("RedTopic", "someTopicName");
    }

    public Subscriber(String topicFactory, String topicName) {
        try {

            InitialContext ctx = new InitialContext();

            TopicConnectionFactory connectionFactory = (TopicConnectionFactory) ctx.lookup(topicFactory);

            Topic chatTopic = (Topic) ctx.lookup(topicName);

            TopicConnection topicConnection = connectionFactory.createTopicConnection();

            TopicSession subscriberSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);

            TopicSubscriber subscriber = subscriberSession.createSubscriber(chatTopic, null, true);

            subscriber.setMessageListener(this);

            topicConnection.start();

        } catch (Exception e) {
            // this is sooo bad!
            e.printStackTrace();
        }
    }

    public void onMessage(Message message) {
        try {
            TextMessage textMessage = (TextMessage) message;
            System.out.println(textMessage.getText());
        } catch (JMSException e) {
            // this is sooo bad!
            e.printStackTrace();
        }
    }
}

/src/main/resources/jndi.properties

java.naming.factory.initial = org.apache.activemq.jndi.ActiveMQInitialContextFactory
java.naming.provider.url = tcp://localhost:61616
java.naming.security.principal = system
java.naming.security.credentials = manager

connectionFactoryNames = RedTopic
topic.someTopicName = jms.someTopicName

The Subscriber class includes a main() method for testing purpose. So you can run this class as standalone Java application.

java pl.btbw.Subscriber

Test

if ActiveMQ server and "Subscriber" app are running, you can goto http://127.0.0.1:8161/admin/topics.jsp page, next chooses "jms.someTopicName" topic, and by the page that will apper send the message

Test 2

Ok I have to admit, test by external panel is sad.** What we can do ? We can prepare simple Publisher program

Publisher.java

package pl.btbw;

import javax.jms.*;
import javax.naming.InitialContext;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Publisher {

    private TopicConnection topicConnection;
    private TopicSession publisherSession;
    private TopicPublisher publisher;

    public static void main(String[] args) {
        try {

            Publisher publisher = new Publisher("RedTopic", "someTopicName");

            BufferedReader commandLine = new java.io.BufferedReader(new InputStreamReader(System.in));

            while (true) {

                String s = commandLine.readLine();

                if (s.equalsIgnoreCase("exit")) {
                    publisher.close();
                    System.exit(0);
                } else {
                    publisher.writeMessage(s);
                }
            }

        } catch (Exception e) {
            // this is sooo bad!
            e.printStackTrace();
        }
    }

    public Publisher(String topicFactory, String topicName) {

        try {
            InitialContext ctx = new InitialContext();

            TopicConnectionFactory connectionFactory = (TopicConnectionFactory) ctx.lookup(topicFactory);

            this.topicConnection = connectionFactory.createTopicConnection();

            this.publisherSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);

            Topic chatTopic = (Topic) ctx.lookup(topicName);

            this.publisher = publisherSession.createPublisher(chatTopic);

            topicConnection.start();

        } catch (Exception e) {
            // this is sooo bad!
            e.printStackTrace();
        }
    }

    public void writeMessage(String text) throws JMSException {
        TextMessage message = publisherSession.createTextMessage();
        message.setText(text);
        publisher.publish(message);
    }

    public void close() throws JMSException {
        topicConnection.close();
    }
}

The Publisher class includes a main() method for testing purpose. So you can run this class as standalone Java application and type some message into a console. Your message should appear in the window where you opened Subscriber app

Appendix A

if you are not a big fan of jndi.properties file, you can remove that file and configure your InitialContext by

package pl.btbw;

import javax.naming.Context;
import java.util.Properties;

public class PropertiesUtil {

    public static Properties getNoFileProperties() {
        Properties properties = new Properties();
        properties.put(Context.SECURITY_PRINCIPAL, "system");
        properties.put(Context.SECURITY_CREDENTIALS, "manager");
        properties.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.activemq.jndi.ActiveMQInitialContextFactory");
        properties.put(Context.PROVIDER_URL, "tcp://localhost:61616");

        properties.put("connectionFactoryNames", "RedTopic");
        properties.put("topic.someTopicName", "jms.someTopicName");

        return properties;
    }

}
InitialContext ctx = new InitialContext(PropertiesUtil.getNoFileProperties());

GIT