最近温习了下EJB和JMS,整理了下思路,和大家分享下P2P和Pub/Sub的demo
;JBoss 7 集成了HornetQ,JMS可以在HornetQ中间件运行,有时间在和大家分享关于HornetQ的文章。
1.下载Jboss 7并配置运行环境 http://www.jboss.org/jbossas/downloads
2.增加testjms用户(用以jms链接时使用),在jboss的bin目录下运行add-user.bat,如下:
3.修改启动配置文件,使用standalone-full.xml启动jboss服务器
$JBOSS_HOME$\bin>standalone.bat --server-config=standalone-full.xml
4.例子:修改Jboss配置文件standalone-full.xml,找到hornetq-server节点,在该节点下的jms-destinations确定含有以下配置:
<jms-destinations>
<jms-queue name="testQueue">
<entry name="queue/test"/>
<entry name="java:jboss/exported/jms/queue/test"/>
</jms-queue>
<jms-topic name="ServerNotificationTopic">
<entry name="topic/ServerNotification"/>
<entry name="java:jboss/exported/jms/topic/ServerNotification"/>
</jms-topic>
</jms-destinations>
P2P demo
package org.jboss.as.quickstarts.jms;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
import java.util.Properties;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
public class JMSProducer {
private static final Logger log = Logger.getLogger(JMSProducer.class.getName());
// Set up all the default values
private static final String DEFAULT_MESSAGE = "Hello, World!";
private static final String DEFAULT_CONNECTION_FACTORY = "jms/RemoteConnectionFactory";
private static final String DEFAULT_DESTINATION = "jms/queue/test";
private static final String DEFAULT_MESSAGE_COUNT = "1";
private static final String DEFAULT_USERNAME = "testjms";
private static final String DEFAULT_PASSWORD = "123456";
private static final String INITIAL_CONTEXT_FACTORY = "org.jboss.naming.remote.client.InitialContextFactory";
private static final String PROVIDER_URL = "remote://localhost:4447";
public static void main(String[] args) throws Exception {
ConnectionFactory connectionFactory = null;
Connection connection = null;
Session session = null;
MessageProducer producer = null;
Destination destination = null;
TextMessage message = null;
Context context = null;
try {
// Set up the context for the JNDI lookup
final Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY);
env.put(Context.PROVIDER_URL, System.getProperty(Context.PROVIDER_URL, PROVIDER_URL));
env.put(Context.SECURITY_PRINCIPAL, System.getProperty("username", DEFAULT_USERNAME));
env.put(Context.SECURITY_CREDENTIALS, System.getProperty("password", DEFAULT_PASSWORD));
context = new InitialContext(env);
// Perform the JNDI lookups
String connectionFactoryString = System.getProperty("connection.factory", DEFAULT_CONNECTION_FACTORY);
log.info("Attempting to acquire connection factory \"" + connectionFactoryString + "\"");
connectionFactory = (ConnectionFactory) context.lookup(connectionFactoryString);
log.info("Found connection factory \"" + connectionFactoryString + "\" in JNDI");
String destinationString = System.getProperty("destination", DEFAULT_DESTINATION);
log.info("Attempting to acquire destination \"" + destinationString + "\"");
destination = (Destination) context.lookup(destinationString);
log.info("Found destination \"" + destinationString + "\" in JNDI");
// Create the JMS connection, session, producer, and consumer
connection = connectionFactory.createConnection(System.getProperty("username", DEFAULT_USERNAME), System.getProperty("password", DEFAULT_PASSWORD));
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
producer = session.createProducer(destination);
connection.start();
int count = Integer.parseInt(System.getProperty("message.count", DEFAULT_MESSAGE_COUNT));
String content = System.getProperty("message.content", DEFAULT_MESSAGE);
log.info("Sending " + count + " messages with content: " + content);
// Send the specified number of messages
for (int i = 0; i < count; i++) {
message = session.createTextMessage(content);
producer.send(message);
}
//等待30秒退出
CountDownLatch latch = new CountDownLatch(1);
latch.await(30, TimeUnit.SECONDS);
} catch (Exception e) {
log.severe(e.getMessage());
throw e;
} finally {
if (context != null) {
context.close();
}
// closing the connection takes care of the session, producer, and consumer
if (connection != null) {
connection.close();
}
}
}
}
package org.jboss.as.quickstarts.jms;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
import java.util.Properties;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
public class JMSConsumer {
private static final Logger log = Logger.getLogger(JMSConsumer.class.getName());
// Set up all the default values
private static final String DEFAULT_CONNECTION_FACTORY = "jms/RemoteConnectionFactory";
private static final String DEFAULT_DESTINATION = "jms/queue/test";
private static final String DEFAULT_USERNAME = "testjms";
private static final String DEFAULT_PASSWORD = "123456";
private static final String INITIAL_CONTEXT_FACTORY = "org.jboss.naming.remote.client.InitialContextFactory";
private static final String PROVIDER_URL = "remote://localhost:4447";
public static void main(String[] args) throws Exception {
ConnectionFactory connectionFactory = null;
Connection connection = null;
Session session = null;
MessageConsumer consumer = null;
Destination destination = null;
TextMessage message = null;
Context context = null;
try {
// Set up the context for the JNDI lookup
final Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY);
env.put(Context.PROVIDER_URL, System.getProperty(Context.PROVIDER_URL, PROVIDER_URL));
env.put(Context.SECURITY_PRINCIPAL, System.getProperty("username", DEFAULT_USERNAME));
env.put(Context.SECURITY_CREDENTIALS, System.getProperty("password", DEFAULT_PASSWORD));
context = new InitialContext(env);
// Perform the JNDI lookups
String connectionFactoryString = System.getProperty("connection.factory", DEFAULT_CONNECTION_FACTORY);
log.info("Attempting to acquire connection factory \"" + connectionFactoryString + "\"");
connectionFactory = (ConnectionFactory) context.lookup(connectionFactoryString);
log.info("Found connection factory \"" + connectionFactoryString + "\" in JNDI");
String destinationString = System.getProperty("destination", DEFAULT_DESTINATION);
log.info("Attempting to acquire destination \"" + destinationString + "\"");
destination = (Destination) context.lookup(destinationString);
log.info("Found destination \"" + destinationString + "\" in JNDI");
// Create the JMS connection, session, producer, and consumer
connection = connectionFactory.createConnection(System.getProperty("username", DEFAULT_USERNAME), System.getProperty("password", DEFAULT_PASSWORD));
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
consumer = session.createConsumer(destination);
connection.start();
//等待30秒退出
CountDownLatch latch = new CountDownLatch(1);
// Then receive the same number of messaes that were sent
while(message == null) {
log.info("----receive message");
message = (TextMessage) consumer.receive(5000);
latch.await(1, TimeUnit.SECONDS);
}
log.info("====Received message with content " + message.getText());
} catch (Exception e) {
log.severe(e.getMessage());
throw e;
} finally {
if (context != null) {
context.close();
}
// closing the connection takes care of the session, producer, and consumer
if (connection != null) {
connection.close();
}
}
}
}
Pub/Sub demo
package com.lym.jms;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class JMSPub {
private static final String DEFAULT_USERNAME = "testjms";
private static final String DEFAULT_PASSWORD = "123456";
private static final String INITIAL_CONTEXT_FACTORY = "org.jboss.naming.remote.client.InitialContextFactory";
private static final String PROVIDER_URL = "remote://localhost:4447";
/**
* @param args
* @throws NamingException
* @throws JMSException
* @throws IOException
*/
public static void main(String[] args) throws NamingException, JMSException, IOException {
final Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY);
env.put(Context.PROVIDER_URL, System.getProperty(Context.PROVIDER_URL, PROVIDER_URL));
env.put(Context.SECURITY_PRINCIPAL, System.getProperty("username", DEFAULT_USERNAME));
env.put(Context.SECURITY_CREDENTIALS, System.getProperty("password", DEFAULT_PASSWORD));
InitialContext context = new InitialContext(env);
// 1) lookup connection factory (local JNDI lookup, no credentials required)
javax.jms.ConnectionFactory cf = (javax.jms.ConnectionFactory)context.lookup("jms/RemoteConnectionFactory");
// 2) create a connection to the remote provider
javax.jms.Connection connection = cf.createConnection(DEFAULT_USERNAME, DEFAULT_PASSWORD);
// 3) create session session
boolean transacted = false;
javax.jms.Session session = connection.createSession(transacted, Session.AUTO_ACKNOWLEDGE);
/**
* 在standalone-full.xml中找到
* <subsystem xmlns="urn:jboss:domain:messaging:1.1">
* 节点下找到<jms-destinations>节点,增加
* <jms-topic name="ServerNotificationTopic">
<entry name="topic/ServerNotification"/>
<entry name="java:jboss/exported/jms/topic/ServerNotification"/>
</jms-topic>
*/
// 4) "create" the queue/topic (using the topic name - not JNDI)
//javax.jms.Topic topic = session.createTopic("ServerNotificationTopic");
javax.jms.Topic topic = (javax.jms.Topic)context.lookup("jms/topic/ServerNotification");
// 5) create producer
//javax.jms.MessageProducer producer = session.createProducer(topic);
Destination destination = (Destination) context.lookup("jms/topic/ServerNotification");
javax.jms.MessageProducer producer = session.createProducer(destination);
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) {
// 6) create message
TextMessage textMessage = session.createTextMessage();
textMessage.setText(line);
// 7) send message
producer.send(textMessage);
quitNow = line.equalsIgnoreCase("quit");
}
} while (!quitNow);
}
}
package com.lym.jms;
import java.util.Properties;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import javax.jms.JMSException;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class JMSSub {
private static final String DEFAULT_USERNAME = "testjms";
private static final String DEFAULT_PASSWORD = "123456";
private static final String INITIAL_CONTEXT_FACTORY = "org.jboss.naming.remote.client.InitialContextFactory";
private static final String PROVIDER_URL = "remote://localhost:4447";
/**
* @param args
* @throws NamingException
* @throws JMSException
* @throws InterruptedException
*/
public static void main(String[] args) throws NamingException, JMSException, InterruptedException {
final Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY);
env.put(Context.PROVIDER_URL, System.getProperty(Context.PROVIDER_URL, PROVIDER_URL));
env.put(Context.SECURITY_PRINCIPAL, System.getProperty("username", DEFAULT_USERNAME));
env.put(Context.SECURITY_CREDENTIALS, System.getProperty("password", DEFAULT_PASSWORD));
InitialContext context = new InitialContext(env);
// javax.jms.Topic topic = (javax.jms.Topic)context.lookup("jms/topic/ServerNotification");
// 1) lookup connection factory (local JNDI lookup, no credentials required)
javax.jms.ConnectionFactory cf = (javax.jms.ConnectionFactory)context.lookup("jms/RemoteConnectionFactory");
// 2) create a connection to the remote provider
javax.jms.Connection connection = cf.createConnection(DEFAULT_USERNAME, DEFAULT_PASSWORD);
// 3) create session session
boolean transacted = false;
javax.jms.Session session = connection.createSession(transacted, Session.AUTO_ACKNOWLEDGE);
// 4) "create" the queue/topic (using the topic name - not JNDI)
javax.jms.Topic topic = session.createTopic("ServerNotificationTopic");
// 5) create consumer
javax.jms.MessageConsumer consumer = session.createConsumer(topic); // messageSelector is optional
// 6) set listener
consumer.setMessageListener(new javax.jms.MessageListener() {
public void onMessage(javax.jms.Message message)
{
try {
TextMessage tm = (TextMessage)message;
System.out.println("received message content: "+tm.getText().toString());
System.out.println("getJMSDestination: "+tm.getJMSDestination());
System.out.println("getJMSReplyTo: "+tm.getJMSReplyTo());
System.out.println("getJMSMessageID: "+tm.getJMSMessageID());
System.out.println("getJMSRedelivered: "+tm.getJMSRedelivered());
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
// 7) listen for messages (start the connection)
connection.start();
//等待30秒退出
CountDownLatch latch = new CountDownLatch(1);
latch.await(30, TimeUnit.SECONDS);
}
}