Jboss7 JMS demo

最近温习了下EJB和JMS,整理了下思路,和大家分享下P2P和Pub/Sub的demo :arrow: ;JBoss 7 集成了HornetQ,JMS可以在HornetQ中间件运行,有时间在和大家分享关于HornetQ的文章。

1.下载Jboss 7并配置运行环境 http://www.jboss.org/jbossas/downloads
2.增加testjms用户(用以jms链接时使用),在jboss的bin目录下运行add-user.bat,如下:
[img]http://dl.iteye.com/upload/attachment/0071/0012/60e1796e-f05a-3b28-8431-2d85074536d8.jpg[/img]
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>


[b]P2P demo[/b]

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();
}
}
}
}



[img]http://dl.iteye.com/upload/attachment/0071/0087/79ce1b6a-c0c9-33f0-b4b6-723541c3d100.jpg[/img]


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();
}
}
}
}



[img]http://dl.iteye.com/upload/attachment/0071/0085/6fdc6ccc-2aa8-3fb7-b45d-77c45e7d7d1c.jpg[/img]


[b]Pub/Sub demo[/b]

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);


}

}


[img]http://dl.iteye.com/upload/attachment/0071/0091/03040566-ed87-316e-af68-30fde7c25597.jpg[/img]


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);


}


}


[img]http://dl.iteye.com/upload/attachment/0071/0095/605b80d0-7add-3128-a351-07b9b9f5a73c.jpg[/img]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值