Java Message Service (JMS)

Java message service is pretty good to send message to another. its maintain a queue and when any message stay in that queue, the publisher immediately publish the message. From the EJB (Enterprise Java Beans) context, generally JMS is used for distributed asynchronous computing. Also its can be used for debugging, web chat service for customer and the provider etc. here i used it for doing logging for web service operation. the response can not wait for log write rather response return to the user and the log message sent to the HornetQ (a message Queue). then log will insert to database.
Here i used JPA for query and Bean managed transaction. necessary tools given below,

1) JBoss-eap-6.2 or 7
2) MySql DB.

here is the project structure.




first we need to add the HornetQ module and for this make a xml file say named "hornetq-jms.xml"
and put the code here. put the xml file in META-INF folder in your class path.


 <?xml version="1.0" encoding="UTF-8"?>  
 <messaging-deployment xmlns="urn:jboss:messaging-deployment:1.0">  
   <hornetq-server>  
     <jms-destinations>  
       <jms-queue name="HornetQueue">  
         <entry name="queue/HornetQueue"/>  
       </jms-queue>        
     </jms-destinations>  
   </hornetq-server>  
 </messaging-deployment>  

suppose i have a EJB method something like below,


1:       @SuppressWarnings("unchecked")  
2:       public List<Book> getAllBookData() {  
3:            Query query = null;  
4:            List<Book> bookList = new ArrayList<Book>();  
5:            try {  
6:                 utx.begin();  
7:                 query = entityManager.createQuery("select book from Book book");  
8:                 bookList = (List<Book>) query.getResultList();  
9:                 logging.setDescription(LogUtils.LOG_GETALL_BOOK);  
10:                 messageSender.msgSender(logging);  
11:                 //entityManager.persist(logging);  
12:                 utx.commit();  
13:            } catch (Exception e) {  
14:                 e.printStackTrace();  
15:            }  
16:            return bookList;  
17:       }  

here in the line no 10, logging information sent to messageSender. logging is an object of ActionLogBook that is look like:


1:  @Entity  
2:  @Table(name="action_log_book")  
3:  @NamedQuery(name="ActionLogBook.findAll", query="SELECT a FROM ActionLogBook a")  
4:  public class ActionLogBook implements Serializable {  
5:       private static final long serialVersionUID = 1L;  
6:       @Id  
7:       @GeneratedValue(strategy=GenerationType.IDENTITY)  
8:       private int id;  
9:       private String description;  
10:       public ActionLogBook() {  
11:       }  
12:       public int getId() {  
13:            return this.id;  
14:       }  
15:       public void setId(int id) {  
16:            this.id = id;  
17:       }  
18:       public String getDescription() {  
19:            return this.description;  
20:       }  
21:       public void setDescription(String description) {  
22:            this.description = description;  
23:       }  
24:  }  

here is the messageSender method given below,


1:  public void msgSender(ActionLogBook log) {  
2:            String destinationName = "queue/HornetQueue";  
3:            Context context = null;  
4:            ConnectionFactory connectionFactory = null;  
5:            Connection connection = null;  
6:            try {  
7:                 context = new InitialContext();  
8:  //               context = getInitialContext();  
9:                 connectionFactory = (ConnectionFactory) context  
10:                           .lookup("java:/ConnectionFactory");  
11:                 Queue queue = (Queue) context.lookup(destinationName);  
12:                 connection = connectionFactory.createConnection();  
13:                 if (connection == null)  
14:                      System.out.println(">>>>>>>>>>>>>>>>>>>>>Connection is null");  
15:                 if (queue == null)  
16:                      System.out.println(">>>>>>>>>>>>>>>>>>>>>>> Queue is null");  
17:                 if (connection != null && queue != null) {  
18:                      Session session = connection.createSession(false,  
19:                                Session.AUTO_ACKNOWLEDGE);  
20:                      MessageProducer publisher = session.createProducer(queue);  
21:                      //MessageConsumer subscriber = session.createConsumer(queue);  
22:                      connection.start();  
23:  //                    TextMessage message = session.createTextMessage(">>>>>>>>>>>>>>>>>>>>>>Hello this from sender!");  
24:                      ObjectMessage object = session.createObjectMessage();  
25:                      object.setObject(log);  
26:  //                    publisher.send(message);  
27:                      publisher.send(object);  
28:                 }  
29:            } catch (Exception e) {  
30:                 e.printStackTrace();  
31:            } finally {  
32:                 if (context != null) {  
33:                      try {  
34:                           context.close();  
35:                      } catch (Exception e) {  
36:                           e.printStackTrace();  
37:                      }  
38:                 }  
39:                 closeConnection(connection);  
40:            }  
41:       }  
42:       private void closeConnection(Connection con) {  
43:            try {  
44:                 if (con != null) {  
45:                      con.close();  
46:                 }  
47:            } catch (JMSException jmse) {  
48:                 System.out.println("Could not close connection " + con  
49:                           + " exception was " + jmse);  
50:            }  
51:       }  

remember that "destinationName" and "entry-name"(in xml file) should be same. so this is the message sender method. and for getting the message we need a message receiver method.
this class should implements MessageListener interface and it's also be a Message Driven Bean.

1:  @MessageDriven(activationConfig = {  
2:            @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"),  
3:            @ActivationConfigProperty(propertyName = "destination", propertyValue = "queue/HornetQueue") })  
4:  public class AuditSystem implements MessageListener{  
5:       @PersistenceContext(unitName = "BookReservation")  
6:       private EntityManager entityManager;  
7:       @Override  
8:       public void onMessage(Message message) {  
9:            ObjectMessage objectMessage = null;  
10:            if(message instanceof ObjectMessage){  
11:                  objectMessage = (ObjectMessage)message;  
12:            }  
13:            ActionLogBook msg = new ActionLogBook();  
14:            try {  
15:                 msg = (ActionLogBook)objectMessage.getObject();  
16:            } catch (JMSException e) {  
17:                 e.printStackTrace();  
18:            }  
19:            System.out.println("###############################the message is = "  
20:                                + msg.getDescription());  
21:            entityManager.persist(msg);  
22:       }  
23:  }  

last of all you need to add some ejb jar as per your choice or from following project screenshot.

Thanks to all.happy coding. :)

Comments

Popular posts from this blog

UUID to BigInteger conversion and BigInteger to UUID conversion

ActiveMQ message producer and consumer with durable subscriber example

Create Maven Local Repository, Upload your own artifact & download jar from local mirror with Artifactory and Nexus OSS