在使用jboss5进行MDB的试验时首先要在jboss5中配置jms 队列。
1)在jboss安装目录下:server\default\deploy\messaging
打开destinations-service.xml文件,加入:
<mbean code="org.jboss.jms.server.destination.QueueService" name="jboss.messaging.destination:service=Queue,name=ExpiryQueue" xmbean-dd="xmdesc/Queue-xmbean.xml"> <depends optional-attribute-name="ServerPeer">jboss.messaging:service=ServerPeer</depends> <depends>jboss.messaging:service=PostOffice</depends> </mbean>
启动jboss5,进入http://localhost:8080/jmx-console/(需要事先设置用户名、密码)
在右侧界面点击 service=JNDIViews ----> 点击List对应的invoke按钮,若出现下图对应的Queue JNDI配置则表示jms Queue队列配置成功
2)编写MDB
java代码如下:
import javax.ejb.ActivationConfigProperty; import javax.ejb.MessageDriven; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.TextMessage; @MessageDriven(activationConfig = { @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"), @ActivationConfigProperty(propertyName = "destination", propertyValue = "queue/ExpiryQueue") } ) public class MyQueueMDBBean implements MessageListener { public void onMessage(Message arg0) { try { TextMessage tm = (TextMessage) arg0; System.out.println("MDB接收到一个消息=" + tm.getText()); } catch (JMSException e) { e.printStackTrace(); } } }
3)客户端编写
java代码如下:(需要引入jboss安装包下client文件夹中的jar文件)
import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.MessageProducer; import javax.jms.Queue; import javax.jms.QueueSession; import javax.jms.Session; import javax.jms.TextMessage; import javax.naming.Context; import javax.naming.InitialContext; public class Point2PClient { public static void main(String[] args) throws Exception { Context context = new InitialContext(); ConnectionFactory factory = (ConnectionFactory) context .lookup("ConnectionFactory"); Queue queue = (Queue) context.lookup("queue/ExpiryQueue"); Connection connection = factory.createConnection(); Session session = connection.createSession(false, QueueSession.AUTO_ACKNOWLEDGE); TextMessage msg = session.createTextMessage("这是一个文本:####pppppp"); MessageProducer sender = session.createProducer(queue); sender.send(msg); session.close(); connection.close(); System.out.println("+++++Success"); } }
配置文件如下:(需放置在工程的src下)
java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
java.naming.provider.url=localhost
4)运行结果如下:
注意事项:
1.javax.naming.NameNotFoundException: mytopic not bound
出现该异常表示你的jms队列配置错误,或EJB和客户端中的jms队列写错
2.Toipc队列的配置和使用方式与Queue方式类似,可以试着尝试将上述代码中的Queue改为Topic进行尝试