Solace Topic Subscriber Hello World
In this example you will see how to connect Solace messaging server and subscribe to the topic and receiver message whenever publisher publish message on it. This could be starting point of your first Solace program on topic:
- SolaceTopicSubscriberHelloWorld.java:
package com.javahonk.solace; import java.util.concurrent.CountDownLatch; import com.solacesystems.jcsmp.BytesXMLMessage; import com.solacesystems.jcsmp.JCSMPException; import com.solacesystems.jcsmp.JCSMPFactory; import com.solacesystems.jcsmp.JCSMPProperties; import com.solacesystems.jcsmp.JCSMPSession; import com.solacesystems.jcsmp.TextMessage; import com.solacesystems.jcsmp.Topic; import com.solacesystems.jcsmp.XMLMessageConsumer; import com.solacesystems.jcsmp.XMLMessageListener; public class SolaceTopicSubscriberHelloWorld { public static void main(String args[]) throws JCSMPException { JCSMPProperties properties = new JCSMPProperties(); properties.setProperty(JCSMPProperties.HOST, "HOST"); properties.setProperty(JCSMPProperties.VPN_NAME, "VPN"); properties.setProperty(JCSMPProperties.USERNAME, "USER_NAME"); properties.setProperty(JCSMPProperties.PASSWORD, "PASSWORD"); Topic topic = JCSMPFactory.onlyInstance().createTopic("TOPIC_NAME"); JCSMPSession session = JCSMPFactory.onlyInstance().createSession(properties); CountDownLatch latch = new CountDownLatch(1); final XMLMessageConsumer cons = session.getMessageConsumer(new XMLMessageListener() { public void onReceive(BytesXMLMessage msg) { if (msg instanceof TextMessage) { System.out.printf("Message received:"+((TextMessage)msg).getText()); } else { System.out.println("Message received but its not text message"); } System.out.printf("Message details:"+msg.dump()); latch.countDown(); } public void onException(JCSMPException e) { System.out.println("Exception:"+e); latch.countDown(); } }); session.addSubscription(topic); System.out.println("Connected. Wait for message"); cons.start(); try { latch.await(); } catch (InterruptedException e) { System.out.println("I got intrrupted while waiting"); } cons.close(); session.closeSession(); } }
Reference: