1、订阅者简单demo
前提准备,需要早weblogic控制台上新建一个连接工厂(ConnectionFactory-topic)和主题(Topic-test),同时需要将weblogic.jar (或者wljmsclient.jar)放到项目的lib下面缺少jar包会报"weblogic.jndi.WLInitialContextFactory class not found".
import java.util.Properties;
import javax.jms.BytesMessage;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import javax.jms.StreamMessage;
import javax.jms.TextMessage;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicSession;
import javax.jms.TopicSubscriber;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class TopicMsgSubscriber implements MessageListener {
// Defines the JNDI context factory.
public final static String JNDI_FACTORY = "weblogic.jndi.WLInitialContextFactory";
// Defines the JNDI provider url.
public final static String PROVIDER_URL = "t3://localhost:7001";//连接weblogic控制台地址
// Defines the JMS connection factory for the topic.
public final static String CONNECTION_FACTORY_JNDI_NAME = "ConnectionFactory-topic";//连接工厂名称
// Defines the topic, use the topic JNDI name
public final static String TOPIC_JNDI_NAME = "Topic-test";//主题名称
private TopicConnectionFactory tconFactory;
private TopicConnection topicConnection;
private TopicSession topicSession;
private TopicSubscriber topicSubscriber;
private Topic topic;
private boolean quit = false;
/**
* get the context object.
*
* @return context object
* @throws NamingException if operation cannot be performed
*/
private static InitialContext getInitialContext() throws NamingException {
Properties properties=new Properties();
// Hashtable table = new Hashtable();
properties.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY);
properties.put(Context.PROVIDER_URL, PROVIDER_URL);
properties.put(Context.SECURITY_PRINCIPAL, "wlsadmin");
properties.put(Context.SECURITY_CREDENTIALS,"test4train");
InitialContext context = new InitialContext(properties);
return context;
}
/**
* Creates all the necessary objects for receiving messages from a JMS topic.
*
* @param ctx JNDI initial context
* @param topicName name of topic
* @exception NamingException if operation cannot be performed
* @exception JMSException if JMS fails to initialize due to internal error
*/
public void init(Context ctx, String topicName) throws NamingException, JMSException {
tconFactory = (TopicConnectionFactory) ctx.lookup(CONNECTION_FACTORY_JNDI_NAME);
topicConnection = tconFactory.createTopicConnection();
//如下可选持久订阅或者非持久订阅模型
// 持久订阅
topicConnection.setClientID("1");
topic = (Topic) ctx.lookup(topicName);
topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
topicSubscriber = topicSession.createDurableSubscriber(topic,"1");
// 非持久订阅者
// topic = (Topic) ctx.lookup(topicName);
// topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
// topicSubscriber = topicSession.createSubscriber(topic);
topicSubscriber.setMessageListener(this);
// second thread: message reveive thread.
topicConnection.start();
}
/**
* implement from MessageListener.
* when a message arrived, it will be invoked.
*
* @param message message
*/
public void onMessage(Message message) {
try {
String msgStr = "";
int age = 0;
if (message instanceof TextMessage) {
msgStr = ((TextMessage) message).getText();
} else if (message instanceof StreamMessage) {
msgStr = ((StreamMessage) message).readString();
age = ((StreamMessage) message).readInt();
} else if (message instanceof BytesMessage) {
byte[] block = new byte[1024];
((BytesMessage) message).readBytes(block);
msgStr = String.valueOf(block);
} else if (message instanceof MapMessage) {
msgStr = ((MapMessage) message).getString("name");
} else if (message instanceof ObjectMessage) {
// User user = (User) ((ObjectMessage) message).getObject();
// msgStr = user.getName();
// age = user.getAge();
}
System.out.println("Message subscribed: " + msgStr + ", " + age);
if (msgStr.equalsIgnoreCase("quit")) {
synchronized (this) {
quit = true;
this.notifyAll(); // Notify main thread to quit
}
}
} catch (JMSException e) {
throw new RuntimeException("error happens", e);
}
}
/**
* release resources.
*
* @exception JMSException if JMS fails to close objects due to internal error
*/
public void close() throws JMSException {
topicSubscriber.close();
topicSession.close();
topicConnection.close();
}
/**
* test client.
* first thread(main thread)
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
InitialContext ctx = getInitialContext();
TopicMsgSubscriber subscriber = new TopicMsgSubscriber();
subscriber.init(ctx, TOPIC_JNDI_NAME);
// Wait until a "quit" message has been subscribed.
synchronized (subscriber) {
while (!subscriber.quit) {
try {
subscriber.wait();
} catch (InterruptedException e) {
throw new RuntimeException("error happens", e);
}
}
}
subscriber.close();
}
}
2、发布者demo
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;
import javax.jms.BytesMessage;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import javax.jms.StreamMessage;
import javax.jms.TextMessage;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicPublisher;
import javax.jms.TopicSession;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class TopicMsgPublisher {
// Defines the JNDI context factory.
public final static String JNDI_FACTORY = "weblogic.jndi.WLInitialContextFactory";
// Defines the JNDI provider url.
public final static String PROVIDER_URL = "t3://localhost:7001";
// Defines the JMS connection factory for the topic.
public final static String CONNECTION_FACTORY_JNDI_NAME = "ConnectionFactory-topic";
// Defines the topic, use the topic JNDI name
public final static String TOPIC_JNDI_NAME = "Topic-test";
private TopicConnectionFactory tconFactory;
private TopicConnection topicConnection;
private TopicSession topicSession;
private TopicPublisher topicPublisher;
private Topic topic;
private TextMessage textMessage;
private StreamMessage streamMessage;
private BytesMessage bytesMessage;
private MapMessage mapMessage;
private ObjectMessage objectMessage;
/**
* get the context object.
*
* @return context object
* @throws NamingException if operation cannot be performed
*/
private static InitialContext getInitialContext() throws NamingException {
Properties properties=new Properties();
// Hashtable table = new Hashtable();
properties.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY);
properties.put(Context.PROVIDER_URL, PROVIDER_URL);
properties.put(Context.SECURITY_PRINCIPAL, "wlsadmin");
properties.put(Context.SECURITY_CREDENTIALS,"test4train");
InitialContext context = new InitialContext(properties);
return context;
}
/**
* Creates all the necessary objects for sending messages to a JMS topic.
*
* @param ctx JNDI initial context
* @param topicName name of topic
* @exception NamingException if operation cannot be performed
* @exception JMSException if JMS fails to initialize due to internal error
*/
public void init(Context ctx, String topicName) throws NamingException, JMSException {
tconFactory = (TopicConnectionFactory) ctx.lookup(CONNECTION_FACTORY_JNDI_NAME);
topicConnection = tconFactory.createTopicConnection();
topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
topic = (Topic) ctx.lookup(topicName);
topicPublisher = topicSession.createPublisher(topic);
textMessage = topicSession.createTextMessage();
streamMessage = topicSession.createStreamMessage();
bytesMessage = topicSession.createBytesMessage();
mapMessage = topicSession.createMapMessage();
objectMessage = topicSession.createObjectMessage();
topicConnection.start();
}
/**
* Sends a message to a JMS topic.
*
* @param message message to be sent
* @exception JMSException if JMS fails to send message due to internal error
*/
public void send(String message) throws JMSException {
// type1: set TextMessage
textMessage.setText(message);
// type2: set StreamMessage
streamMessage.writeString(message);
streamMessage.writeInt(20);
// type3: set BytesMessage
byte[] block = message.getBytes();
bytesMessage.writeBytes(block);
// type4: set MapMessage
mapMessage.setString("name", message);
// type5: set ObjectMessage
// User user = new User();
// user.setName(message);
// user.setAge(30);
// objectMessage.setObject(user);
topicPublisher.publish(mapMessage);
}
/**
* read the msg from the console, then send it.
*
* @param msgPublisher
* @throws IOException if IO fails to send message due to internal error
* @throws JMSException if JMS fails to send message due to internal error
*/
private static void readAndSend(TopicMsgPublisher msgPublisher) throws IOException, JMSException {
BufferedReader msgStream = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter message(input quit to quit):");
String line = null;
boolean quit = false;
do {
line = msgStream.readLine();
if (line != null && line.trim().length() != 0) {
msgPublisher.send(line);
System.out.println("JMS Message Sent: " + line + "\n");
quit = line.equalsIgnoreCase("quit");
}
} while (!quit);
}
/**
* release resources.
*
* @exception JMSException if JMS fails to close objects due to internal error
*/
public void close() throws JMSException {
topicPublisher.close();
topicSession.close();
topicConnection.close();
}
/**
* test client.
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
InitialContext ctx = getInitialContext();
TopicMsgPublisher publisher = new TopicMsgPublisher();
publisher.init(ctx, TOPIC_JNDI_NAME);
readAndSend(publisher);
System.out.println("publisher结束");
publisher.close();
}
}