- 浏览: 307388 次
- 性别:
- 来自: 杭州
文章分类
最新评论
-
wst0350:
点赞,有空深入讲解下原理
Servlet、Filter 和 Listener 调用顺序、生命周期的实验分析 -
tuspark:
Eclipse中高亮设置内容还有很多细节选项可以设置的,可以看 ...
Eclipse 设置匹配代码高亮 -
xichao1929:
这个时候,怎么启动发布的项目呢?????
JBoss设置为Windows服务 -
xiaozi7:
非常感谢,楼主的英语水平不一般那
WebSphere MQ Version 7 发布订阅相关配置 -
qtlkw:
slave没玩过
Hudson: java.lang.OutOfMemoryError: Java heap space error
转载自: http://www.devx.com/Java/Article/41921/1954
Message-oriented middleware (MOM) decouples applications by allowing them to communicate using one of two messaging models: point-to-point messaging and publish/subscribe messaging. The models differ in fundamental ways, but neither requires applications to know the other’s implementation details.
Point-to-point messaging achieves only partial decoupling of applications, because you still need to know where to put messages. Publish/subscribe provides a higher degree of independence and reduces design complexity in many cases, but it requires more coding and configuration. Traditionally, MOM shops have opted for point-to-point messaging to avoid the more complex requirements of publish/subscribe.
Enter IBM WebSphere MQ (WMQ), Version 7. This latest release of WMQ aims to make coding and configuring publish/subscribe easier and more intuitive. A previous DevX article focused on the point-to-point messaging capabilities of WMQ. This article explains WMQ's publish/subscribe messaging.
Publish/Subscribe Messaging Overview
Publish/subscribe is the messaging-oriented equivalent of the object-oriented observer design pattern. In publish/subscribe messaging, a sender application creates a message containing the information it wants to send and assigns it a topic that denotes the subject of the information. This message is called a publication. WMQ receives the publication, recognizes the topic, and then distributes the publication to interested applications.
Specifically, WMQ publish/subscribe components include:
Publisher (information producer): This component generates messages (publications) under a certain subject (topic) and sends the publications to a WMQ queue manager. A publisher knows nothing about the recipient(s) of the information.
Subscriber (information consumer/receiver): This component registers interest in a certain topic(s) with a WMQ queue manager. It also specifies its subscription queue name; that is, the queue where it wants to receive the messages related to this topic. The subscriber knows nothing about the information publishers(s).
A publications router: This component passes messages from publishers to topic subscribers. Earlier WMQ versions required a broker component on top of a queue manager to enable publish/subscribe. The broker maintained topics and subscriptions, and it routed publications. In WMQ Version 7, IBM changed this approach significantly. The queue manager is now responsible for topics, subscriptions, and routing publications. Also, MQ Explorer for Version 7 allows you to create topics and subscriptions graphically.
Figure 1 shows a basic MQ publish/subscribe setup.
A publish/subscribe system can have many publishers and many subscribers, and often, two or more queue managers communicating with one another. Also, an application can be both a publisher and a subscriber.
A Publish/Subscribe Scenario
Suppose a company sends notifications to its clients via email and Short Message Service (SMS) based on information received from various information providers (say, news and weather services). If the company adds another provider (say, for entertainment), it will have to configure the new provider to write messages to both SMS and email queues. Figure 2 shows the point-to-point implementation for this use case, and Figure 3 shows the publish/subscribe implementation.
Set Up Your Own Publish/Subscribe Use Case
In this section, you will create a publish/subscribe setup resembling part of the use case in Figure 3. You will create a publisher for the news topic and two subscriptions for the email and SMS applications using the following procedure:
1. Create a queue manager.
2. Create a news topic.
3. Create subscription queues.
4. Create subscriptions.
5. Create Java Messaging Services (JMS)-administered objects.
6. Write publisher and subscriber classes.
7. Run the classes.
This tutorial uses MQ Version 7 on Windows XP. (Download a trial version from the IBM web site.) Installation on Windows is straightforward. Just keep all the default values as you go through the installation wizard, but be sure to perform the installation as a user from the administrators group.
Don't worry if you haven't used WMQ before. You will use the Eclipse-based WebSphere MQ Explorer, an easy GUI for administering WMQ, to perform basic definitions.
Start WebSphere MQ Explorer as follows: Start –> All Programs –> IBM WebSphere MQ –> WebSphere MQ Explorer. If this is the first time you are starting MQ Explorer, a welcome screen will appear. Just close the welcome screen.
Create a Queue Manager
1. In MQ Explorer's Navigator view, right-click Queue Managers and then select New –> Queue Manager. This starts the "Create Queue Manager" wizard.
2. On Step 1, enter TestQM as the queue manager name and enter the name of the default Dead Letter Queue which is SYSTEM.DEAD.LETTER.QUEUE, then click Next (see Figure 4).
3. Click Next on the wizard screens for Steps 2 and 3. At Step 4, make sure "Create listener configured for TCP/IP" is checked and the entered port number is free (see Figure 5), and then click Finish.
Create a News Topic
1. Under TestQM, right-click Topics and then select New –> Topic to start the "New Topic" wizard.
2. Type News.Topic as the topic name (see Figure 6). This represents the WMQ administrative object used to manage the topic. Click Next.
3. On the topic properties page, type News in the "Topic string" field (see Figure 7). This string is used when creating JMS administered objects to refer to the News topic. Click Finish.
Create Subscription Queues
Next, you will set up news publications to be delivered to Subscription queues. Create two queues for the email and SMS applications:
1. Under TestQM, right-click Queues then select New –> Local Queue to start the "New Local Queue" wizard.
2. In the name field, type Email.Queue and click Finish.
3. Repeat the above steps to create another queue called SMS.Queue.
Create Subscriptions
In order to receive a topic's publications, subscribers have to register interest in the topic. They use subscriptions to accomplish this. You can can create subscriptions programmatically or through MQ Explorer. Through the following steps, you will create two subscriptions using MQ Explorer:
1. Under TestQM, right-click Subscriptions and then select New –> Subscription to start the "New Subscription" wizard.
2. In the name field, type EmailSubscription and click Next (see Figure8). In the "Change properties" page, press the Select button next to the "Topic name" and then select News.Topic from the displayed topics list. Press OK. On the same page, type Email.Queue in the destination name field (see Figure 9). Click Finish.
3. Repeat the above steps to create another subscription called SMSSubscription with the topic set to News.Topic and the destination name set to SMS.Queue.
A Quick Test for Your Publish/Subscribe Setup
Perform the following to verify you have correctly completed the setup for the News topic:
1. Under TestQM, click Topics.
2. In the right pane, right click News.Topic and select "Test Publication" to open the test window.
3. In the message data field, type "publish/subscribe test" (or any other text), click the "Publish message" button, and then click the Close button. This should distribute the message to the subscriber queues Email.Queue and SMS.Queue.
4. Under TestQM, click Queues.
5. In the right pane, right click Email.Queue and select "Browse Messages." When the browse messages window opens, search the "Message Data" column for the text you entered. You should also see the same message in SMS.Queue.
6. Right click Email.Queue and select "Clear Messages." Click the Clear button in the "Clear queue" window. Do the same for SMS.Queue.
Create JMS-Administered Objects
JMS applications require you to wrap vendor-specific objects in JMS-administered objects. To store JMS-administered objects, create a file-based Java Naming and Directory Interface (JNDI) namespace. Start by adding a new initial context:
1. Right-click JMS-Administered Objects and then select Add Initial Context.
2. On Screen 1:
Select "File System" for "Where is the JNDI located."
For the Bindings directory, browse to C:\JNDI-Directory (This directory has to exist).
Keep note of the factory class and provider URL; you will use them in the Java code (see Figure 10).
Click Finish.
Next, create a JMS Connection factory and destinations under the Initial Context.
Create a Connection Factory
1. Right-click Connection Factories and then select New –> Connection Factory. On the first screen, type TestQMConnectionFactory in the name field and click Next (see Figure 11). You will use TestQMConnectionFactory in the JNDI lookup.
2. Click Next on Step 2, Step 3, and Step 4.
3. On the last page, select the connection tab (on the left) and then click the Select button to select TestQM as "Base queue manager" (See Figure 12). Click Finish.
Create Destinations
JMS destinations wrap WMQ topics and queues. Create a destination corresponding to the News topic:
1. Right-click destinations and select New –> Destination to start the "New Destination" wizard.
2. In the first step, enter NewsTopic in the Name field and change the Type field to Topic (See Figure 13). Click Next.
3. Click Next on the second screen.
4. On the last page (Change properties), type News in the Topic field and then click Finish (See Figure 14). This is the topic string you defined when you created the News topic.
Create two destinations corresponding to the subscriber queues:
1. Right-click destinations and then select New –> Destination to start the new "Destination wizard."
2. In the first step, type EmailQueue in the Name field and then click Next.
3. Click Next on the second screen.
4. On the last page, click the Select button next to the "Queue Manager" field and select TestQM from the list.
5. Click the Select button next to the Queue field and select Email (See Figure 15). Queue from the list. Click Finish.
6. Repeat the above steps to create another Destination called SMSQueue for SMS.Queue. Your destinations should look like the ones in Figure 16.
Coding JMS Publishers and Subscribers
After you have defined your topics and subscriptions through the MQ Explorer, writing publisher and subscriber applications is easy. To publish a message, you must write a message to a topic (just as you would with a queue). Subscribers simply read messages from queues.
The downloadable source code for this article uses generic JMS interfaces, which treat queues and topics uniformly as destinations. It provides compiled classes that include a News publisher and two subscribers (corresponding to the Email and SMS applications).
The following are brief explanations of the classes.
JNDIUtil Class
This class includes methods to retrieve objects by name through JNDI lookup (see Listing 1).
NewsPublisher Class
This class publishes messages to the News topic (see Listing 2).
factory= jndiUtil.getConnectionFactory("TestQMConnectionFactory");
connection = factory.createConnection();
You use the connection object to create a session:
session = connection.createSession( transacted, Session.AUTO_ACKNOWLEDGE);
To publish messages, retrieve a News destination object, create a MessageProducer, and then send messages:
destination = jndiUtil.getDestination("NewsTopic");
producer = session.createProducer(destination);
TextMessage message = session.createTextMessage("No News is Good News!");
producer.send(message);
EmailSubscriber and SMSSubscriber
These two classes represent the email application and the SMS application (see Listing 3 and Listing 4). Because you already defined subscriptions in MQ Explorer, the two applications simply read messages from the subscriber queues.
The code is similar to the NewsPublisher class, except that it uses a MessageConsumer to retrieve messages from queues:
consumer = session.createConsumer(destination);
TextMessage iMsg = (TextMessage) consumer.receive(1000);
Compiling and Running the Sample Classes
The JAR files required to compile and run the sample classes are automatically added to the CLASSPATH environment variable when you install WMQ. The required JARs are located in C:\Program Files\IBM\WebSphere MQ\Java\lib, including the JARs you need for JMS and JNDI. You just need to add the sample classes from the code download to your CLASSPATH environment variable.
To publish messages, run the NewsPublisher:
java devx.articles.pubsub.NewsPublisher
Run both subscribers after your run the NewsPublisher to retrieve messages. Each class should retrieve its own copy of the messages published by NewsPublisher:
java devx.articles.pubsub.EmailSubscriber
java devx.articles.pubsub.SMSSubscriber
You're done. Your sample classes should compile and run successfully.
So the next time you're designing messaging-based applications, don't be so quick to dismiss publish/subscribe. Remember this article and how quickly you were able to get started with publish/subscribe messaging.
WebSphere Version 6 和 Version 7的不同参考:
http://publib.boulder.ibm.com/infocenter/wmqv7/v7r0/index.jsp?topic=/com.ibm.mq.csqzao.doc/mi29080_.htm
Message-oriented middleware (MOM) decouples applications by allowing them to communicate using one of two messaging models: point-to-point messaging and publish/subscribe messaging. The models differ in fundamental ways, but neither requires applications to know the other’s implementation details.
Point-to-point messaging achieves only partial decoupling of applications, because you still need to know where to put messages. Publish/subscribe provides a higher degree of independence and reduces design complexity in many cases, but it requires more coding and configuration. Traditionally, MOM shops have opted for point-to-point messaging to avoid the more complex requirements of publish/subscribe.
Enter IBM WebSphere MQ (WMQ), Version 7. This latest release of WMQ aims to make coding and configuring publish/subscribe easier and more intuitive. A previous DevX article focused on the point-to-point messaging capabilities of WMQ. This article explains WMQ's publish/subscribe messaging.
Publish/Subscribe Messaging Overview
Publish/subscribe is the messaging-oriented equivalent of the object-oriented observer design pattern. In publish/subscribe messaging, a sender application creates a message containing the information it wants to send and assigns it a topic that denotes the subject of the information. This message is called a publication. WMQ receives the publication, recognizes the topic, and then distributes the publication to interested applications.
Specifically, WMQ publish/subscribe components include:
Publisher (information producer): This component generates messages (publications) under a certain subject (topic) and sends the publications to a WMQ queue manager. A publisher knows nothing about the recipient(s) of the information.
Subscriber (information consumer/receiver): This component registers interest in a certain topic(s) with a WMQ queue manager. It also specifies its subscription queue name; that is, the queue where it wants to receive the messages related to this topic. The subscriber knows nothing about the information publishers(s).
A publications router: This component passes messages from publishers to topic subscribers. Earlier WMQ versions required a broker component on top of a queue manager to enable publish/subscribe. The broker maintained topics and subscriptions, and it routed publications. In WMQ Version 7, IBM changed this approach significantly. The queue manager is now responsible for topics, subscriptions, and routing publications. Also, MQ Explorer for Version 7 allows you to create topics and subscriptions graphically.
Figure 1 shows a basic MQ publish/subscribe setup.
A publish/subscribe system can have many publishers and many subscribers, and often, two or more queue managers communicating with one another. Also, an application can be both a publisher and a subscriber.
A Publish/Subscribe Scenario
Suppose a company sends notifications to its clients via email and Short Message Service (SMS) based on information received from various information providers (say, news and weather services). If the company adds another provider (say, for entertainment), it will have to configure the new provider to write messages to both SMS and email queues. Figure 2 shows the point-to-point implementation for this use case, and Figure 3 shows the publish/subscribe implementation.
Set Up Your Own Publish/Subscribe Use Case
In this section, you will create a publish/subscribe setup resembling part of the use case in Figure 3. You will create a publisher for the news topic and two subscriptions for the email and SMS applications using the following procedure:
1. Create a queue manager.
2. Create a news topic.
3. Create subscription queues.
4. Create subscriptions.
5. Create Java Messaging Services (JMS)-administered objects.
6. Write publisher and subscriber classes.
7. Run the classes.
This tutorial uses MQ Version 7 on Windows XP. (Download a trial version from the IBM web site.) Installation on Windows is straightforward. Just keep all the default values as you go through the installation wizard, but be sure to perform the installation as a user from the administrators group.
Don't worry if you haven't used WMQ before. You will use the Eclipse-based WebSphere MQ Explorer, an easy GUI for administering WMQ, to perform basic definitions.
Start WebSphere MQ Explorer as follows: Start –> All Programs –> IBM WebSphere MQ –> WebSphere MQ Explorer. If this is the first time you are starting MQ Explorer, a welcome screen will appear. Just close the welcome screen.
Create a Queue Manager
1. In MQ Explorer's Navigator view, right-click Queue Managers and then select New –> Queue Manager. This starts the "Create Queue Manager" wizard.
2. On Step 1, enter TestQM as the queue manager name and enter the name of the default Dead Letter Queue which is SYSTEM.DEAD.LETTER.QUEUE, then click Next (see Figure 4).
3. Click Next on the wizard screens for Steps 2 and 3. At Step 4, make sure "Create listener configured for TCP/IP" is checked and the entered port number is free (see Figure 5), and then click Finish.
Create a News Topic
1. Under TestQM, right-click Topics and then select New –> Topic to start the "New Topic" wizard.
2. Type News.Topic as the topic name (see Figure 6). This represents the WMQ administrative object used to manage the topic. Click Next.
3. On the topic properties page, type News in the "Topic string" field (see Figure 7). This string is used when creating JMS administered objects to refer to the News topic. Click Finish.
Create Subscription Queues
Next, you will set up news publications to be delivered to Subscription queues. Create two queues for the email and SMS applications:
1. Under TestQM, right-click Queues then select New –> Local Queue to start the "New Local Queue" wizard.
2. In the name field, type Email.Queue and click Finish.
3. Repeat the above steps to create another queue called SMS.Queue.
Create Subscriptions
In order to receive a topic's publications, subscribers have to register interest in the topic. They use subscriptions to accomplish this. You can can create subscriptions programmatically or through MQ Explorer. Through the following steps, you will create two subscriptions using MQ Explorer:
1. Under TestQM, right-click Subscriptions and then select New –> Subscription to start the "New Subscription" wizard.
2. In the name field, type EmailSubscription and click Next (see Figure8). In the "Change properties" page, press the Select button next to the "Topic name" and then select News.Topic from the displayed topics list. Press OK. On the same page, type Email.Queue in the destination name field (see Figure 9). Click Finish.
3. Repeat the above steps to create another subscription called SMSSubscription with the topic set to News.Topic and the destination name set to SMS.Queue.
A Quick Test for Your Publish/Subscribe Setup
Perform the following to verify you have correctly completed the setup for the News topic:
1. Under TestQM, click Topics.
2. In the right pane, right click News.Topic and select "Test Publication" to open the test window.
3. In the message data field, type "publish/subscribe test" (or any other text), click the "Publish message" button, and then click the Close button. This should distribute the message to the subscriber queues Email.Queue and SMS.Queue.
4. Under TestQM, click Queues.
5. In the right pane, right click Email.Queue and select "Browse Messages." When the browse messages window opens, search the "Message Data" column for the text you entered. You should also see the same message in SMS.Queue.
6. Right click Email.Queue and select "Clear Messages." Click the Clear button in the "Clear queue" window. Do the same for SMS.Queue.
Create JMS-Administered Objects
JMS applications require you to wrap vendor-specific objects in JMS-administered objects. To store JMS-administered objects, create a file-based Java Naming and Directory Interface (JNDI) namespace. Start by adding a new initial context:
1. Right-click JMS-Administered Objects and then select Add Initial Context.
2. On Screen 1:
Select "File System" for "Where is the JNDI located."
For the Bindings directory, browse to C:\JNDI-Directory (This directory has to exist).
Keep note of the factory class and provider URL; you will use them in the Java code (see Figure 10).
Click Finish.
Next, create a JMS Connection factory and destinations under the Initial Context.
Create a Connection Factory
1. Right-click Connection Factories and then select New –> Connection Factory. On the first screen, type TestQMConnectionFactory in the name field and click Next (see Figure 11). You will use TestQMConnectionFactory in the JNDI lookup.
2. Click Next on Step 2, Step 3, and Step 4.
3. On the last page, select the connection tab (on the left) and then click the Select button to select TestQM as "Base queue manager" (See Figure 12). Click Finish.
Create Destinations
JMS destinations wrap WMQ topics and queues. Create a destination corresponding to the News topic:
1. Right-click destinations and select New –> Destination to start the "New Destination" wizard.
2. In the first step, enter NewsTopic in the Name field and change the Type field to Topic (See Figure 13). Click Next.
3. Click Next on the second screen.
4. On the last page (Change properties), type News in the Topic field and then click Finish (See Figure 14). This is the topic string you defined when you created the News topic.
Create two destinations corresponding to the subscriber queues:
1. Right-click destinations and then select New –> Destination to start the new "Destination wizard."
2. In the first step, type EmailQueue in the Name field and then click Next.
3. Click Next on the second screen.
4. On the last page, click the Select button next to the "Queue Manager" field and select TestQM from the list.
5. Click the Select button next to the Queue field and select Email (See Figure 15). Queue from the list. Click Finish.
6. Repeat the above steps to create another Destination called SMSQueue for SMS.Queue. Your destinations should look like the ones in Figure 16.
Coding JMS Publishers and Subscribers
After you have defined your topics and subscriptions through the MQ Explorer, writing publisher and subscriber applications is easy. To publish a message, you must write a message to a topic (just as you would with a queue). Subscribers simply read messages from queues.
The downloadable source code for this article uses generic JMS interfaces, which treat queues and topics uniformly as destinations. It provides compiled classes that include a News publisher and two subscribers (corresponding to the Email and SMS applications).
The following are brief explanations of the classes.
JNDIUtil Class
This class includes methods to retrieve objects by name through JNDI lookup (see Listing 1).
Listing 1. JNDIUtil Class This class includes methods to retrieve objects by name through JNDI lookup. package devx.articles.pubsub; //JMS classes import javax.jms.JMSException; import javax.jms.ConnectionFactory; import javax.jms.Destination; //JNDI classes import javax.naming.InitialContext; import javax.naming.Context; import javax.naming.NamingException; //Standard Java classes import java.util.Hashtable; /** * * A wrapper class for JNDI calls * */ public class JNDIUtil { private Context context; public JNDIUtil(String icf, String url) throws JMSException, NamingException { Hashtable environment = new Hashtable(); environment.put(Context.INITIAL_CONTEXT_FACTORY, icf ); environment.put(Context.PROVIDER_URL, url); context= new InitialContext( environment ); } /** * @param ObjName Object Name to be retrieved * @return Retrieved Object * @throws NamingException */ private Object getObjectByName(String ObjName) throws NamingException { return context.lookup( ObjName ); } /** * @param factoryName Factory Name * @return ConnectionFactory object * @throws NamingException */ public ConnectionFactory getConnectionFactory(String factoryName) throws NamingException { return (ConnectionFactory) getObjectByName(factoryName); } /** * @param destinationName Destination Name * @return ConnectionFactory object * @throws NamingException */ public Destination getDestination(String destinationName) throws NamingException { return (Destination) getObjectByName(destinationName); } }You will use methods in this class to retrieve references to the JMS objects you have already defined.
NewsPublisher Class
This class publishes messages to the News topic (see Listing 2).
package devx.articles.pubsub; //JMS classes import javax.jms.JMSException; import javax.jms.ConnectionFactory; import javax.jms.Connection; import javax.jms.Session; import javax.jms.Destination; import javax.jms.MessageProducer; import javax.jms.TextMessage; //JNDI classes import javax.naming.NamingException; /** * A class to demonstrate how to a publish to a topic. */ public class NewsPublisher { public static String icf = "com.sun.jndi.fscontext.RefFSContextFactory"; public static String url = "file:/C:/JNDI-Directory"; public static void main(String[] vars) throws JMSException, NamingException { ConnectionFactory factory = null; Connection connection = null; Session session = null; Destination destination= null; // a destination can be a topic or a queue MessageProducer producer= null; try { JNDIUtil jndiUtil= new JNDIUtil(icf,url); factory= jndiUtil.getConnectionFactory("TestQMConnectionFactory"); connection = factory.createConnection(); connection.start(); // Indicate a non-transactional session boolean transacted = false; session = connection.createSession( transacted, Session.AUTO_ACKNOWLEDGE); destination = jndiUtil.getDestination("NewsTopic"); producer = session.createProducer(destination); TextMessage message = session.createTextMessage("No News is Good News!"); producer.send(message); System.out.println("NewsPublisher: Message Publication Completed"); } finally { // Always release resources if ( producer!= null ) producer.close(); if ( session!= null ) session.close(); if ( connection!= null ) connection.close(); } } }The starting point is a connection factory lookup. You use the factory to create a connection:
factory= jndiUtil.getConnectionFactory("TestQMConnectionFactory");
connection = factory.createConnection();
You use the connection object to create a session:
session = connection.createSession( transacted, Session.AUTO_ACKNOWLEDGE);
To publish messages, retrieve a News destination object, create a MessageProducer, and then send messages:
destination = jndiUtil.getDestination("NewsTopic");
producer = session.createProducer(destination);
TextMessage message = session.createTextMessage("No News is Good News!");
producer.send(message);
EmailSubscriber and SMSSubscriber
These two classes represent the email application and the SMS application (see Listing 3 and Listing 4). Because you already defined subscriptions in MQ Explorer, the two applications simply read messages from the subscriber queues.
Listing 3. EmailSubscriber This class represents the email application. package devx.articles.pubsub; //JMS classes import javax.jms.JMSException; import javax.jms.ConnectionFactory; import javax.jms.Connection; import javax.jms.Session; import javax.jms.Destination; import javax.jms.MessageConsumer; import javax.jms.TextMessage; //JNDI classes import javax.naming.NamingException; /** * A class to demonstrate how to retrieve publications from subscription queues. */ public class EmailSubscriber { public static String icf = "com.sun.jndi.fscontext.RefFSContextFactory"; public static String url = "file:/C:/JNDI-Directory"; public static void main(String[] vars) throws JMSException, NamingException { ConnectionFactory factory = null; Connection connection = null; Session session = null; Destination destination= null; // a destination can be a topic or a queue MessageConsumer consumer= null; try { JNDIUtil jndiUtil= new JNDIUtil(icf,url); factory= jndiUtil.getConnectionFactory("TestQMConnectionFactory"); connection = factory.createConnection(); connection.start(); // Indicate a non-transactional session boolean transacted = false; session = connection.createSession( transacted, Session.AUTO_ACKNOWLEDGE); destination = jndiUtil.getDestination("EmailQueue"); consumer = session.createConsumer(destination); TextMessage iMsg = (TextMessage) consumer.receive(1000); if ( iMsg != null ) System.out.println( iMsg.getText() ); else System.out.println( "No messages in queue " ); System.out.println("EmailSubscriber: Message Reading Completed"); } finally { // Always release resources if ( consumer!= null ) consumer.close(); if ( session!= null ) session.close(); if ( connection!= null ) connection.close(); } } }
Listing 4. SMSSubscriber This class represents the SMS application. package devx.articles.pubsub; //JMS classes import javax.jms.JMSException; import javax.jms.ConnectionFactory; import javax.jms.Connection; import javax.jms.Session; import javax.jms.Destination; import javax.jms.MessageConsumer; import javax.jms.TextMessage; //JNDI classes import javax.naming.NamingException; /** * A class to demonstrate how to retrieve publications from subscription queues. */ public class SMSSubscriber { public static String icf = "com.sun.jndi.fscontext.RefFSContextFactory"; public static String url = "file:/C:/JNDI-Directory"; public static void main(String[] vars) throws JMSException, NamingException { ConnectionFactory factory = null; Connection connection = null; Session session = null; Destination destination= null; // a destination can be a topic or a queue MessageConsumer consumer= null; try { JNDIUtil jndiUtil= new JNDIUtil(icf,url); factory= jndiUtil.getConnectionFactory("TestQMConnectionFactory"); connection = factory.createConnection(); connection.start(); // Indicate a non-transactional session boolean transacted = false; session = connection.createSession( transacted, Session.AUTO_ACKNOWLEDGE); destination = jndiUtil.getDestination("SMSQueue"); consumer = session.createConsumer(destination); TextMessage iMsg = (TextMessage) consumer.receive(1000); if ( iMsg != null ) System.out.println( iMsg.getText() ); else System.out.println( "No messages in queue " ); System.out.println("SMSSubscriber: Message Reading Completed"); } finally { // Always release resources if ( consumer!= null ) consumer.close(); if ( session!= null ) session.close(); if ( connection!= null ) connection.close(); } } }
The code is similar to the NewsPublisher class, except that it uses a MessageConsumer to retrieve messages from queues:
consumer = session.createConsumer(destination);
TextMessage iMsg = (TextMessage) consumer.receive(1000);
Compiling and Running the Sample Classes
The JAR files required to compile and run the sample classes are automatically added to the CLASSPATH environment variable when you install WMQ. The required JARs are located in C:\Program Files\IBM\WebSphere MQ\Java\lib, including the JARs you need for JMS and JNDI. You just need to add the sample classes from the code download to your CLASSPATH environment variable.
To publish messages, run the NewsPublisher:
java devx.articles.pubsub.NewsPublisher
Run both subscribers after your run the NewsPublisher to retrieve messages. Each class should retrieve its own copy of the messages published by NewsPublisher:
java devx.articles.pubsub.EmailSubscriber
java devx.articles.pubsub.SMSSubscriber
You're done. Your sample classes should compile and run successfully.
So the next time you're designing messaging-based applications, don't be so quick to dismiss publish/subscribe. Remember this article and how quickly you were able to get started with publish/subscribe messaging.
WebSphere Version 6 和 Version 7的不同参考:
http://publib.boulder.ibm.com/infocenter/wmqv7/v7r0/index.jsp?topic=/com.ibm.mq.csqzao.doc/mi29080_.htm
相关推荐
【IBM WebSphere MQ安装包详解】 IBM WebSphere MQ,前身为IBM MQSeries,是IBM公司推出的一款企业级的消息中间件产品。它在信息技术领域扮演着至关重要的角色,为跨网络、操作系统和应用程序提供了高效、安全的...
* 增强了订阅/发布的易用性:WebSphere MQ 支持订阅/发布式的消息传递,能够满足企业的实时业务需求。 * 支持多种集成方式:WebSphere MQ 支持多种集成方式,包括点对点式、发布/订阅式等,满足企业的不同集成需求。...
IBM WebSphere MQ入门教程 IBM WebSphere MQ 是一种基于消息队列的中间件,用于实现不同的应用程序之间的异步通信。下面是对 IBM WebSphere MQ 的入门教程的总结,涵盖了 WebSphere MQ 的原理、体系结构、重要特点...
【Websphere MQ入门教程7】是一本专为初学者和WebSphere MQ系统管理员及开发者设计的实用指南。全书涵盖了WebSphere MQ的基础知识、系统管理和应用开发等多个方面,旨在帮助读者深入理解这一消息中间件的工作原理和...
WebSphere MQ的v7版本特别针对开发者的易用性和选择性进行了增强,提供了集成的发布/订阅消息功能。 WebSphere MQ具有如下特点: 1. 统一的消息传输机制:为SOA架构提供了通用的消息处理方式,使企业能够灵活地将...
WebSphere MQ配置.rar WebSphere MQ配置.rar WebSphere MQ配置.rar
本教程的详细内容可参考附件中的“WebSphere MQ入门教程7.doc”,该文档将深入讲解上述知识点,并包含实例代码和配置步骤,是学习和理解WebSphere MQ的良好参考资料。在实际应用中,读者需结合自身业务场景,灵活...
WebSphere MQ(Message Queue)是 IBM 提供的一款企业级的消息中间件产品,它支持多种消息传递模型,包括点对点 (Point-to-Point, PTP) 和发布/订阅 (Publish/Subscribe, Pub/Sub) 模型。WebSphere MQ 版本 6 引入了...
"IBM WebSphere MQ V7 jar" 指的是版本7的WebSphere MQ对应的Java API库。 在描述中提到的“java连接MQ操作Queue数据所需jar”,意味着开发人员在编写Java程序来连接和操作IBM WebSphere MQ的队列时,需要引入这些...
学习MQ和WebSphere MQ的相关书籍可以帮助我们深入理解以下关键概念: 1. **消息队列模型**:理解消息如何在队列中存储和传递,以及不同类型的队列(如本地队列、远程队列、死信队列等)。 2. **WebSphere MQ架构**...
本文将介绍如何在 Linux 上安装和配置 WebSphere MQ,以及如何使用 Java 应用程序开发 MQ 环境。本文将通过示例应用程序说明如何向队列发送消息和从队列接收消息。 WebSphere MQ 简介 WebSphere MQ 是一种可靠的...
这些 JAR 文件位于 `WebSphere MQ\java\lib` 目录下,是开发、配置和运行与 WebSphere MQ 集成的应用程序所必需的。 1. **WebSphere MQ 概述**: WebSphere MQ(原名 MQSeries)是 IBM 提供的一种企业级的消息队列...
【配置IBM WEBSPHERE MQ触发器】是IBM企业级消息中间件产品中的一项重要功能,它允许用户在消息进入或离开队列时自动执行特定的操作,例如启动应用程序、执行脚本或者更新数据库。这一特性使得MQ系统能更好地与业务...
在这个例子中,它可能包含与WebSphere MQ相关的bean配置,比如JMS的ConnectionFactory,Queue,以及消息监听器等。 6. **运行和测试**:部署应用程序,确保发送方能够成功将消息放入队列,而接收方能正确地接收和...
本文将详细阐述如何配置 Websphere MQ 的远程通信,以便两台WinXP操作系统通过以太网进行通信。 首先,确保两台机器(发送端与接收端)已正确连接,并关闭防火墙,因为防火墙可能会阻止MQ的数据传输。发送端机器...
7. **安全性**:WebSphere MQ支持用户认证、授权和加密,确保消息在传输过程中的安全,防止未授权访问和数据泄露。 8. **故障处理和高可用性**:通过集群、镜像队列、远程复制等方式确保服务连续性和数据完整性。 ...
**配置WebSphere MQ队列管理器**以接受TCP/IP客户端连接是实现远程通信的基础。这通常涉及到修改队列管理器的配置文件,添加必要的通道定义,并可能需要调整安全设置以允许外部访问。 遇到问题时,**解决WebSphere ...
IBM Websphere MQ入门教程 IBM Websphere MQ是IBM公司开发的一款消息队列中间件,旨在提供一个可靠的异步通信机制,实现不同应用程序之间的数据...但是,Websphere MQ的配置和管理也存在一定的复杂性和高昂的成本。
WebSphere MQ V6.0是这个系列的一个重要版本,发布于2007年,为用户提供了稳定、高效且安全的消息传递服务。 **WebSphere MQ的基本概念:** 1. **消息队列**:WebSphere MQ的核心概念,是数据传输的载体,用于存储...