最近温习了下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,如下: guest 一定要写。 
 
3.修改启动配置文件,使用standalone-full.xml启动jboss服务器

  1. $JBOSS_HOME$\bin>standalone.bat --server-config=standalone-full.xml


4.例子:修改Jboss配置文件standalone-full.xml,找到hornetq-server节点,在该节点下的jms-destinations确定含有以下配置:

  1. <jms-destinations>
  2. <jms-queue name="testQueue">
  3. <entry name="queue/test"/>
  4. <entry name="java:jboss/exported/jms/queue/test"/>
  5. </jms-queue>
  6. <jms-topic name="ServerNotificationTopic">
  7. <entry name="topic/ServerNotification"/>
  8. <entry name="java:jboss/exported/jms/topic/ServerNotification"/>
  9. </jms-topic>
  10. </jms-destinations>

客户端项目用eclipse集成jboss的 j2ee项目。runtime是jboss 7.

另外一定别忘了加入 external lib :jboss-client-7.1.0.Final.jar (JBOSS_HOME/bin/client) 
否则会报错:
javax.naming.NamingException: JBAS011843: Failed instantiate InitialContextFactory
 
 User: acs doesn't have permission='SEND' on address jms.queue.testQueue 权限错误,需要看看:
“jboss-home\stabdalone\configuration\application-roles.properties” 
加一句 testjms=guest
 
其他错误参见:
http://www.techartifact.com/blogs/2012/10/jboss-as-7-setting-up-hornetq-jms.html#sthash.OLzvKFO6.dpbs
 
在测试中遇到收不到消息。可以在控制台查看对应的queue有多少个comsumer。我的代码由于开始没有写consumer.close(). 导致接收完后虽然函数结束没有再调用receve阻塞方法了,但consumer一直存在。从jboss7的管理页面可以看到有好几个consumer。导致再次发送的消息还会被它吃掉。整了一天不断测试才搞明白。
 public Object Receive(String filter, long timeoutReceive) throws JMSException {
System.out.println ("======enter Receive===" );
System.out.println("Creating cosumer with filter: " + filter );
MessageConsumer consumer = queuesession.createConsumer(queue, filter); Message mrcv = null;
System.out.println("receive message with timeout="+timeoutReceive);
mrcv = consumer.receive(timeoutReceive);
if (mrcv != null) {
try {
System.out.println("RCV1: " + mrcv.getJMSCorrelationID());
System.out.println("====== consumer.close();.=====");
consumer.close();
return ((ObjectMessage) mrcv).getObject();;
} catch (MessageFormatException e) {
System.out.println("MessageFormatException: " + e.getMessage());
mrcv.acknowledge();
}
} else {
System.out.println("======receive message time out.=====");
}
consumer.close();
return null;
}
P2P demo

  1. package org.jboss.as.quickstarts.jms;
  2. import java.util.concurrent.CountDownLatch;
  3. import java.util.concurrent.TimeUnit;
  4. import java.util.logging.Logger;
  5. import java.util.Properties;
  6. import javax.jms.Connection;
  7. import javax.jms.ConnectionFactory;
  8. import javax.jms.Destination;
  9. import javax.jms.MessageConsumer;
  10. import javax.jms.MessageProducer;
  11. import javax.jms.Session;
  12. import javax.jms.TextMessage;
  13. import javax.naming.Context;
  14. import javax.naming.InitialContext;
  15. public class JMSProducer {
  16. private static final Logger log = Logger.getLogger(JMSProducer.class.getName());
  17. // Set up all the default values
  18. private static final String DEFAULT_MESSAGE = "Hello, World!";
  19. private static final String DEFAULT_CONNECTION_FACTORY = "jms/RemoteConnectionFactory";
  20. private static final String DEFAULT_DESTINATION = "jms/queue/test";
  21. private static final String DEFAULT_MESSAGE_COUNT = "1";
  22. private static final String DEFAULT_USERNAME = "testjms";
  23. private static final String DEFAULT_PASSWORD = "123456";
  24. private static final String INITIAL_CONTEXT_FACTORY = "org.jboss.naming.remote.client.InitialContextFactory";
  25. private static final String PROVIDER_URL = "remote://localhost:4447";
  26. public static void main(String[] args) throws Exception {
  27. ConnectionFactory connectionFactory = null;
  28. Connection connection = null;
  29. Session session = null;
  30. MessageProducer producer = null;
  31. Destination destination = null;
  32. TextMessage message = null;
  33. Context context = null;
  34. try {
  35. // Set up the context for the JNDI lookup
  36. final Properties env = new Properties();
  37. env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY);
  38. env.put(Context.PROVIDER_URL, System.getProperty(Context.PROVIDER_URL, PROVIDER_URL));
  39. env.put(Context.SECURITY_PRINCIPAL, System.getProperty("username", DEFAULT_USERNAME));
  40. env.put(Context.SECURITY_CREDENTIALS, System.getProperty("password", DEFAULT_PASSWORD));
  41. context = new InitialContext(env);
  42. // Perform the JNDI lookups
  43. String connectionFactoryString = System.getProperty("connection.factory", DEFAULT_CONNECTION_FACTORY);
  44. log.info("Attempting to acquire connection factory \"" + connectionFactoryString + "\"");
  45. connectionFactory = (ConnectionFactory) context.lookup(connectionFactoryString);
  46. log.info("Found connection factory \"" + connectionFactoryString + "\" in JNDI");
  47. String destinationString = System.getProperty("destination", DEFAULT_DESTINATION);
  48. log.info("Attempting to acquire destination \"" + destinationString + "\"");
  49. destination = (Destination) context.lookup(destinationString);
  50. log.info("Found destination \"" + destinationString + "\" in JNDI");
  51. // Create the JMS connection, session, producer, and consumer
  52. connection = connectionFactory.createConnection(System.getProperty("username", DEFAULT_USERNAME), System.getProperty("password", DEFAULT_PASSWORD));
  53. session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
  54. producer = session.createProducer(destination);
  55. connection.start();
  56. int count = Integer.parseInt(System.getProperty("message.count", DEFAULT_MESSAGE_COUNT));
  57. String content = System.getProperty("message.content", DEFAULT_MESSAGE);
  58. log.info("Sending " + count + " messages with content: " + content);
  59. // Send the specified number of messages
  60. for (int i = 0; i < count; i++) {
  61. message = session.createTextMessage(content);
  62. producer.send(message);
  63. }
  64. //等待30秒退出
  65. CountDownLatch latch = new CountDownLatch(1);
  66. latch.await(30, TimeUnit.SECONDS);
  67. } catch (Exception e) {
  68. log.severe(e.getMessage());
  69. throw e;
  70. } finally {
  71. if (context != null) {
  72. context.close();
  73. }
  74. // closing the connection takes care of the session, producer, and consumer
  75. if (connection != null) {
  76. connection.close();
  77. }
  78. }
  79. }
  80. }

  1. package org.jboss.as.quickstarts.jms;
  2. import java.util.concurrent.CountDownLatch;
  3. import java.util.concurrent.TimeUnit;
  4. import java.util.logging.Logger;
  5. import java.util.Properties;
  6. import javax.jms.Connection;
  7. import javax.jms.ConnectionFactory;
  8. import javax.jms.Destination;
  9. import javax.jms.MessageConsumer;
  10. import javax.jms.MessageProducer;
  11. import javax.jms.Session;
  12. import javax.jms.TextMessage;
  13. import javax.naming.Context;
  14. import javax.naming.InitialContext;
  15. public class JMSConsumer {
  16. private static final Logger log = Logger.getLogger(JMSConsumer.class.getName());
  17. // Set up all the default values
  18. private static final String DEFAULT_CONNECTION_FACTORY = "jms/RemoteConnectionFactory";
  19. private static final String DEFAULT_DESTINATION = "jms/queue/test";
  20. private static final String DEFAULT_USERNAME = "testjms";
  21. private static final String DEFAULT_PASSWORD = "123456";
  22. private static final String INITIAL_CONTEXT_FACTORY = "org.jboss.naming.remote.client.InitialContextFactory";
  23. private static final String PROVIDER_URL = "remote://localhost:4447";
  24. public static void main(String[] args) throws Exception {
  25. ConnectionFactory connectionFactory = null;
  26. Connection connection = null;
  27. Session session = null;
  28. MessageConsumer consumer = null;
  29. Destination destination = null;
  30. TextMessage message = null;
  31. Context context = null;
  32. try {
  33. // Set up the context for the JNDI lookup
  34. final Properties env = new Properties();
  35. env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY);
  36. env.put(Context.PROVIDER_URL, System.getProperty(Context.PROVIDER_URL, PROVIDER_URL));
  37. env.put(Context.SECURITY_PRINCIPAL, System.getProperty("username", DEFAULT_USERNAME));
  38. env.put(Context.SECURITY_CREDENTIALS, System.getProperty("password", DEFAULT_PASSWORD));
  39. context = new InitialContext(env);
  40. // Perform the JNDI lookups
  41. String connectionFactoryString = System.getProperty("connection.factory", DEFAULT_CONNECTION_FACTORY);
  42. log.info("Attempting to acquire connection factory \"" + connectionFactoryString + "\"");
  43. connectionFactory = (ConnectionFactory) context.lookup(connectionFactoryString);
  44. log.info("Found connection factory \"" + connectionFactoryString + "\" in JNDI");
  45. String destinationString = System.getProperty("destination", DEFAULT_DESTINATION);
  46. log.info("Attempting to acquire destination \"" + destinationString + "\"");
  47. destination = (Destination) context.lookup(destinationString);
  48. log.info("Found destination \"" + destinationString + "\" in JNDI");
  49. // Create the JMS connection, session, producer, and consumer
  50. connection = connectionFactory.createConnection(System.getProperty("username", DEFAULT_USERNAME), System.getProperty("password", DEFAULT_PASSWORD));
  51. session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
  52. consumer = session.createConsumer(destination);
  53. connection.start();
  54. //等待30秒退出
  55. CountDownLatch latch = new CountDownLatch(1);
  56. // Then receive the same number of messaes that were sent
  57. while(message == null) {
  58. log.info("----receive message");
  59. message = (TextMessage) consumer.receive(5000);
  60. latch.await(1, TimeUnit.SECONDS);
  61. }
  62. log.info("====Received message with content " + message.getText());
  63. } catch (Exception e) {
  64. log.severe(e.getMessage());
  65. throw e;
  66. } finally {
  67. if (context != null) {
  68. context.close();
  69. }
  70. // closing the connection takes care of the session, producer, and consumer
  71. if (connection != null) {
  72. connection.close();
  73. }
  74. }
  75. }
  76. }

Pub/Sub demo

  1. package com.lym.jms;
  2. import java.io.BufferedReader;
  3. import java.io.IOException;
  4. import java.io.InputStreamReader;
  5. import java.util.Properties;
  6. import javax.jms.Destination;
  7. import javax.jms.JMSException;
  8. import javax.jms.Session;
  9. import javax.jms.TextMessage;
  10. import javax.naming.Context;
  11. import javax.naming.InitialContext;
  12. import javax.naming.NamingException;
  13. public class JMSPub {
  14. private static final String DEFAULT_USERNAME = "testjms";
  15. private static final String DEFAULT_PASSWORD = "123456";
  16. private static final String INITIAL_CONTEXT_FACTORY = "org.jboss.naming.remote.client.InitialContextFactory";
  17. private static final String PROVIDER_URL = "remote://localhost:4447";
  18. /**
  19. * @param args
  20. * @throws NamingException
  21. * @throws JMSException
  22. * @throws IOException
  23. */
  24. public static void main(String[] args) throws NamingException, JMSException, IOException {
  25. final Properties env = new Properties();
  26. env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY);
  27. env.put(Context.PROVIDER_URL, System.getProperty(Context.PROVIDER_URL, PROVIDER_URL));
  28. env.put(Context.SECURITY_PRINCIPAL, System.getProperty("username", DEFAULT_USERNAME));
  29. env.put(Context.SECURITY_CREDENTIALS, System.getProperty("password", DEFAULT_PASSWORD));
  30. InitialContext context = new InitialContext(env);
  31. // 1) lookup connection factory (local JNDI lookup, no credentials required)
  32. javax.jms.ConnectionFactory cf = (javax.jms.ConnectionFactory)context.lookup("jms/RemoteConnectionFactory");
  33. // 2) create a connection to the remote provider
  34. javax.jms.Connection connection = cf.createConnection(DEFAULT_USERNAME, DEFAULT_PASSWORD);
  35. // 3) create session session
  36. boolean transacted = false;
  37. javax.jms.Session session = connection.createSession(transacted, Session.AUTO_ACKNOWLEDGE);
  38. /**
  39. * 在standalone-full.xml中找到
  40. * <subsystem xmlns="urn:jboss:domain:messaging:1.1">
  41. * 节点下找到<jms-destinations>节点,增加
  42. *  <jms-topic name="ServerNotificationTopic">
  43. <entry name="topic/ServerNotification"/>
  44. <entry name="java:jboss/exported/jms/topic/ServerNotification"/>
  45. </jms-topic>
  46. */
  47. // 4) "create" the queue/topic (using the topic name - not JNDI)
  48. //javax.jms.Topic topic = session.createTopic("ServerNotificationTopic");
  49. javax.jms.Topic topic = (javax.jms.Topic)context.lookup("jms/topic/ServerNotification");
  50. // 5) create producer
  51. //javax.jms.MessageProducer producer = session.createProducer(topic);
  52. Destination destination = (Destination) context.lookup("jms/topic/ServerNotification");
  53. javax.jms.MessageProducer producer = session.createProducer(destination);
  54. BufferedReader msgStream = new BufferedReader(new InputStreamReader(
  55. System.in));
  56. String line = null;
  57. boolean quitNow = false;
  58. do {
  59. System.out.print("Enter message (\"quit\" to quit): ");
  60. line = msgStream.readLine();
  61. if (line != null && line.trim().length() != 0) {
  62. // 6) create message
  63. TextMessage textMessage = session.createTextMessage();
  64. textMessage.setText(line);
  65. // 7) send message
  66. producer.send(textMessage);
  67. quitNow = line.equalsIgnoreCase("quit");
  68. }
  69. } while (!quitNow);
  70. }
  71. }

  1. package com.lym.jms;
  2. import java.util.Properties;
  3. import java.util.concurrent.CountDownLatch;
  4. import java.util.concurrent.TimeUnit;
  5. import javax.jms.JMSException;
  6. import javax.jms.Session;
  7. import javax.jms.TextMessage;
  8. import javax.naming.Context;
  9. import javax.naming.InitialContext;
  10. import javax.naming.NamingException;
  11. public class JMSSub {
  12. private static final String DEFAULT_USERNAME = "testjms";
  13. private static final String DEFAULT_PASSWORD = "123456";
  14. private static final String INITIAL_CONTEXT_FACTORY = "org.jboss.naming.remote.client.InitialContextFactory";
  15. private static final String PROVIDER_URL = "remote://localhost:4447";
  16. /**
  17. * @param args
  18. * @throws NamingException
  19. * @throws JMSException
  20. * @throws InterruptedException
  21. */
  22. public static void main(String[] args) throws NamingException, JMSException, InterruptedException {
  23. final Properties env = new Properties();
  24. env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY);
  25. env.put(Context.PROVIDER_URL, System.getProperty(Context.PROVIDER_URL, PROVIDER_URL));
  26. env.put(Context.SECURITY_PRINCIPAL, System.getProperty("username", DEFAULT_USERNAME));
  27. env.put(Context.SECURITY_CREDENTIALS, System.getProperty("password", DEFAULT_PASSWORD));
  28. InitialContext context = new InitialContext(env);
  29. //      javax.jms.Topic topic = (javax.jms.Topic)context.lookup("jms/topic/ServerNotification");
  30. // 1) lookup connection factory (local JNDI lookup, no credentials required)
  31. javax.jms.ConnectionFactory cf = (javax.jms.ConnectionFactory)context.lookup("jms/RemoteConnectionFactory");
  32. // 2) create a connection to the remote provider
  33. javax.jms.Connection connection = cf.createConnection(DEFAULT_USERNAME, DEFAULT_PASSWORD);
  34. // 3) create session session
  35. boolean transacted = false;
  36. javax.jms.Session session = connection.createSession(transacted, Session.AUTO_ACKNOWLEDGE);
  37. // 4) "create" the queue/topic (using the topic name - not JNDI)
  38. javax.jms.Topic topic = session.createTopic("ServerNotificationTopic");
  39. // 5) create consumer
  40. javax.jms.MessageConsumer consumer = session.createConsumer(topic); // messageSelector is optional
  41. // 6) set listener
  42. consumer.setMessageListener(new javax.jms.MessageListener() {
  43. public void onMessage(javax.jms.Message message)
  44. {
  45. try {
  46. TextMessage tm = (TextMessage)message;
  47. System.out.println("received message content: "+tm.getText().toString());
  48. System.out.println("getJMSDestination: "+tm.getJMSDestination());
  49. System.out.println("getJMSReplyTo: "+tm.getJMSReplyTo());
  50. System.out.println("getJMSMessageID: "+tm.getJMSMessageID());
  51. System.out.println("getJMSRedelivered: "+tm.getJMSRedelivered());
  52. } catch (JMSException e) {
  53. // TODO Auto-generated catch block
  54. e.printStackTrace();
  55. }
  56. }
  57. });
  58. // 7) listen for messages (start the connection)
  59. connection.start();
  60. //等待30秒退出
  61. CountDownLatch latch = new CountDownLatch(1);
  62. latch.await(30, TimeUnit.SECONDS);
  63. }
  64. }

jboss jms 实例的更多相关文章

  1. ActionMQ5.8.0 JMS实例 手把手详细图解

    出自:http://blog.csdn.net/tongjie008/article/details/40687087 ActionMQ 是开源的JMS实现 1.下载ActiveMQ 去官方网站下载: ...

  2. 一台机器运行多个JBoss多实例

    JBossXMLJVMTomcat应用服务器  我们经常会遇到这种情况,有时候希望在同一台机器上部署若干个JBoss实例,上面运行不同的应用程序,这样的话无论由于什么原因需要对某个JBoss实例进行关 ...

  3. 配置JBOSS多实例

    在使用Jbossserver时.非常多情况我们须要配置多个实例,以下为大家介绍JBoss里怎样配置多实例,以Jboss5.1为例介绍. 1.复制${JBOSS_HOME}\server\default ...

  4. 简单的JMS实例

    1.首先需要一台JMS的提供者,在这里我选择使用的是apache-activemq-5.3.2这个服务器,首先下载服务器并通过bin目录下的activemq.bat启动服务器,此时可通过http:// ...

  5. 通过spring整合activeMQ实现jms实例

    写的很详细 http://blog.csdn.net/leonardo9029/article/details/43154385

  6. Jboss ESB简介及开发实例

    一.Jboss ESB的简介 1. 什么是ESB.         ESB的全称是Enterprise Service Bus,即企业服务总线.ESB是过去消息中间件的发展,ESB采用了“总线”这样一 ...

  7. Linux下关闭JBoss实例

    本文内容: 查看JBoss运行实例 #ps -ef|grep java 上图就是运行结果(部分结果),其中一个服务器上可能会运行多个JBOSS server实例,找到你需要看的那个. 其中 ps -e ...

  8. JBoss EAP应用服务器部署方法和JBoss 开发JMS消息服务小例子

    一.download JBoss-EAP-6.2.0GA: http://jbossas.jboss.org/downloads JBoss Enterprise Application Platfo ...

  9. ActiveMQ学习总结(5)——Java消息服务JMS详解

    JMS: Java消息服务(Java Message Service) JMS是用于访问企业消息系统的开发商中立的API.企业消息系统可以协助应用软件通过网络进行消息交互. JMS的编程过程很简单,概 ...

随机推荐

  1. ffmpeg在shell循环中只执行一次问题

    最近写了一个shell脚本,发现 ffmpeg 命令只执行了一次就停了,最后找到原因: ffmpeg有时会读取标准输入流,导致命令出错,解决办法是在ffmpeg命令之后添加 #xxx ffmpeg x ...

  2. [POJ1284]Primitive Roots(原根性质的应用)

    题目:http://poj.org/problem?id=1284 题意:就是求一个奇素数有多少个原根 分析: 使得方程a^x=1(mod m)成立的最小正整数x是φ(m),则称a是m的一个原根 然后 ...

  3. Vmware player 12

    免费版的虚拟机Vmware,体积小.运行快速... 官方下载界面 下载地址: http://yunpan.cn/cm5smywVvqS8V  访问密码 35ac 官方下载:点击下载

  4. 简单的解释XSS攻击

    XSS 跨站点脚本 cross site script 怎么造成攻击? 举例:有一个公共的页面,所有用户都可以访问且可以保存内容,输入的时候若输入<script>alert('I am h ...

  5. 1018LINUX中crontab的用法

    转自http://blog.csdn.net/ethanzhao/article/details/4406017#comments 基本格式 :* * * * * command分 时 日 月 周 命 ...

  6. 非常实用的jquery版表单验证

    <!DOCTYPE html><html> <head> <meta charset="UTF-8"> <script src ...

  7. 分析函数——keep(dense_rank first/last)

    来源于:http://blog.itpub.net/28929558/viewspace-1182183/ 销售表:SQL> select * from criss_sales where de ...

  8. Java--笔记(5)

    41.面向对象的五大基本原则 (1)单一职责原则(SRP) (2)开放封闭原则(OCP) (3)里氏替换原则(LSP) (4)依赖倒置原则(DIP) (5)接口隔离原则(ISP) 单一职责原则(SRP ...

  9. mysql 备份恢复图

    http://blog.csdn.net/oldboy8/article/details/8294631

  10. Extract Fasta Sequences Sub Sets by position

    cut -d " " -f 1 sequences.fa | tr -s "\n" "\t"| sed -s 's/>/\n/g' & ...