1、配置部分html
2、代碼部分java
3、頁面部分web
4、Controller控制器spring
5、效果展現apache
6、加入監聽器api
7、最最重要的,別忘了打賞spring-mvc
ActiveMQ的安裝這就不說了,很簡單,服務器
這個例子採用maven構建,首先看一下pom.xml微信
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.gzframe.demo</groupId> <artifactId>gzframe</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>gzframe Maven Webapp</name> <url>http://maven.apache.org</url> <!-- 版本管理 --> <properties> <springframework>4.1.8.RELEASE</springframework> <javax.servlet>3.1.0</javax.servlet> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.10</version> <scope>test</scope> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>${javax.servlet}</version> </dependency> <!-- spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${springframework}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${springframework}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${springframework}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${springframework}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jms</artifactId> <version>${springframework}</version> </dependency> <!-- xbean 如<amq:connectionFactory /> --> <dependency> <groupId>org.apache.xbean</groupId> <artifactId>xbean-spring</artifactId> <version>3.16</version> </dependency> <!-- activemq --> <dependency> <groupId>org.apache.activemq</groupId> <artifactId>activemq-core</artifactId> <version>5.7.0</version> </dependency> <dependency> <groupId>org.apache.activemq</groupId> <artifactId>activemq-pool</artifactId> <version>5.12.1</version> </dependency> </dependencies> <build> <finalName>gzframe</finalName> </build> </project>
接下來看一下web.xml,以下session
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <display-name>Archetype Created Web Application</display-name> <!-- 加載spring的配置文件,例如hibernate、jms等集成 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:spring-root.xml; classpath:activemq.xml; </param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <servlet> <servlet-name>springMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc-dispatch.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springMVC</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 處理編碼格式 --> <filter> <filter-name>characterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
其中spring-root.xml 很簡單,負責加載一些spring的配置
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd"> <context:component-scan base-package="com.gzframe.demo.entity" /> <mvc:annotation-driven /> </beans>
spring-mvc-dispatch.xml以下
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd"> <context:component-scan base-package="com.gzframe.demo.mvc.controller" /> <mvc:annotation-driven /> <bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="/WEB-INF/views/" /> <property name="suffix" value=".jsp" /> </bean> </beans>
activemq.xml是關鍵的配置,以下
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:amq="http://activemq.apache.org/schema/core" xmlns:jms="http://www.springframework.org/schema/jms" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-4.1.xsd http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core-5.12.1.xsd" > <context:component-scan base-package="com.gzframe.demo.activemq" /> <mvc:annotation-driven /> <amq:connectionFactory id="amqConnectionFactory" brokerURL="tcp://192.168.150.61:61616" userName="admin" password="admin" /> <!-- 配置JMS鏈接工長 --> <bean id="connectionFactory" class="org.springframework.jms.connection.CachingConnectionFactory"> <constructor-arg ref="amqConnectionFactory" /> <property name="sessionCacheSize" value="100" /> </bean> <!-- 定義消息隊列(Queue) --> <bean id="demoQueueDestination" class="org.apache.activemq.command.ActiveMQQueue"> <!-- 設置消息隊列的名字 --> <constructor-arg> <value>gzframe.demo</value> </constructor-arg> </bean> <!-- 配置JMS模板(Queue),Spring提供的JMS工具類,它發送、接收消息。 --> <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate"> <property name="connectionFactory" ref="connectionFactory" /> <property name="defaultDestination" ref="demoQueueDestination" /> <property name="receiveTimeout" value="10000" /> <!-- true是topic,false是queue,默認是false,此處顯示寫出false --> <property name="pubSubDomain" value="false" /> </bean>
</beans>
消息生產者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; @Service public 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; @Service public 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"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Welcome</title> </head> <body> <h1>Welcome!!!</h1> <h2><a href="producer">去發消息</a></h2> <h2><a href="receive">從隊列中取一個消息</a></h2> </body> </html>
2.而後是生產者頁面jms_producer.jsp,以下
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JMS-Producer</title> </head> <body> <h1>JMS-Producer!!!</h1> <form action="onsend" method="post"> MessageText:<textarea name="message">${time }</textarea> <input type="submit" value="提交" /> </form> <h2><a href="welcome">返回主頁</a></h2> </body> </html>
3.接收者頁面queue_receive.jsp,以下
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Receive</title> </head> <body> <h1>${textMessage }</h1> <h2><a href="welcome">返回主頁</a></h2> </body> </html>
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; @Controller public 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; @Controller public 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中
<!-- 配置消息隊列監聽者(Queue) --> <bean id="queueMessageListener" class="com.gzframe.demo.activemq.listener.QueueMessageListener" /> <!-- 顯示注入消息監聽容器(Queue),配置鏈接工廠,監聽的目標是demoQueueDestination,監聽器是上面定義的監聽器 --> <bean id="queueListenerContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer"> <property name="connectionFactory" ref="connectionFactory" /> <property name="destination" ref="demoQueueDestination" /> <property name="messageListener" ref="queueMessageListener" /> </bean>
3.測試
配置完成後,從新啓動服務,去消息發送頁提交消息,提交完畢後,監聽檢測到,將當即消費掉,並在後臺打印出來
後臺輸出以下
友情贊助
若是您喜歡此文,感受對您工做有幫助,預期領導會給您漲工資,不妨小額贊助一下,讓我有動力繼續努力。
贊助方式1:打開支付寶App,使用「掃一掃」付款,付款碼見下圖,別忘了付款留言哦!
贊助方式2: 若是您有微信錢包,請打開微信,使用「掃一掃」付款,付款碼見下圖