Write to JMS Queue

Updated: Jun 30, 2023

This example writes a list of records to a Java Message Service (JMS) queue. It provides an interface to stream records to a JMS queue for further processing or distribution.

When integrating multiple systems or applications, a common approach is to use message queues for exchanging data in a decoupled manner. This library facilitates the writing of data records to a JMS queue, making it useful for scenarios where data needs to be efficiently shared or synchronized between different systems.

 

Java Code

package com.northconcepts.datapipeline.examples.cookbook;

import java.util.Properties;

import javax.naming.Context;

import com.northconcepts.datapipeline.core.DataWriter;
import com.northconcepts.datapipeline.core.Record;
import com.northconcepts.datapipeline.core.RecordList;
import com.northconcepts.datapipeline.jms.JmsDestinationType;
import com.northconcepts.datapipeline.jms.JmsSettings;
import com.northconcepts.datapipeline.jms.JmsWriter;
import com.northconcepts.datapipeline.job.Job;
import com.northconcepts.datapipeline.memory.MemoryReader;

public class WriteToJmsQueue {
    
    // run activemq before running the code below
    public static void main(String[] args) {
        Record record = new Record();
        record.setField("Team", "Manchester United");
        record.setField("Points", 90);
        
        RecordList recordList = new RecordList(record);
        MemoryReader memoryReader = new MemoryReader(recordList);
        
        Properties props = new Properties();
        props.setProperty(Context.INITIAL_CONTEXT_FACTORY,"org.apache.activemq.jndi.ActiveMQInitialContextFactory");
        props.setProperty(Context.PROVIDER_URL,"tcp://localhost:61616");
        
        DataWriter writer = new JmsWriter(new JmsSettings("premierLeague", JmsDestinationType.QUEUE, props));
        Job.run(memoryReader, writer);
    }

}

 

Code Walkthrough

  1. A new Record with two fields (Team, Points) is created and added to the RecordList.
  2. To read the RecordList, a new MemoryReader is instantiated.
  3. New Java Properties are declared with an Apache ActiveMQ INITIAL_CONTEXT_FACTORY and an ActiveMQ PROVIDER_URL pointing to localhost.
  4. A new DataWriter has been defined as a JmsWriter, which accepts JmsSettings with the properties defined above and a JmsDestinationType.QUEUE.
  5. The Job.run(reader, writer) method has been executed with the reader and writer defined above.

 

Output

If ActiveMQ is running on the PROVIDER_URL configured in this example, then it should receive the message.

Mobile Analytics