博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring mvc4 + ActiveMQ 整合
阅读量:5155 次
发布时间:2019-06-13

本文共 12061 字,大约阅读时间需要 40 分钟。

转载:http://www.cnblogs.com/leiOOlei/p/5075402.html

 

一、配置部分

ActiveMQ的安装这就不说了,很简单,

这个例子采用maven构建,首先看一下pom.xml

4.0.0
com.gzframe.demo
gzframe
war
0.0.1-SNAPSHOT
gzframe Maven Webapp
http://maven.apache.org
4.1.8.RELEASE
3.1.0
junit
junit
4.10
test
jstl
jstl
1.2
javax.servlet
servlet-api
${javax.servlet}
org.springframework
spring-core
${springframework}
org.springframework
spring-context
${springframework}
org.springframework
spring-tx
${springframework}
org.springframework
spring-webmvc
${springframework}
org.springframework
spring-jms
${springframework}
org.apache.xbean
xbean-spring
3.16
org.apache.activemq
activemq-core
5.7.0
org.apache.activemq
activemq-pool
5.12.1
gzframe

接下来看一下web.xml,如下

Archetype Created Web Application
contextConfigLocation
classpath:spring-root.xml; classpath:activemq.xml;
org.springframework.web.context.ContextLoaderListener
springMVC
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:spring-mvc-dispatch.xml
1
springMVC
/
characterEncodingFilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
UTF-8
forceEncoding
true
characterEncodingFilter
/*

其中spring-root.xml 很简单,负责加载一些spring的配置

spring-mvc-dispatch.xml如下

 

activemq.xml是关键的配置,如下

gzframe.demo

二、代码部分

消息生产者ProducerService.java,代码如下

package com.gzframe.demo.activemq.producer;import javax.annotation.Resource;import javax.jms.Destination;import javax.jms.JMSException;import javax.jms.Message;import javax.jms.Session;import org.springframework.jms.core.JmsTemplate;import org.springframework.jms.core.MessageCreator;import org.springframework.stereotype.Service;@Servicepublic class ProducerService {    @Resource(name="jmsTemplate")    private JmsTemplate jmsTemplate;             /**       * 向指定队列发送消息       */      public void sendMessage(Destination destination, final String msg) {        System.out.println("向队列" + destination.toString() + "发送了消息------------" + msg);        jmsTemplate.send(destination, new MessageCreator() {          public Message createMessage(Session session) throws JMSException {            return session.createTextMessage(msg);          }        });      }         /**     * 向默认队列发送消息     */      public void sendMessage(final String msg) {        String destination =  jmsTemplate.getDefaultDestination().toString();        System.out.println("向队列" +destination+ "发送了消息------------" + msg);        jmsTemplate.send(new MessageCreator() {          public Message createMessage(Session session) throws JMSException {            return session.createTextMessage(msg);          }        });           }    }

 

消费者ConsumerService.java,代码如下

package com.gzframe.demo.activemq.consumer;import javax.annotation.Resource;import javax.jms.Destination;import javax.jms.JMSException;import javax.jms.TextMessage;import org.springframework.jms.core.JmsTemplate;import org.springframework.stereotype.Service;@Servicepublic class ConsumerService {    @Resource(name="jmsTemplate")    private JmsTemplate jmsTemplate;         /**     * 接收消息     */    public TextMessage receive(Destination destination) {        TextMessage tm = (TextMessage) jmsTemplate.receive(destination);        try {            System.out.println("从队列" + destination.toString() + "收到了消息:\t"                    + tm.getText());        } catch (JMSException e) {            e.printStackTrace();        }                return tm;            } }

 

三、页面部分

1.首先写一个欢迎页,welcome.jsp如下,

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%>
Welcome

Welcome!!!

去发消息

从队列中取一个消息

 

2.然后是生产者页面jms_producer.jsp,如下

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%>
JMS-Producer

JMS-Producer!!!

MessageText:

返回主页

 

3.接收者页面queue_receive.jsp,如下

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%>
Receive

${textMessage }

返回主页

四、Controller控制器

1.首先controller到首页welcome页,WelcomeController.java如下:

package com.gzframe.demo.mvc.controller;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.servlet.ModelAndView;@Controllerpublic class WelcomeController {        @RequestMapping(value="/welcome",method=RequestMethod.GET)    public ModelAndView welcome(){        System.out.println("------------welcome");                ModelAndView mv = new ModelAndView();        mv.setViewName("welcome");        return mv;    }}

2.然后定义消息生产和消费的控制器,DemoController.java,代码如下

package com.gzframe.demo.mvc.controller;import java.io.IOException;import java.text.SimpleDateFormat;import java.util.*;import javax.annotation.Resource;import javax.jms.Destination;import javax.jms.JMSException;import javax.jms.TextMessage;import javax.management.MBeanServerConnection;import javax.management.remote.JMXConnector;import javax.management.remote.JMXConnectorFactory;import javax.management.remote.JMXServiceURL;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.servlet.ModelAndView;import com.gzframe.demo.activemq.consumer.ConsumerService;import com.gzframe.demo.activemq.producer.ProducerService;@Controllerpublic class DemoController {    //队列名gzframe.demo    @Resource(name="demoQueueDestination")    private Destination demoQueueDestination;    //队列消息生产者    @Resource(name="producerService")    private ProducerService producer;      //队列消息消费者    @Resource(name="consumerService")    private ConsumerService consumer;        @RequestMapping(value="/producer",method=RequestMethod.GET)    public ModelAndView producer(){        System.out.println("------------go producer");                Date now = new Date();         SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");        String time = dateFormat.format( now );         System.out.println(time);                ModelAndView mv = new ModelAndView();        mv.addObject("time", time);        mv.setViewName("jms_producer");                return mv;    }        @RequestMapping(value="/onsend",method=RequestMethod.POST)    public ModelAndView producer(@RequestParam("message") String message) {        System.out.println("------------send to jms");        ModelAndView mv = new ModelAndView();        producer.sendMessage(demoQueueDestination, message);        mv.setViewName("welcome");        return mv;    }        @RequestMapping(value="/receive",method=RequestMethod.GET)    public ModelAndView queue_receive() throws JMSException {        System.out.println("------------receive message");        ModelAndView mv = new ModelAndView();                TextMessage tm = consumer.receive(demoQueueDestination);        mv.addObject("textMessage", tm.getText());                mv.setViewName("queue_receive");        return mv;    }        /*     * ActiveMQ Manager Test     */    @RequestMapping(value="/jms",method=RequestMethod.GET)    public ModelAndView jmsManager() throws IOException {        System.out.println("------------jms manager");        ModelAndView mv = new ModelAndView();        mv.setViewName("welcome");                JMXServiceURL url = new JMXServiceURL("");        JMXConnector connector = JMXConnectorFactory.connect(url);        connector.connect();        MBeanServerConnection connection = connector.getMBeanServerConnection();                return mv;    }            }

五、效果展示

首先访问欢迎页,如下

 

然后点“去发消息”,进入到如下页面,默认消息框一已经填写了时间,点击提交,会将时间“2015-12-25 11:51:25”提交到qctivemq服务器中,

提交完成后,根据页面代码,会转到欢迎页,在欢迎页中既可以点击“从队列中取一个消息”,效果如下

可以看到,取到的消息即为刚才提交的时间,demo成功!

经过以上操作后的后台输出如下

六、加入监听器

以上例子中,接收消息是靠手动点击接收,下面将配置一个消息监听器“QueueMessageListener.java”,负责自动监听qctiveMQ中的队列消息,

一旦有新消息后,将自动读取消费,妈妈再也不用担心漏掉消息啦!

1.首先写一个监听的类“QueueMessageListener.java”,必须实现“MessageListerner”接口,代码如下

package com.gzframe.demo.activemq.listener;import javax.jms.JMSException;import javax.jms.Message;import javax.jms.MessageListener;import javax.jms.TextMessage;public class QueueMessageListener implements MessageListener {        //当收到消息后,自动调用该方法    @Override    public void onMessage(Message message) {                TextMessage tm = (TextMessage) message;        try {            System.out.println("QueueMessageListener监听到了文本消息:\t"                    + tm.getText());            //do something ...        } catch (JMSException e) {            e.printStackTrace();        }    }}

2.写完监听类后,打开activemq.xml配置文件,需要将这个监听配置到文件中,这样,应用加载后,即会加载此监听。

将以下的配置段加入到activemq.xml中

3.测试

配置完成后,重新启动服务,去消息发送页提交消息,提交完毕后,监听检测到,将立即消费掉,并在后台打印出来

后台输出如下

转载于:https://www.cnblogs.com/ruiati/p/7111199.html

你可能感兴趣的文章
js如何操作或是更改sass里的变量
查看>>
BZOJ1419: Red is good
查看>>
POJ 3308 Paratroopers (对数转换+最小点权覆盖)
查看>>
rendering omni shadow in one pass.
查看>>
No repository found containing,eclipse 自动更新erro 解决
查看>>
iOS设计模式之单例模式
查看>>
MySQL面试题中:主从同步的原理
查看>>
HTTP和WebSocket协议(二)
查看>>
项目练习(二)—微博数据结构化
查看>>
尤金·卡巴斯基:卡巴斯基实验室调查内网遭黑客攻击事件
查看>>
android之Handler Runnable实现倒计时
查看>>
POS Tagging 标签类型查询表(Penn Treebank Project)
查看>>
Cookie/Session机制详解
查看>>
搭建Docker环境---Docker概述
查看>>
UVa 11383 少林决胜(二分图最佳完美匹配)
查看>>
ISP DSP的不同
查看>>
深入Linux grep指令的详解(实用型)
查看>>
嵌入式根文件系统的移植和制作详解
查看>>
javascript Uncaught ReferenceError: 方法名 is not defined
查看>>
Android 学习心得(2)——Android内置数据库SQLite
查看>>