`
huhupure
  • 浏览: 4660 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
最近访客 更多访客>>
文章分类
社区版块
存档分类
最新评论

如何在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("呵呵,其实没错") ;

}

}

请大家帮忙看看.
分享到:
评论

相关推荐

    activemq-web-5.3.0.jar.zip

    Java消息服务(JMS)是Java平台上的标准接口,用于在分布式环境中发送、接收和管理消息。ActiveMQ作为JMS实现,提供了一种可靠的方式来交换数据,尤其适合处理异步通信和解耦系统组件。 3. **Web集成** activemq-...

    activeMq in action 使用activeMq开发JMS的简单讲述

    3. **多种协议**:除了JMS之外,ActiveMQ还支持STOMP、AMQP、MQTT等多种消息传输协议,增加了系统的兼容性。 4. **高可用性**:通过网络集群和故障转移,ActiveMQ可以实现高可用性和负载均衡,确保服务不间断。 5. *...

    ActiveMq-JMS好用实例详解

    下面介绍如何将ActiveMQ与Tomcat整合,以便在Web应用中使用JMS。 ##### 准备工作 1. **准备JAR包** 将ActiveMQ `lib` 目录下的5个核心JAR包复制到Tomcat `lib` 目录下: - `activemq-core-5.1.0.jar` - `...

    axisJMSSample

    - **JMS 发送者** (JMS Sender):将消息转换为JMS格式,并通过JMS网络发送。 - **JMS 监听器** (JMS Listener):监听JMS网络上的消息。 - **Axis 引擎服务** (Axis Engine Service):处理接收到的消息并提供相应的...

    Java Web开发常用API合集

    除此之外,可能还包括其他的辅助API,如JNDI(Java Naming and Directory Interface)用于查找和管理资源,JTA(Java Transaction API)处理事务管理,JMS(Java Message Service)提供消息传递服务,以及EL...

    rabbitmq研究与应用

    - **交换器** 负责接收来自消息生产者的消息,并根据消息的路由信息将其发送到相应的队列中。每个虚拟主机内的交换器都有唯一的名称。交换器可以是持久的、临时的或自动删除的。 - **持久交换器** 会一直存在,直到...

    精通J2EE--Eclipse、Struts、Hibernate及Spring整合应用案例.doc

    - **创建和发布Web应用**:可以手动部署Web应用,也可以使用Eclipse + MyEclipse等IDE来简化部署过程。 #### Java Servlet - **Servlet简介**:Servlet是一种基于Java的Web技术,用于动态生成Web页面。 - **...

    ActiveMQ In Action

    ActiveMQ作为Java消息服务(JMS)的实现,它在企业级应用集成中扮演着关键角色,负责处理系统间的异步通信和解耦。 一、ActiveMQ简介 ActiveMQ是Apache软件基金会开发的一款开源消息代理,它支持多种协议,如...

    apache-activemq-5.15.2

    JMS是Java平台上的一个标准接口,它定义了应用程序如何创建、发送、接收和读取消息。通过使用JMS,开发者可以在应用程序之间传递数据,而无需两者之间有直接的交互,这有助于实现系统的松耦合和可扩展性。 Apache ...

    spring webService1.51官方指南[pdf]

    Email 传输方式允许 Web Service 通过电子邮件发送和接收消息,这在某些场景下非常有用。 **5.3.5 内嵌 HTTP 服务器传输** 内嵌 HTTP 服务器是一种轻量级的选择,适用于测试环境或不需要独立部署的服务。 **5.4 ...

    JavaEE 学习,各种小案例代码

    JavaEE 是一种企业级应用程序开发框架,用于构建可扩展、高度交互的Web应用程序。这个学习资源包包含了多种JavaEE的小型实例代码,是学习和掌握JavaEE技术的有效途径。JavaEE平台由一系列标准组件组成,如Servlet、...

    Java EE培训课件

    这些组件和服务使得开发者能够构建可扩展、高并发、安全且健壮的Web应用程序。 1. Servlet:Servlet是Java EE中的核心组件之一,它是一个Java类,用于扩展服务器的功能。Servlet可以接收HTTP请求,处理数据,然后...

    2017 javaEE32期黑马培训视频(完整版)

    JSP最终会被编译为Servlet,简化了Web应用的开发。 3. EJB(Enterprise JavaBeans):EJB是JavaEE中的核心组件,用于构建可复用的、分布式的、事务管理的企业级服务。EJB有三种类型:会话bean(Session Beans)、...

    Manning ActiveMQ in action chapter1

    JMS定义了一组接口和规范,允许开发者编写能够在任何支持JMS的消息中间件上运行的应用程序。 ### 二、Apache ActiveMQ简介 #### Apache ActiveMQ概述 Apache ActiveMQ是基于JMS 1.1和AMQP标准的最流行的高性能消息...

    ActiveMQ教程

    其核心概念是允许独立的应用程序在不同的系统中通过消息队列进行通信。 ### ActiveMQ核心功能和特点 - **遵循JMS和J2EE规范**:ActiveMQ提供JMS规范的完整实现,支持JMS 1.1中的所有功能,包括持久化、事务(XA消息...

    全面解析j2ee系统

    开发Web应用时,必须依赖于这些容器提供的支持。 - **API**:在Web技术中,除了JSP/Servlet之外,通常还需要JavaBeans或Java Class来实现特定功能或封装数据。 - **JavaBeans**:是Java中的一种组件技术,用于实现...

    apache-artemis.rar 最新jar 好用不得了

    2. **多协议支持**:除了JMS之外,Artemis还支持AMQP、STOMP、MQTT等多种消息协议,使得它能够与各种语言和平台无缝集成。 3. **持久化**:Artemis提供了灵活的持久化选项,包括基于文件的存储和完全事务化的数据库...

    javaeetutorial7

    - Java Message Service(JMS):提供了在两个应用之间,通过异步消息传递的方式进行通信的API。 - JavaMail:提供了一套用于读取、撰写和发送电子邮件的应用程序接口。 此外,Java EE 7还引入了对HTML5和WebSocket...

Global site tag (gtag.js) - Google Analytics