gpt4 book ai didi

java - 带有数据源的消息驱动 Bean

转载 作者:行者123 更新时间:2023-11-30 09:58:54 25 4
gpt4 key购买 nike

我的问题是如何配置 EJB 3.0 风格的消息驱动 bean 以在 jboss 中使用已配置的 JMS 数据源。

例如,我的 MDB 看起来像这样:

@MessageDriven(mappedName = "ExampleMDB", activationConfig = {

@ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Topic"),
@ActivationConfigProperty(propertyName = "destination", propertyValue = "MyTopic"),
@ActivationConfigProperty(propertyName = "channel", propertyValue = "MyChannel"),

})
@ResourceAdapter(value = "wmq.jmsra.rar")
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
@TransactionManagement(TransactionManagementType.BEAN)
public class MyMDB implements MessageListener {
.....
}

但我希望 bean 附加到给定的 JMS 数据源(在 jboss 4.2.2 的情况下,这是在 deploy/jms/jms-ds.xml 中)。也许这甚至是不可能的,但值得一问。

最佳答案

如果我对你的问题的理解正确,MyMDB 会听取 WebLogic 上的一个主题,并且你想使用 JBoss 提供的附加 JMS 目标,该目标在已部署的配置文件中定义并由其 JNDI 名称标识(默认情况下,deploy/jms/jms-ds.xml 仅包含 JMS 提供程序和连接工厂的配置——没有数据源)。

最简单的方法是让容器通过其 JNDI 名称注入(inject) JMS 目的地和连接工厂(在 JBoss 中,JMS 目的地由 deploying xxx-service.xml files 配置)。在启动时,您可以初始化连接,并在 MDB 释放后立即执行清理。

以下示例显示注入(inject) (@Resource) 和资源管理 (@PostConstruct@PreDestroy)。 JMS 连接和目标在 useJmsDestination(String) 中用于发送文本消息。

public class MyMDB implements MessageListener {

@Resource(mappedName = "queue/YourQueueName") // can be topic too
private Queue targetDestination;

@Resource(mappedName = "QueueConnectionFactory") // or ConnectionFactory
private QueueConnectionFactory factory;

private Connection conn;

public void onMessage(Message m) {
// parse message and do what you need to do
...
// do something with the message and the JBoss JMS destination
useJmsDestination(messageString);
}

private void useJmsDestination(String text) {
Session session = null;
MessageProducer producer = null;

try {
session = conn.createSession(true, Session.AUTO_ACKNOWLEDGE);
producer = session.createProducer(targetDestination);
TextMessage msg = session.createTextMessage(text);
producer.send(msg);
} catch (JMSException e) {
throw new RuntimeException(e);
} finally {
try {
if (producer != null) {
producer.close();
}
if (session != null) {
session.close();
}
} catch (JMSException e) {
// handle error, should be non-fatal, as the message is already sent.
}
}
}


@PostConstruct
void init() {
initConnection();
// other initialization logic
...
}

@PreDestroy
void cleanUp() {
closeConnection();
// other cleanup logic
...
}

private void initConnection() {
try {
conn = factory.createConnection();
} catch (JMSException e) {
throw new RuntimeException("Could not initialize connection", e);
}
}

private void closeConnection() {
try {
conn.close();
} catch (JMSException e) {
// handle error, should be non-fatal, as the connection is being closed
}
}
}

希望对您有所帮助。

关于java - 带有数据源的消息驱动 Bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/260594/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com