如何在WEB应用之外向其发送jms消息

使用SPRING结合ActiveMQ通过JNDI的方式在一个WEB应用中配置了JMS消息服务,在WEB 应用程序内部的一个ACTION中测了一下,当ACTION被执行时(ACTION中含发送消息的代码),能触发JMS消息服务的监听方法自动执行,但把ACTION中的代码单独放到一个带main方法的类中独立运行,则消息服务器的监听方法不会被执行.
以下是JMS消息在WEB应用中的配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id="jndiTemplate" class="org.springframework.jndi.JndiTemplate" lazy-init="default" autowire="default" dependency-check="default">
<property name="environment">
<props>
<prop key="java.naming.factory.initial">org.apache.activemq.jndi.ActiveMQInitialContextFactory</prop>
<!-- lets register some destinations -->
<prop key="topic.MyTopic">MyTopic</prop>
</props>
</property>
</bean>

<!-- look up the JMS ConnectionFactory in JNDI -->
<bean id="myConnectionFactory" class="org.springframework.jndi.JndiObjectFactoryBean" lazy-init="default" autowire="default" dependency-check="default">
<property name="jndiTemplate"><ref bean="jndiTemplate" /></property>
<property name="jndiName"><value>ConnectionFactory</value></property>
</bean>

<!-- look up the Destination in JNDI -->
<bean id="myDestination" class="org.springframework.jndi.JndiObjectFactoryBean" lazy-init="default" autowire="default" dependency-check="default">
<property name="jndiTemplate"><ref bean="jndiTemplate"/></property>
<property name="jndiName"><value>MyTopic</value></property>
</bean>

<bean id="myJmsTemplate" class="org.springframework.jms.core.JmsTemplate" lazy-init="default" autowire="default" dependency-check="default">
<property name="pubSubDomain"><value>true</value></property>
<property name="connectionFactory">
<!-- lets wrap in a pool to avoid creating a connection per send -->
<bean class="org.springframework.jms.connection.SingleConnectionFactory" lazy-init="default" autowire="default" dependency-check="default">
<property name="targetConnectionFactory"><ref bean="myConnectionFactory" /></property>
</bean>
</property>
<property name="defaultDestination"><ref bean="myDestination" /></property>
</bean>

<bean id="consumerJmsTemplate" class="org.springframework.jms.core.JmsTemplate" lazy-init="default" autowire="default" dependency-check="default">
<property name="pubSubDomain"><value>true</value></property>
<property name="connectionFactory" ref="myConnectionFactory" />
<property name="defaultDestination"><ref bean="myDestination" /></property>
</bean>


<bean id="messageSender" class="com.hxcy.service.TestSend">
<property name="jmsTemplate" ref="myJmsTemplate"/>
</bean>

<bean id="updateMapService" class="com.hxcy.service.UpdateMapService"/>

<bean id="mapMsgListener" class="org.springframework.jms.listener.adapter.MessageListenerAdapter">
<constructor-arg ref="updateMapService"/>
<property name="defaultListenerMethod" value="update"/>
</bean>
<bean id="listenerContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="connectionFactory" ref="myConnectionFactory"/>
<property name="messageListener" ref="mapMsgListener"/>
<property name="destination" ref="myDestination"/>
</bean>


<bean id="paramResolver" class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver">
<property name="paramName"><value>method</value></property>
</bean>
<bean name="/message.do" class="org.springframework.web.servlet.mvc.multiaction.MultiActionController">
<property name="methodNameResolver"><ref bean="paramResolver"/></property>
<property name="delegate"><ref bean="messageAction"/></property>
</bean>
<bean id="messageAction" class="com.hxcy.action.MessageAction">
<property name="messageSender"><ref bean="messageSender"/></property>
</bean>

<bean id="handlerMapping" class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
<bean name="/index.do" class="org.springframework.web.servlet.mvc.ParameterizableViewController">
<property name="viewName">
<value>index.jsp</value>
</property>
</bean>

</beans>

以下是jndi.properties文件中的配置:
## ---------------------------------------------------------------------------
## Licensed to the Apache Software Foundation (ASF) under one or more
## contributor license agreements. See the NOTICE file distributed with
## this work for additional information regarding copyright ownership.
## The ASF licenses this file to You under the Apache License, Version 2.0
## (the "License"); you may not use this file except in compliance with
## the License. You may obtain a copy of the License at
##
## http://www.apache.org/licenses/LICENSE-2.0
##
## Unless required by applicable law or agreed to in writing, software
## distributed under the License is distributed on an "AS IS" BASIS,
## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
## See the License for the specific language governing permissions and
## limitations under the License.
## ---------------------------------------------------------------------------

# START SNIPPET: jndi

java.naming.factory.initial = org.apache.activemq.jndi.ActiveMQInitialContextFactory

# use the following property to configure the default connector
java.naming.provider.url = vm://localhost:61616

# use the following property to specify the JNDI name the connection factory
# should appear as.
#connectionFactoryNames = connectionFactory, queueConnectionFactory, topicConnectionFactry

# register some queues in JNDI using the form
# queue.[jndiName] = [physicalName]
queue.MyQueue=MyQueue


# register some topics in JNDI using the form
# topic.[jndiName] = [physicalName]
topic.MyTopic=MyTopic

# END SNIPPET: jndi

以下是发送类的代码:
package com.hxcy.test ;
/**
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.util.Arrays;
import java.util.Date;

import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.util.IndentPrinter;

/**
* A simple tool for publishing messages
*
* @version $Revision: 1.2 $
*/
public class ProducerTool {

private Destination destination;
private int messageCount = 10;
private long sleepTime = 0L;
private boolean verbose = true;
private int messageSize = 255;
private long timeToLive;
private String user = ActiveMQConnection.DEFAULT_USER;
private String password = ActiveMQConnection.DEFAULT_PASSWORD;
private String url = "vm://localhost:61616" ;//ActiveMQConnection.DEFAULT_BROKER_URL;
private String subject = "MyTopic" ;//"TOOL.DEFAULT";
private boolean topic = true ; //false;
private boolean transacted = true; //false;
private boolean persistent = true; //false;

public static void main(String[] args) {
ProducerTool producerTool = new ProducerTool();
//String[] unknonwn = CommnadLineSupport.setOptions(producerTool, args);
//if( unknonwn.length > 0 ) {
// System.out.println("Unknown options: "+Arrays.toString(unknonwn));
// System.exit(-1);
//}
producerTool.run();
}

public void run() {
Connection connection=null;
try {
//System.out.println("Connecting to URL: " + url);
//System.out.println("Publishing a Message with size " + messageSize+ " to " + (topic ? "topic" : "queue") + ": " + subject);
//System.out.println("Using " + (persistent ? "persistent" : "non-persistent") + " messages");
//System.out.println("Sleeping between publish " + sleepTime + " ms");
if (timeToLive != 0) {
System.out.println("Messages time to live " + timeToLive + " ms");
}

// Create the connection.
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, url);
connection = connectionFactory.createConnection();
connection.start();

// Create the session
Session session = connection.createSession(transacted, Session.AUTO_ACKNOWLEDGE);
System.out.println("session=" + session ) ;
if (topic) {
destination = session.createTopic(subject);
System.out.println("destination=" + destination) ;
} else {
destination = session.createQueue(subject);
}

// Create the producer.
MessageProducer producer = session.createProducer(destination);
System.out.println("producer=" + producer) ;

if (persistent) {
producer.setDeliveryMode(DeliveryMode.PERSISTENT);
} else {
producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
}
if (timeToLive != 0)
producer.setTimeToLive(timeToLive);

// Start sending messages
sendLoop(session, producer);

System.out.println("Done.");

// Use the ActiveMQConnection interface to dump the connection stats.
ActiveMQConnection c = (ActiveMQConnection) connection;
c.getConnectionStats().dump(new IndentPrinter());

} catch (Exception e) {
System.out.println("出错:----------------------");
System.out.println("Caught: " + e);
e.printStackTrace();
} finally {
try {
connection.close();
} catch (Throwable ignore) {
}
}
}

protected void sendLoop(Session session, MessageProducer producer)
throws Exception {

for (int i = 0; i < messageCount || messageCount == 0; i++) {

TextMessage message = session
.createTextMessage(createMessageText(i));

if (verbose) {
String msg = message.getText();
if (msg.length() > 50) {
msg = msg.substring(0, 50) + "...";
}
System.out.println("Sending message: " + msg);
}

producer.send(message);
if (transacted) {
session.commit();
}

Thread.sleep(sleepTime);

}

}

private String createMessageText(int index) {
StringBuffer buffer = new StringBuffer(messageSize);
buffer.append("Message: " + index + " sent at: " + new Date());
if (buffer.length() > messageSize) {
return buffer.substring(0, messageSize);
}
for (int i = buffer.length(); i < messageSize; i++) {
buffer.append(' ');
}
return buffer.toString();
}


public void setPersistent(boolean durable) {
this.persistent = durable;
}
public void setMessageCount(int messageCount) {
this.messageCount = messageCount;
}
public void setMessageSize(int messageSize) {
this.messageSize = messageSize;
}
public void setPassword(String pwd) {
this.password = pwd;
}
public void setSleepTime(long sleepTime) {
this.sleepTime = sleepTime;
}
public void setSubject(String subject) {
this.subject = subject;
}
public void setTimeToLive(long timeToLive) {
this.timeToLive = timeToLive;
}
public void setTopic(boolean topic) {
this.topic = topic;
}
public void setQueue(boolean queue) {
this.topic = !queue;
}
public void setTransacted(boolean transacted) {
this.transacted = transacted;
}
public void setUrl(String url) {
this.url = url;
}
public void setUser(String user) {
this.user = user;
}
public void setVerbose(boolean verbose) {
this.verbose = verbose;
}
}


以下是消息监听的代码:
package com.hxcy.service;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class UpdateMapService {

protected final Log logger = LogFactory.getLog(getClass());
public void update(String msg)
{
System.out.println("开始更新地图.") ;
logger.error("呵呵,其实没错") ;

}

}

请大家帮忙看看.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值