浏览 6610 次
锁定老帖子 主题:JMS
精华帖 (5) :: 良好帖 (0) :: 新手帖 (1) :: 隐藏帖 (0)
作者 正文
   发表时间:2008-05-13  

1.PTP模型应用

package com.xmddl.jms.demo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Hashtable;

import javax.jms.BytesMessage;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.StreamMessage;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class QueueSend {

	// 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 queue.
	public final static String JMS_FACTORY = "SendJMSFactory";

	// Defines the queue.
	public final static String QUEUE = "SendJMSQueue";

	private QueueConnectionFactory qconFactory;

	private QueueConnection qcon;

	private QueueSession qsession;

	private QueueSender qsender;

	private Queue queue;

	private TextMessage msg;

	private StreamMessage sm;

	private BytesMessage bm;

	private MapMessage mm;

	private ObjectMessage om;

	/**
	 * Creates all the necessary objects for sending messages to a JMS queue.
	 * 
	 * @param ctx
	 *            JNDI initial context
	 * @param queueName
	 *            name of queue
	 * @exception NamingException
	 *                if operation cannot be performed
	 * @exception JMSException
	 *                if JMS fails to initialize due to internal error
	 */
	public void init(Context ctx, String queueName) throws NamingException,
			JMSException {
		qconFactory = (QueueConnectionFactory) ctx.lookup(JMS_FACTORY);
		qcon = qconFactory.createQueueConnection();
		qsession = qcon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
		queue = (Queue) ctx.lookup(queueName);
		qsender = qsession.createSender(queue);

		msg = qsession.createTextMessage();
		sm = qsession.createStreamMessage();
		bm = qsession.createBytesMessage();
		mm = qsession.createMapMessage();
		om = qsession.createObjectMessage();

		qcon.start();
	}

	/**
	 * Sends a message to a JMS queue.
	 * 
	 * @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 {
		// set TextMessage
		msg.setText(message);

		// set StreamMessage
		sm.writeString("xmddl369");
		sm.writeDouble(23.33);

		// set BytesMessage
		String name = "xmddl369";
		byte[] block = name.getBytes();
		bm.writeBytes(block);

		// set MapMessage
		mm.setString("name", "xmddl369");

		// set ObjectMessage
		UserInfo ui = new UserInfo();
		ui.setName("xmddl369");
		ui.setAddress("厦门");
		ui.setAge(100);
		om.setObject(ui);

		// qsender.send(msg);
		// qsender.send(sm);
		// qsender.send(bm);
		// qsender.send(mm);
		qsender.send(om);
	}

	/**
	 * Closes JMS objects.
	 * 
	 * @exception JMSException
	 *                if JMS fails to close objects due to internal error
	 */
	public void close() throws JMSException {
		qsender.close();
		qsession.close();
		qcon.close();
	}

	public static void main(String[] args) throws Exception {
		InitialContext ic = getInitialContext();
		QueueSend qs = new QueueSend();
		qs.init(ic, QUEUE);
		readAndSend(qs);
		qs.close();
	}

	private static void readAndSend(QueueSend qs) throws IOException,
			JMSException {
		BufferedReader msgStream = new BufferedReader(new InputStreamReader(
				System.in));
		String line = null;
		boolean quitNow = false;
		do {
			System.out.print("Enter message (\"quit\" to quit): ");
			line = msgStream.readLine();
			if (line != null && line.trim().length() != 0) {
				qs.send(line);
				System.out.println("JMS Message Sent: " + line + "\n");
				quitNow = line.equalsIgnoreCase("quit");
			}
		} while (!quitNow);

	}

	private static InitialContext getInitialContext() throws NamingException {
		Hashtable env = new Hashtable();
		env.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY);
		env.put(Context.PROVIDER_URL, PROVIDER_URL);
		return new InitialContext(env);
	}
}

 

package com.xmddl.jms.demo;

import java.util.Hashtable;

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.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueReceiver;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.StreamMessage;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

/**
 * 
 * @author Administrator
 * <pre>
 * 		修改版本:  修改人:  修改日期:  修改内容: 
 * </pre>
 */
public class QueueReceive 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";

	// Defines the JMS connection factory for the queue.
	public final static String JMS_FACTORY = "SendJMSFactory";

	// Defines the queue.
	public final static String QUEUE = "SendJMSQueue";

	private QueueConnectionFactory qconFactory;

	private QueueConnection qcon;

	private QueueSession qsession;

	private QueueReceiver qreceiver;

	private Queue queue;

	private boolean quit = false;

	/**
	 * Message listener interface.
	 * 
	 * @param msg
	 *            message
	 */
	public void onMessage(Message msg) {
		try {
			String msgText = "";
			double d = 0;

			if (msg instanceof TextMessage) {
				msgText = ((TextMessage) msg).getText();
			} else if (msg instanceof StreamMessage) {
				msgText = ((StreamMessage) msg).readString();
				d = ((StreamMessage) msg).readDouble();
			} else if (msg instanceof BytesMessage) {
				byte[] block = new byte[1024];
				((BytesMessage) msg).readBytes(block);
				msgText = String.valueOf(block);
			} else if (msg instanceof MapMessage) {
				msgText = ((MapMessage) msg).getString("name");
			} else if (msg instanceof ObjectMessage) {
				UserInfo ui = (UserInfo) ((ObjectMessage) msg).getObject();
				msgText = ui.getName();
				d = ui.getAge();
			}

			System.out.println("Message Received: " + msgText + "\t" + d);

			if (msgText.equalsIgnoreCase("quit")) {
				synchronized (this) {
					quit = true;
					this.notifyAll(); // Notify main thread to quit
				}
			}
		} catch (JMSException jmse) {
			jmse.printStackTrace();
		}
	}

	/**
	 * Creates all the necessary objects for receiving messages from a JMS
	 * queue.
	 * 
	 * @param ctx
	 *            JNDI initial context
	 * @param queueName
	 *            name of queue
	 * @exception NamingException
	 *                if operation cannot be performed
	 * @exception JMSException
	 *                if JMS fails to initialize due to internal error
	 */
	public void init(Context ctx, String queueName) throws NamingException,
			JMSException {
		qconFactory = (QueueConnectionFactory) ctx.lookup(JMS_FACTORY);
		qcon = qconFactory.createQueueConnection();
		qsession = qcon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
		queue = (Queue) ctx.lookup(queueName);
		qreceiver = qsession.createReceiver(queue);
		qreceiver.setMessageListener(this);
		qcon.start();
	}

	/**
	 * Closes JMS objects.
	 * 
	 * @exception JMSException
	 *                if JMS fails to close objects due to internal error
	 */
	public void close() throws JMSException {
		qreceiver.close();
		qsession.close();
		qcon.close();
	}

	/**
	 * main() method.
	 * 
	 * @param args
	 *            WebLogic Server URL
	 * @exception Exception
	 *                if execution fails
	 */

	public static void main(String[] args) throws Exception {

		InitialContext ic = getInitialContext();
		QueueReceive qr = new QueueReceive();
		qr.init(ic, QUEUE);

		System.out
				.println("JMS Ready To Receive Messages (To quit, send a \"quit\" message).");

		// Wait until a "quit" message has been received.
		synchronized (qr) {
			while (!qr.quit) {
				try {
					qr.wait();
				} catch (InterruptedException ie) {
					ie.printStackTrace();
				}
			}
		}
		qr.close();
	}

	private static InitialContext getInitialContext() throws NamingException {
		Hashtable env = new Hashtable();
		env.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY);
		env.put(Context.PROVIDER_URL, PROVIDER_URL);
		return new InitialContext(env);
	}

	public String getEncoding() throws Exception {
		return "Hello World!";
	}
}

 

package com.xmddl.jms.demo;

import java.io.Serializable;

public class UserInfo implements Serializable{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String name;
	private String address;
	private double age;
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public double getAge() {
		return age;
	}
	public void setAge(double age) {
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}

 2.PUB/SUB模型应用

package com.xmddl.jms.demo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Hashtable;

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 TopicSend {
	// 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 queue.
	public final static String JMS_FACTORY = "SendJMSFactory";

	// Defines the queue.
	public final static String TOPIC= "SendJMSTopic";
	
	private TopicConnectionFactory qconFactory;

	private TopicConnection qcon;

	private TopicSession qsession;

	private TopicPublisher publisher;

	private Topic topic;

	private TextMessage msg;
	
	private StreamMessage sm;
	
	private BytesMessage bm;
	
	private MapMessage mm;
	
	private ObjectMessage om;
	
	public void init(Context ctx, String queueName) throws NamingException,
	JMSException {
		qconFactory = (TopicConnectionFactory) ctx.lookup(JMS_FACTORY);
		qcon = qconFactory.createTopicConnection();
//		qsession = qcon.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
		qsession = qcon.createTopicSession(true, Session.AUTO_ACKNOWLEDGE);
		topic = (Topic) ctx.lookup(queueName);
		publisher = qsession.createPublisher(topic);
		
		msg = qsession.createTextMessage();
		sm=qsession.createStreamMessage();
		bm=qsession.createBytesMessage();
		mm=qsession.createMapMessage();
		om=qsession.createObjectMessage();
		
		qcon.start();
	}
	
	
	
	
	/**
	 * Sends a message to a JMS queue.
	 * 
	 * @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 {
		//set TextMessage
		msg.setText(message);
		
		//set StreamMessage
		sm.writeString("xmddl369");
		sm.writeDouble(23.33);
		
		//set BytesMessage
		String name="xmddl369";
		byte[] block=name.getBytes();
		bm.writeBytes(block);
		
		//set MapMessage
		mm.setString("name", "xmddl369");
		
		//set ObjectMessage
		UserInfo ui=new UserInfo();
		ui.setName("xmddl369");
		ui.setAddress("厦门");
		ui.setAge(100);
		om.setObject(ui);
		
//		qsender.send(msg);
//		qsender.send(sm);
//		qsender.send(bm);
//		qsender.send(mm);
		publisher.publish(om);
//		qsession.commit();
	}

	/**
	 * Closes JMS objects.
	 * 
	 * @exception JMSException
	 *                if JMS fails to close objects due to internal error
	 */
	public void close() throws JMSException {
		publisher.close();
		qsession.close();
		qcon.close();
	}

	public static void main(String[] args) throws Exception {
		InitialContext ic = getInitialContext();
		TopicSend qs = new TopicSend();
		qs.init(ic, TOPIC);
		readAndSend(qs);
		qs.close();
	}

	private static void readAndSend(TopicSend qs) throws IOException,
			JMSException {
		BufferedReader msgStream = new BufferedReader(new InputStreamReader(
				System.in));
		String line = null;
		boolean quitNow = false;
		do {
			System.out.print("Enter message (\"quit\" to quit): ");
			line = msgStream.readLine();
			if (line != null && line.trim().length() != 0) {
				qs.send(line);
				System.out.println("JMS Message Sent: " + line + "\n");
				quitNow = line.equalsIgnoreCase("quit");
			}
		} while (!quitNow);

	}

	private static InitialContext getInitialContext() throws NamingException {
		Hashtable env = new Hashtable();
		env.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY);
		env.put(Context.PROVIDER_URL, PROVIDER_URL);
		return new InitialContext(env);
	}
}

 

package com.xmddl.jms.demo;

import java.util.Hashtable;

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 TopicReceive 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";

	// Defines the JMS connection factory for the queue.
	public final static String JMS_FACTORY = "SendJMSFactory";

	// Defines the queue.
	public final static String TOPIC= "SendJMSTopic";
	
	private TopicConnectionFactory qconFactory;

	private TopicConnection qcon;

	private TopicSession qsession;

	private TopicSubscriber subscriber;

	private Topic topic;

	private TextMessage msg;
	
	private boolean quit = false;


	public void onMessage(Message msg) {
		try {
			String msgText = "";
			double d = 0;

			if (msg instanceof TextMessage) {
				msgText = ((TextMessage) msg).getText();
			} else if (msg instanceof StreamMessage) {
				msgText = ((StreamMessage) msg).readString();
				d = ((StreamMessage) msg).readDouble();
			} else if (msg instanceof BytesMessage) {
				byte[] block = new byte[1024];
				((BytesMessage) msg).readBytes(block);
				msgText = String.valueOf(block);
			} else if (msg instanceof MapMessage) {
				msgText = ((MapMessage) msg).getString("name");
			} else if (msg instanceof ObjectMessage) {
				UserInfo ui = (UserInfo) ((ObjectMessage) msg).getObject();
				msgText = ui.getName();
				d = ui.getAge();
			}

			System.out.println("Message Received: " + msgText + "\t" + d);

			if (msgText.equalsIgnoreCase("quit")) {
				synchronized (this) {
					quit = true;
					this.notifyAll(); // Notify main thread to quit
				}
			}
		} catch (JMSException jmse) {
			jmse.printStackTrace();
		}
	}

	/**
	 * Creates all the necessary objects for receiving messages from a JMS
	 * queue.
	 * 
	 * @param ctx
	 *            JNDI initial context
	 * @param queueName
	 *            name of queue
	 * @exception NamingException
	 *                if operation cannot be performed
	 * @exception JMSException
	 *                if JMS fails to initialize due to internal error
	 */
	public void init(Context ctx, String queueName) throws NamingException,
			JMSException {
		qconFactory = (TopicConnectionFactory) ctx.lookup(JMS_FACTORY);
		qcon = qconFactory.createTopicConnection();
		qsession = qcon.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
		topic = (Topic) ctx.lookup(queueName);
		subscriber = qsession.createSubscriber(topic);
		subscriber.setMessageListener(this);
		qcon.start();
	}

	/**
	 * Closes JMS objects.
	 * 
	 * @exception JMSException
	 *                if JMS fails to close objects due to internal error
	 */
	public void close() throws JMSException {
		subscriber.close();
		qsession.close();
		qcon.close();
	}

	/**
	 * main() method.
	 * 
	 * @param args
	 *            WebLogic Server URL
	 * @exception Exception
	 *                if execution fails
	 */

	public static void main(String[] args) throws Exception {

		InitialContext ic = getInitialContext();
		TopicReceive qr = new TopicReceive();
		qr.init(ic, TOPIC);

		System.out
				.println("JMS Ready To Receive Messages (To quit, send a \"quit\" message).");

		// Wait until a "quit" message has been received.
		synchronized (qr) {
			while (!qr.quit) {
				try {
					qr.wait();
				} catch (InterruptedException ie) {
					ie.printStackTrace();
				}
			}
		}
		qr.close();
	}

	private static InitialContext getInitialContext() throws NamingException {
		Hashtable env = new Hashtable();
		env.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY);
		env.put(Context.PROVIDER_URL, PROVIDER_URL);
		return new InitialContext(env);
	}

	public String getEncoding() throws Exception {
		return "Hello World!";
	}
}

 说明:点对点的消息只能被一个人消费一次,发布和订阅的消息可以被多个人消费一次。SendJMSFactory和SendJMSTopic等要通过JNDI从weblogic中查找......

  • 大小: 60.5 KB
  • 大小: 61.7 KB
   发表时间:2009-02-16  
谢谢lz!正在学习中
0 请登录后投票
   发表时间:2009-02-16  
好帖,代码清晰明了。
超级喜欢lz这样的教学贴,建议斑竹加精哦!

看了代码,一气呵成,感觉特爽快,一下子将jms的基础梳理了一遍,学习了!

希望楼主继续有jms深入的帖子发表
0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics