📄 topicsupplier.java
字号:
package com.wls8unleashed.jms;
import javax.naming.*;
import javax.jms.*;
import java.util.*;
import java.io.*;
/**
* Implements the functionality to publish a message to
* a topic. Extends the TopicManager for init info.
*/
public class TopicSupplier extends TopicManager{
private TopicPublisher topicPublisher;
/**
* Initializes the topic supplier.
*/
public TopicSupplier(Context context){
// Call superclass TopicManager constructor
super(context);
try{
// Create topic publisher
System.out.println("Creating topic publisher...");
topicPublisher = topicSession.createPublisher(topic);
}catch(JMSException e){
System.out.println("Problem creating Topic Publisher");
e.printStackTrace();
}
}
/**
* Publish an order message to a topic.
*/
public void sendOrder(OrderItem message) throws JMSException {
System.out.println("Publishing order message:" + message);
// Create empty ObjectMessage on session
System.out.println("Creating empty object message...");
ObjectMessage sendingMessage = topicSession.createObjectMessage();
// Start the topicconnection
System.out.println("Starting topic connection...");
topicConnection.start();
// Set the order object onto the message carrier
System.out.println("Setting order item into message...");
sendingMessage.setObject((Serializable) message);
// Send the message
System.out.println("Publishing the order message...");
topicPublisher.publish(sendingMessage);
}
/**
* Close JMS related objects.
*/
public void close() throws JMSException {
topicPublisher.close();
topicSession.close();
topicConnection.close();
}
/**
* Main method used to execute the TopicSupplier example
*/
public static void main(String[] args) throws Exception {
try {
// Get some orders from the OrderManager class
System.out.println("Getting a bunch of orders to send...");
Collection orders = OrderManager.getOrders();
// For each order, get order request and send to consumer
Iterator it = orders.iterator();
while (it.hasNext()) {
// Get an OrderItem object to send
OrderItem item = (OrderItem) it.next();
// Create JNDI context
Context context = Props.getInitialContext();
// Create new TopicSupplier
System.out.println("Creating new TopicSupplier...");
TopicSupplier topicSupplier = new TopicSupplier(context);
// Send the order
System.out.println("Initiating order to send...");
topicSupplier.sendOrder(item);
// Close TopicSupplier
System.out.println("Closing TopicSupplier...");
topicSupplier.close();
}
}catch(Exception e){
System.out.println("Problem executing topic supplier");
e.printStackTrace();
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -