美文网首页编程it互联网
spring整合activemq消息队列之点对点模式

spring整合activemq消息队列之点对点模式

作者: 荒唐的程序猿 | 来源:发表于2017-01-06 16:03 被阅读162次

关于jms概念以及activemq这里不做具体赘述,activemq是apache的一款项目,介绍里号称是最方便最强大的jms实现方式。其实jms与webservice功能是一样的,侧重点不同而已。都是提供多系统之间的交互通信方式,前者相对于后者更加轻量级,可以实现延迟通信,避免系统高峰期交互通信,也不需要暴露接口等,开发起来更加方便,但是如果项目要求即时性很高那么就选择后者,当然他们两者也可以整合起来一起使用,本文重点介绍的是spring框架整合activemq实现点对点模式,关于activemq具体概念百度。
1:下载activemq中间件,地址:http://activemq.apache.org/
下载好压缩到本地,可以看到这个目录

这里写图片描述
从它的目录来说,还是很简单的:
bin存放的是脚本文件
conf存放的是基本配置文件
data存放的是日志文件
docs存放的是说明文档
examples存放的是简单的实例
lib存放的是activemq所需jar包
webapps用于存放项目的目录

其中conf里面有个activemq.xml里面有个配置<broker xmlns="http://activemq.apache.org/schema/core" brokerName="localhost" dataDirectory="${activemq.data}">默认是localhost,这个是可以修改,比如可以换成本机ip地址或是局域网另一台电脑ip,这样把中间件部署到同事电脑你也可以访问,同理部署到linux服务器上只需要把localhost换成服务器ip地址,关于这一段的修改用意在代码里面会提及。修改完后进入bin文件夹选择32或64位文件夹后点击activemq.bat批处理命令后中间件启动了起来。该项目还提供了一个管理页面,访问地址是http://(localhost或是你前面修改的同事ip或服务器ip地址):8161/admin 默认的用户名密码都是admin,见下图。我们主要点击Queues栏,里面会显示你的发送消息和接收消息的具体信息,也可以做删除等操作。


这里写图片描述

2:进行项目的搭建

pom.xml配置
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<springframework>4.1.8.RELEASE</springframework>
</properties>

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>

<dependency>  
  <groupId>javax.servlet</groupId>  
  <artifactId>jstl</artifactId>  
  <version>1.2</version>  
</dependency>  
  
<dependency>       
    <groupId>javax.servlet</groupId>  
    <artifactId>javax.servlet-api</artifactId>  
    <version>3.1.0</version>  
</dependency>  
  
<dependency>  
    <groupId>javax.servlet.jsp</groupId>  
    <artifactId>javax.servlet.jsp-api</artifactId>  
    <version>2.3.1</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-web</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>  
  
<!--实现日志  -->  
<dependency>  
    <groupId>org.slf4j</groupId>  
    <artifactId>slf4j-log4j12</artifactId>  
    <version>1.7.22</version>  
</dependency>  
  
<!--处理json  -->  
<dependency>  
        <groupId>com.alibaba</groupId>  
        <artifactId>fastjson</artifactId>  
        <version>1.2.0</version>  
</dependency>  

</dependencies>

applicationContext.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.qqw">  
    <!-- 只扫描Service,也可以添加Repostory,但是要把Controller排除在外,Controller由spring-mvc.xml去加载 -->  
    <!-- <context:include-filter type="annotation" expression="org.springframework.stereotype.Service" /> -->  
    <!-- <context:include-filter type="annotation" expression="org.springframework.stereotype.Repository" /> -->  
    <!-- <context:include-filter type="annotation" expression="org.springframework.stereotype.Component" /> -->  
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>  
 </context:component-scan>  
<!-- <mvc:annotation-driven /> -->  

</beans>

spring-mvc.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">

<!-- 启用MVC注解 -->  
<mvc:annotation-driven />  
  
<!-- 静态资源文件,不会被Spring MVC拦截 -->  
<mvc:resources location="/resources/" mapping="/resources/**"/>  
  
<!-- 指定Sping组件扫描的基本包路径 -->  
<context:component-scan base-package="com.qqw" >  
    <!-- 这里只扫描Controller,不可重复加载Service -->  
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>  
</context:component-scan>  
  
<!-- JSP视图解析器-->   
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>  
    <!-- <property name="prefix" value="/WEB-INF/jsp/"/> -->  
    <property name="prefix" value="/"/>  
    <property name="suffix" value=".jsp"/>  
  
<!--  定义其解析视图的order顺序为1 -->  
    <property name="order" value="1" />  
</bean>  

</beans>

接下来就是重要的spring-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"
>

//这里的是用默认的localhost,如果做了修改或是项目上线,这个要换成网络ip地址,具体见上面的配置提到
<amq:connectionFactory id="amqConnectionFactory"
brokerURL="tcp://localhost: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>  
  
<!--加入监听器  -->  
 <bean id="queueMessageListener" class="com.qqw.active.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>  

</beans>

3:逻辑代码

 (1)消息发送者

package com.qqw.active;

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);  
      }  
    });  
   
  }  

}

(2)消息接受者

package com.qqw.active;

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;

import com.alibaba.fastjson.JSON;

@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());  
        /*Gson gson = new Gson();*/  
        Person fromJson = JSON.parseObject(tm.getText(), Person.class);  
        System.out.println(fromJson.toString());  
    } catch (JMSException e) {  
        e.printStackTrace();  
    }  
      
    return tm;  
      
}  

}

(3)传递的实体类
package com.qqw.active;

public class Person {

private String name;  
private String sex;  
private int age;  
public Person() {  
    super();  
    // TODO Auto-generated constructor stub  
}  
public String getName() {  
    return name;  
}  
public void setName(String name) {  
    this.name = name;  
}  
public String getSex() {  
    return sex;  
}  
public void setSex(String sex) {  
    this.sex = sex;  
}  
public int getAge() {  
    return age;  
}  
public void setAge(int age) {  
    this.age = age;  
}  
@Override  
public String toString() {  
    return "Person [name=" + name + ", sex=" + sex + ", age=" + age + "]";  
}  

}

(4)为接受者定义监听器,这样消息一发到中间件会自动接收处理,如果不需要自动,这段不用写,并且把activemq.xml后两个bean注释掉

package com.qqw.active;

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());            

        Person fromJson = JSON.parseObject(tm.getText(), Person.class);  
        System.out.println(fromJson.toString());  

       //do something ...  
    } catch (JMSException e){ e.printStackTrace();   
    }   
    }  
}  

}

(5)具体业务逻辑

//发送queue消息
@RequestMapping(value="/onsend",method=RequestMethod.POST)
public ModelAndView producer(@RequestParam("message") String message) {
System.out.println("------------send to jms");
com.alibaba.fastjson.JSONObject jsonObj = new com.alibaba.fastjson.JSONObject();
jsonObj.put("name", "张三");
jsonObj.put("sex", "男");
jsonObj.put("age", 20);
String resultjson=JSON.toJSONString(jsonObj);
ModelAndView mv = null;
producer.sendMessage(demoQueueDestination, resultjson);
mv=new ModelAndView("index");
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;  
}  

(6)本地运行截图

以上就介绍完了,参考了网上资料以及自己的一些实践,大家互相交流学习!!!

相关文章

网友评论

    本文标题:spring整合activemq消息队列之点对点模式

    本文链接:https://www.haomeiwen.com/subject/vhqxbttx.html