---
title: "Message Driven Bean"
author: "linhrg"
date: "2011-10-11T15:06:22Z"
tags: []
categories: ["企业架构"]
slug: "message-driven-bean"
draft: false
lastmod: "2011-10-11T15:06:22Z"
id: 1189652
url: "https://linhrg.iteye.com/blog/1189652"
---

MDB是一个当消息达到时被容器调用的异步消息消费程序。

MDB用来处理基于消息的请求组件，它是一个异步的无状态Session Bean

在MDB中，Web端发送消息的一般步骤如下：

1、查找一个JNDI来初始化上下文环境，如：

```
Properties props = new Properties();
props.setProperty("java.naming.factory.initial","org.jnp.interfaces.NamingContextFactory");
props.setProperty("java.naming.provider.url", "localhost:1099");
props.setProperty("java.naming.factory.url.pkgs","org.jboss.naming");
InitialContext ctx = new InitialContext(props);
```

 2、根据上下文环境来查找一个连接工厂QueueConnectionFactory或者TopicConnectFactory，P2P模型中应用的是QueueConnectionFactory，Pub/Sub模型中应用的是TopicConnectFactory，如下代码：

```
QueueConnectionFactory factory = (QueueConnectionFactory) ctx.lookup("ConnectionFactory");
```

 3、从连接工厂获得一个连接，如：

conn = factory.createQueueConnection();

```
conn = factory.createQueueConnection();
```

4、通过连接来建立一个Session，如：

```
session = conn.createQueueSession(false,QueueSession.AUTO_ACKNOWLEDGE);
```

5、查找目的地：

```
Destination destination = (Queue) ctx.lookup("queue/BeanTest");
```

 6、根据会话，目的地建立消息生产者：

```
// 创建消息生产者
MessageProducer producer = session.createProducer(destination);
// 创建所要发送的文本信息
TextMessage msg = session.createTextMessage("Bean测试");
// 发送消息
producer.send(msg);
```