Showing posts with label easy. Show all posts
Showing posts with label easy. Show all posts

Thursday, October 29, 2015

Super Simple Example of Spring JMS - Producer

Step 1: You need Jar files:

A. Spring core, spring-context
B. Spring JMS
C. activemq-all 
D. slf4j , log4j etc.


Step 2: Create a Java Project in Eclipse and add "applicationContext.xml" File directly under "src" folder:

applicationContext.xml :

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:jms="http://www.springframework.org/schema/jms"
       xmlns:amq="http://activemq.apache.org/schema/core"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
                           http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context 
                           http://www.springframework.org/schema/context/spring-context.xsd
                           http://www.springframework.org/schema/jms 
                           http://www.springframework.org/schema/jms/spring-jms.xsd
                           http://activemq.apache.org/schema/core 
                           http://activemq.apache.org/schema/core/activemq-core.xsd">

<context:component-scan base-package="com.itech" />
<context:annotation-config/>

<!-- JMS ConnectionFactory to use, configuring the embedded broker using XML -->
<bean id="activemqConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
    <!-- brokerURL, You may have different IP or port -->
    <constructor-arg name="brokerURL" value="vm://localhost:61616" />
  </bean>  

<!-- Pooled Spring connection factory -->
 <bean id="connectionFactory" class="org.springframework.jms.connection.CachingConnectionFactory">
    <constructor-arg ref="activemqConnectionFactory" />
 </bean>

<!--  Queue Destination  -->
    <bean id="queueDestination" class="org.apache.activemq.command.ActiveMQQueue">
    <!-- name of the queue -->
    <constructor-arg index="0" value="THIS.IS.TEST.QUEUE" />
  </bean>

  <!-- JmsTemplate Definition -->
  <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
    <property name="connectionFactory" ref="connectionFactory" />
    <property name="defaultDestination" ref="queueDestination" />
  </bean>

</beans>


Have a look at XML, it has almost everything you need to start with: - ConnectionFactory, Destination and Spring Provides JmsTemplate which we will be using to send the message.

Step 3: Create Test Class:

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;

public class ProducerTest {

public static void main(String[] args) {
// Load Application Context 
   ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
  
            // Get JmsTemplate Bean from context     
   JmsTemplate template = (JmsTemplate) ctx.getBean("jmsTemplate");
 
           // Create Message 
   MessageCreator message = new MessageCreator() {
@Override
public Message createMessage(Session session) throws JMSException {
return session.createTextMessage("This is test message");
}
};

              // Send the message
template.send(message);

              // Close the context
((ClassPathXmlApplicationContext)ctx).close();
// You are Done!!
}

}

That's it. You are Done! You have written  a complete code in SpringJMS for sending a message.
Thanks!




Monday, May 14, 2012

Sending a Message to Queue (JMS Way)

There are thousand confusing ways to send a message to queue and every method looks correct and perfect for production implemetation.
Below is simple method which is used most of the time and also JMS API Complient. Benefit of using JMS Complient provider is: your code will remain unchanged even if provider changes.  But yes, you have to make sure about you exception handling mechanism and your queue access.

Steps are explained below:
1. Get the ConnectionFactory from JNDI
2. Create Connection from Connection Factory
3. Get the destination from JNDI or Create Destination
3. Create a Session from Connection
4. Create a Message Producer from Session using Destination
5. Create a Message from Session
6. Send the message using message producer.
7. Close the mess.
8. Check the queue depth - Not in Java (using queue browsing tools)



package com.xyz;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class SampleMessageSender
{
private String jndiQCFName = null;
private ConnectionFactory factory = null;
public SampleMessageSender(String jndiQCFName){
this.jndiQCFName = jndiQCFName;
}
public void sendMessage(String jndiDestination, String messagePayload)
throws NamingException
{
InitialContext context = null;
MessageProducer producer =  null;
Connection connection = null;
Session session = null;
try
{
context = new InitialContext();
factory = (ConnectionFactory) context.lookup("java:comp/env/"+jndiQCFName);
Destination destination = (Destination) context.lookup("java:comp/env/"+jndiDestination);
connection = factory.createConnection();
session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
// Create a Producer for this Destination
producer = session.createProducer(destination);
// Create a Message from Payload
Message message = session.createTextMessage(messagePayload);
// Send the message
producer.send(message);
}
catch(JMSException exe)
{
exe.printStackTrace();
// Do logging
if(exe.getLinkedException() != null){
// Linked exception may have provider specific details. Log it.
exe.getLinkedException().printStackTrace();
}
}
finally{
context.close();
try {
producer.close();
session.close();
connection.close();
} catch (JMSException e) {
// Nothing can be done here
e.printStackTrace();
}
}
}
}