Ejb_ message-Driven development bean

Source: Internet
Author: User
Tags jboss jboss server

Message-Driven Development beans

Java Information Services (Java Messageservice)

Java Information Services (Java Message Service, referred to as JMS) is a developer-neutral API for visiting enterprise messaging systems.

The Enterprise messaging system can assist the application software to interact with the message over the network.

The programming process for JMS is very easy to summarize: Application A sends a message to a message server's target (Destination), and the message server forwards the message to application B.

Since application A and application B do not have direct code-related connection, both implementations understand the couple.

Messages in JMS

The center of the messaging system is the message. A message consists of three parts:

Header, property, and body (body).

There are several types of messages. They are all derived from the Message interface.

Streammessage: A message in the body that includes a stream of Java primitive values. Its padding and reads are performed sequentially.

Mapmessage: A message that includes a set of name-value pairs in a body.

The order of entries is undefined.

TextMessage: A message that includes a Java string in the body (for example, an XML message).

ObjectMessage: A message that includes a serialized Java object in the body.

Bytesmessage: A message that includes a continuous stream of bytes in the body.

The delivery model of the message

JMS supports two message delivery models: Point-to-point (point-to-point. (PTP) and announcement/subscription (Publish/subscribe, abbreviated as PUB/SUB).

These two message-passing models are similar. But there are the following differences:

The PTP messaging model specifies that a message can only be passed to a receiver. It is expressed in javax.jms.Queue.

The PUB/SUB message delivery model agrees that a message is passed to multiple receivers.

Using Javax.jms.Topic to express

Both of these models are implemented by extending the common base class. For example: Javax.jms.Queue and Javax.jms.Topic are extended from javax.jms.Destination classes.

Point-to-point PTP message delivery model


Whoever listens first will receive it first.

Advertise/SUBSCRIBE Messaging model

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvsmvyb21lx3m=/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/center ">

Configure Destination Address

Before you start JMS programming. We need to first configure the destination address (Destination) to which the message arrives. Since only the destination address exists, we have the ability to send a message to this address. Because each application server is configured differently about the destination address, the following is an example of JBoss, which configures a queue type's destination address.

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

<server>

<mbeancode= "Org.jboss.mq.server.jmx.Queue"

Name= "Jboss.mq.destination:service=queue,name=foshanshop" >

<attributename= "Jndiname" >queue/foshanshop</attribute>

<dependsoptional-attribute-name= "Destinationmanager" >jboss.mq:service=DestinationManager</depends>

</mbean>

</server>

JBoss uses an XML file to configure the queue address. The name format of the document shall be in accordance with *-service.xml

<attribute name= "Jndiname" > property specifies the global Jndi name of the destination address. Assuming you do not specify the Jndiname property, JBoss generates a default global jndi for you, whose name consists of the "queue" + "/" + Destination address name.

In addition, before any queue or topic is deployed, the application server must first deploy the destination Manager Mbean. So we declare this dependency through the <depends> node.

Bold yourself to define the settings, black without changes.

Steps:

Create a new hqu-service.xml on the desktop copy the above XML code changes bold section:

<?

XML version="1.0"encoding="UTF-8"?>

< Server >

< Mbean Code="Org.jboss.mq.server.jmx.Queue"

name="Jboss.mq.destination:service=queue,name=hququeue">

< attribute name="Jndiname">queue/hququeue</attribute>

< depends optional-attribute-name="Destinationmanager">

Jboss.mq:service=destinationmanager</depends>

</ Mbean >

</ Server >

Announcement: The copy to JBoss Server\default\deploy is published. Be able to see the announcement information in the console.

Can be seen on the JBoss Management page: http://localhost:8080/jmx-console/

Jboss.mq.destination under the Name=hququeue,service=queue

After the target address is established. We will be able to send the message.

Sending messages in the Java class

The following steps are typically sent for a message:

(1) Get a Jndi initialization context

Initialcontextctx = new InitialContext ();

(2) Find a connection factory queueconnectionfactory according to the context.

This connection factory is provided by JMS and does not need to be created by us. Each vendor binds it to a global jndi, which we can get through its global jndi;

Queueconnectionfactoryfactory = (queueconnectionfactory)

Ctx.lookup ("Queueconnectionfactory");

(3) Get a connection from the connection factory queueconnection

Conn= factory.createqueueconnection ();

(4) Establish a session by connecting;

Session= Conn.createqueuesession (False, Queuesession.auto_acknowledge);

This code means: Create a session that does not require a transaction and can proactively confirm that the message has been received.

(5) Find the destination address:

Sample corresponding Code: Destinationdestination = (Destination) ctx.lookup ("Queue/hququeue");

(6) Build messages based on session and destination address producer MessageProducer (Queuesender and Topicpublisher both extend from MessageProducer interface)

Sample corresponding Code:

MessageProducer producer =session.createproducer (destination);

TextMessage msg =session.createtextmessage ("Hello, this is my first message-driven bean");

Producer.send (msg);

Steps:

Create a new message-driven bean project and create a new Javaproject:messagedrivenbean. Add a new Java class to the EJB required jar file: Queuesender under Cn.hqu.app to send the queue.

Package Cn.hqu.app;import Javax.jms.destination;import Javax.jms.messageproducer;import javax.jms.QueueConnection; Import Javax.jms.queueconnectionfactory;import Javax.jms.queuesession;import Javax.naming.initialcontext;public Class Queuesender {public static void main (string[] args) {try {//1. First initialize a Jndi context object InitialContext CTX = new Initialcontex T ();//2. Find a connection factory from the context queueconnectionfactoryqueueconnectionfactory factory = (queueconnectionfactory) ctx.lookup (" Queueconnectionfactory ");//3. You can create a queue connection queueconnection through a connection factory. Queueconnection conn = Factory.createqueueconnection ();//4. Create a session to the destination address via the connection queuesession session = Conn.createqueuesession (false, Queuesession.auto_acknowledge);//5. Find the destination address destination Destination = (destination) ctx.lookup ("Queue/hququeue"),//6. Get the message sender MessageProducer producer = Session.createproducer (destination);//Through this sender we can send a message: Producer.send (session.createtextmessage ("Hello, Su Zhida")); Session.close (); Conn.close ();} catch (Exception e) {e.printstacktrace ();}}}


Inside the method. Write the sending code.

1. Initialize a Jndi context object first:

Copy the previous item's jdni.properties to SRC, in the Mian of the class Queuesender

Try {

InitialContextctx = newinitialcontext ();

}catch(Namingexception e) {

E.printstacktrace ();

}

2. Find a connection factory by context Queueconnectionfactory

Find the connection factory to the queue type,

Queueconnectionfactory Factory = (queueconnectionfactory) ctx.lookup ("queueconnectionfactory");

3. Connect the factory to create a queue connection queueconnection.

QueueconnectionConn = Factory.createqueueconnection ();

4. Create a session to a destination by connecting: The first parameter specifies whether a transaction is required. The second parameter specifies a message determination pattern.

Queuesession Session= Conn.createqueuesession (false, queuesession. Auto_acknowledge);

5. To find the destination address:

Destination Destination= (Destination) ctx.lookup ("Queue/hququeue");

6. The sender who gets the message

MessageProducerproducer = Session.createproducer (destination);

With this sender we are able to send a message:

Producer.send (Session.createtextmessage (" hello. Su Zhi da "));

The calling program sends a message to the destination address. Executes main. The message is sent out. Next, write the message receiver.

Receiving messages with message-driven beans

Can be received in the form of a Java class, where a message-driven bean (message driven bean) is used to receive messages, because the message-driven bean (MDB) is designed to specifically handle message-based requests. It uses the same instance pool technique as the stateless session bean. A container can handle hundreds or thousands of JMS messages concurrently with a certain number of bean instances.

This is because the MDB has the ability to handle a large number of concurrent messages. So it is ideal for applications in some message gateway products. Suppose a business runs for a very long time, and the results do not need to be fed back to the user in real time. It's also great for using MDB. If the order is successful, send an email or send a text message to the user.

An MDB typically implements the MessageListener interface, which defines the OnMessage () method. The bean passes through it to process the received JMS message.

Package JAVAX.JMS;

Public interface MessageListener {

public void OnMessage (Message message);

}

When the container detects that a message arrives at the target address that the bean waits for, the container calls the OnMessage () method and passes the message as a parameter to the MDB. The MDB decides what to do with the message in OnMessage (). You can use gaze to specify which target address (Destination) the MDB listens to. When the MDB is deployed. The container will read the configuration information.

Steps:

Create a new message-driven Bean:messagedrivenbean to implement MessageListener under Cn.hqu.message.

When the container detects that a message arrives at the target address that the JavaBean listens to, it will help us get the message to onmessage this way.

Annotations enable you to specify what type of message-driven bean it listens to, and the Jndi name of the destination address.

@MessageDriven (activationconfig=

{

@Activationconfigproperty (Propertyname="destinationtype",

propertyvalue="Javax.jms.Queue"),

@Activationconfigproperty (propertyname="Destination",

propertyvalue="Queue/hququeu"),

@Activationconfigproperty (Propertyname="Acknowledgemode",

propertyvalue="Auto-acknowledge")

})

Public class Messagedrivenbean implements messagelistener{

From the target address of the queue type, look for the destination address that Jndi is bound to Queue/hququeu.

When the message is received, the confirmation mode of the message is confirmed by itself. Acknowledgemode is the default, so this can be removed.

Processing received messages in the OnMessage method

Public void onMessage (Message msg) {

textmessage message = (textmessage) msg;

Try {

System. out. println (Message.gettext ());

} catch (JMSException e) {

E.printstacktrace ();

}

}

To be packaged, deployed.

Copy the ant from the previous project, change the configuration file Build.xml name to

Messagedrivenbean.

Run deploy to advertise the message-driven bean to JBoss. Printing in the console

16:07:57,999 INFO [jmxkernelabstraction] Installing Mbean:jboss.j2ee:jar=messa

Gedrivenbean.jar,name=messagedrivenbean,service=ejb3with dependencies:

16:07:58,015 INFO [Ejbcontainer] STARTED EJB:cn.hqu.message.MessageDrivenBean

Ejbname:messagedrivenbean

16:07:58,039 INFO [Ejb3deployer] deployed:file:/f:/java/jboss-4.2.2.ga/server/

Default/deploy/messagedrivenbean.jar

16:07:58,060 INFO [STDOUT] Hello, Su Zhida.

The message was received.

JMS agrees that the sender and receiver can be online at a different time. There is no code correlation between the two, which enables very good decoupling.

Code: Http://pan.baidu.com/s/1bn2DgPT

The delivery of the queue type is over, and the next

The topic is sent and received.

The first step is to configure the destination address. Type is not a queue type, is a topic type, in configuration file Hqu-service.xml plus a topic configuration

<mbean code= "Org.jboss.mq.server.jmx.Topic"

Name= "Jboss.mq.destination:service=topic,name=hqutopic" >

<attribute name= "Jndiname" >topic/hquTopic</attribute>

<depends optional-attribute-name= "Destinationmanager" >

Jboss.mq:service=destinationmanager</depends>

</mbean>

Configure it to publish it to JBoss (copy it in).

The new class Topicsender is used to advertise messages of type topic under Cn.hqu.app.

The Jndi name can be seen in the post-publication console.

Package Cn.hqu.app;import Javax.jms.destination;import Javax.jms.messageproducer;import javax.jms.TopicConnection; Import Javax.jms.topicconnectionfactory;import Javax.jms.topicsession;import Javax.naming.initialcontext;public  Class Topicsender {/** * @param args */public static void main (string[] args) {try {//1. First initialize a Jndi context object InitialContext CTX = new InitialContext ();//2. Find a connection factory from the context queueconnectionfactorytopicconnectionfactory factory = ( topicconnectionfactory) ctx.lookup ("Topicconnectionfactory");//3. You can create a queue connection queueconnection by connecting to the factory. Topicconnection conn = Factory.createtopicconnection ();//4. Create a session to the destination address via the connection topicsession session = Conn.createtopicsession (false, Topicsession.auto_acknowledge);//5. Find the destination address destination Destination = (destination) ctx.lookup ("Topic/hqutopic"),//6. Get the message sender MessageProducer producer = Session.createproducer (destination);//Through this sender we can send a message: Producer.send (session.createtextmessage ("Hello, Su Zhida")); Session.close (); Conn.close ();} catch (Exception e) {E.printstacktrace();}}} 

Executes main.

The recipient of the development message. Two message-driven beans are created because they are received by multiple parties

The new Receivebean implementation MessageListener under Cn.hqu.message.

Package Cn.hqu.message;import Javax.ejb.activationconfigproperty;import Javax.ejb.messagedriven;import Javax.jms.jmsexception;import Javax.jms.message;import Javax.jms.messagelistener;import javax.jms.TextMessage;@ Messagedriven (activationconfig ={  @ActivationConfigProperty (propertyname= "destinationtype",    Propertyvalue= "Javax.jms.Topic"),  @ActivationConfigProperty (propertyname= "Destination",    propertyvalue= "Topic/hqutopic")}) public class Receivebean implements MessageListener {@Overridepublic void OnMessage (Message msg) { TextMessage message = (textmessage) msg;try {System.out.println (This.getclass () +message.gettext ());} catch ( JMSException e) {e.printstacktrace ();}}}

Another message-driven Bean:receiveotherbean

Package Cn.hqu.message;import Javax.ejb.activationconfigproperty;import Javax.ejb.messagedriven;import Javax.jms.jmsexception;import Javax.jms.message;import Javax.jms.messagelistener;import javax.jms.TextMessage;@ Messagedriven (activationconfig ={  @ActivationConfigProperty (propertyname= "destinationtype",    Propertyvalue= "Javax.jms.Topic"),  @ActivationConfigProperty (propertyname= "Destination",    propertyvalue= "Topic/hqutopic")}) public class Receiveotherbean implements MessageListener {@Overridepublic void OnMessage (Message msg) {TextMessage message = (textmessage) msg;try {System.out.println (This.getclass () +message.gettext ());} catch ( JMSException e) {e.printstacktrace ();}}}

Advertise the Execute ant deploy

The announcement is complete and you do not see the topic message that you just sent, because for the topic type of message, it is assumed that the receiver was not listening for this topic type of message. He could not get the news. Although we now deploy it to JBoss, because it did not listen to the topic target address at that time, he could not get the message.

Now that we run the topic send again, we can see multiple receivers receiving messages from the console.

Code: Http://pan.baidu.com/s/1nthubNF

Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.

Ejb_ message-Driven development bean

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.