The principle of JMS message middleware and its application in Enterprise (ACTIVEMQ)

Source: Internet
Author: User

Code implementation: Send Message---"Accept message---" Server configuration
1 Send Message (accept reply message)
public class Sendermessageservice {
Publish the specified message to the specified address (it is recommended to save the message to the database before publishing)
public void Publish (String type, Object object) {
try {
InitialContext initctx = new InitialContext ();
1
Context Envcontext = (context) initctx.lookup ("java:comp/env");
2
ConnectionFactory connectionfactory = (connectionfactory) envcontext
. Lookup ("Jms/normalconnectionfactory");
3
Connection Connection = Connectionfactory.createconnection ();
4
Session jmssession = Connection.createsession (False,
Session.auto_acknowledge);
5,6 Destination: You need to specify its corresponding theme (subject) name
MessageProducer producer = Jmssession
. Createproducer ((Destination) Envcontext
. Lookup ("Jms/topic/mytopic"));
Set Persistence mode: Create MessageProducer objects based on destination, and set their persistent modes
Producer.setdeliverymode (deliverymode.persistent);
7
Message message = Jmssession.createmessage ();
Message.setobjectproperty (Type, object);
Topic Topic = jmssession.createtopic ("Jms/topic/mytopic");
8
Message.setjmsreplyto (topic);
Send Message
Producer.send (message);

9 message to receive a reply
Messageconsumer consumer = jmssession.createconsumer (topic);
Consumer.setmessagelistener (New MessageListener () {
public void OnMessage (message message) {
if (message! = NULL && message instanceof TextMessage) {
String messagereceived = null;
try {
messagereceived = ((textmessage) message). GetText ();
} catch (JMSException e) {
E.printstacktrace ();
}
System.out
. println ("Reply message received from Customer1:"
+ messagereceived);
}
}
});
Connection.start ();

Post Refresh post messages
Testmessage.clearproperties ();
Testmessage.setstringproperty ("Refreshthreadid", "331");
Producer.send (TestMessage);
} catch (Namingexception e) {
E.printstacktrace ();
} catch (JMSException e) {
E.printstacktrace ();
}
}
}
2 Receive Message (send reply)
Import javax.servlet.*;
Import javax.servlet.http.*;
Import javax.naming.*;
Import javax.jms.*;
Import com.brightmart.MessageAction;
Import Com.brightmart.SM;
Import Com.util.mail.TestSendMail;
Initializes a JMS connection, creates a topic listener, and specifies the corresponding processing to be made when the message is received
public class Jmslistener extends HttpServlet implements MessageListener {
Private static final long serialversionuid = 3963233366687996777L;
Initializing a JMS connection, creating a topic listener
public void init (ServletConfig config) throws servletexception {
try {
InitialContext initctx = new InitialContext ();
Context Envcontext = (context) initctx.lookup ("java:comp/env");//1
Get by Jndi
ConnectionFactory connectionfactory = (connectionfactory) envcontext
. Lookup ("jms/failoverconnectionfactory");//2
Connection Connection = Connectionfactory.createconnection ();//3
Set a ClientID for connection
Connection.setclientid ("MyClient");
Sessions: two parameters, transaction and Answer modes
Session jmssession = Connection.createsession (False,
Session.client_acknowledge);//4 Auto_acknowledge
Regular message Subscribers, unable to receive persistent messages//Messageconsumer consumer =
Jmssession.createconsumer ((Destination)//envcontext.lookup ("Jms/topic/mytopic"));
Create a persistent message subscriber based on topic, assuming: connection must specify a unique ClientID, which is currently myclient
TopicSubscriber consumer = Jmssession.createdurablesubscriber (
(Topic) envcontext.lookup ("Jms/topic/mytopic"), "mysub");//5
Consumer.setmessagelistener (this);
Connection.start ();
} catch (Namingexception e) {
E.printstacktrace ();
} catch (JMSException e) {
E.printstacktrace ();
}
}
Receive the message, do the appropriate processing
public void OnMessage (message message) {
SYSTEM.OUT.PRINTLN ("Message in Coustomer1.");
if (message = = NULL) {
Return
}
try {
if (Message.getobjectproperty ("email") = = null) {
String emailaddress = (string) message
. Getobjectproperty ("email");
Testsendmail sendMail = new Testsendmail ();
Sendmail.sendmail (EmailAddress);
Message.acknowledge ();
Destination d = Message.getjmsreplyto ();
Session sessionn = getconnection (). CreateSession (False,
Session.client_acknowledge);
MessageProducer p = sessionn.createproducer (d);
TextMessage TM = Sessionn
. Createtextmessage ("Ustomer1 RECEIVED a email type message");
System.out
. println ("customer1 RECEIVED a email type message");
P.send (tm);
} else if (Message.getobjectproperty ("message") = = null) {
Messageaction m = new messageaction ();
SM SM = new SM ();
Sm.setdesttermid (String) message.getobjectproperty ("message"));
Sm.setmsgcontent ("Distributed JMS-ACTIVEMQ system testing");
M.ADDSM (SM);
Message.acknowledge ();
} else {
SYSTEM.OUT.PRINTLN ("Receive normal messages, do not do any processing!") ");
}
} catch (JMSException e) {
E.printstacktrace ();
}
}
Public Connection getconnection () {
InitialContext Initctx;
try {
Initctx = new InitialContext ();
Context Envcontext = (context) initctx.lookup ("java:comp/env");
Obtained based on Jndi, URL, user, password
ConnectionFactory connectionfactory = (connectionfactory) envcontext
. Lookup ("Jms/failoverconnectionfactory");
Connection Connection = Connectionfactory.createconnection ();
return connection;
} catch (Exception e) {
E.printstacktrace ();
return null;
}
}
}

3 Context.xml
To add a configuration in the context:
<resource
Name= "Jms/failoverconnectionfactory"
Auth= "Container"
Type= "Org.apache.activemq.ActiveMQConnectionFactory"
description= "JMS Connection Factory"
factory= "Org.apache.activemq.jndi.JNDIReferenceFactory"
Brokerurl= "Failover: (tcp://localhost:61616)? initialreconnectdelay=100&amp;maxreconnectattempts=5"
Brokername= "localhost"
Useembeddedbroker= "false"/>
<resource
Name= "Jms/normalconnectionfactory"
Auth= "Container"
Type= "Org.apache.activemq.ActiveMQConnectionFactory"
description= "JMS Connection Factory"
factory= "Org.apache.activemq.jndi.JNDIReferenceFactory"
Brokerurl= "tcp://localhost:61616"
Brokername= "localhost"
Useembeddedbroker= "false"/>
<resource name= "Jms/topic/mytopic"
Auth= "Container"
Type= "Org.apache.activemq.command.ActiveMQTopic"
factory= "Org.apache.activemq.jndi.JNDIReferenceFactory"
Physicalname= "MY. TEST. FOO "/>
<resource name= "Jms/queue/myqueue"
Auth= "Container"
Type= "Org.apache.activemq.command.ActiveMQQueue"
factory= "Org.apache.activemq.jndi.JNDIReferenceFactory"
Physicalname= "MY. TEST. Foo. QUEUE "/>

4. Send sms or Mail
Please refer to the first two articles of this blog
Note:
1. The system downloads Activemq, and allows;
2.ActiveMQ requires a converged Web server, such as a context.xml that can be configured with a Tomcat server;
3 in the project, the ACTIVEMQ jar needs to be introduced.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

The principle of JMS message middleware and its application in Enterprise (ACTIVEMQ)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.