ActiveMQ 与spring整合使用

3 篇文章 0 订阅

Queue

QueueProducer
/**
 * @description  队列消息生产者,发送消息到队列
 */
@Component("aQueueProducer")
public class AQueueProducer {

    @Autowired
    @Qualifier("activeQueueTemplate")
    private JmsTemplate jmsTemplate;//通过@Qualifier修饰符来注入对应的bean

    /**
     * 发送一条消息到指定的队列(目标)
     * @param queueName 队列名称
     * @param message 消息内容
     */
    public void send(String queueName,final String message){
            jmsTemplate.send(queueName, new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                return session.createTextMessage(message);
            }
        });
    }

}
QueueConsumer
/**
 * @description  队列消息监听器
 */
@Component("aQueueConsumer1")
public class AQueueConsumer1 implements MessageListener {

    @Override
    public void onMessage(Message message) {
        try {
            System.out.println("ActiveMQ Queue 1接收到消息:"+((TextMessage)message).getText());
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
}

Topic

TopicProducer
/**
 * @description   Topic生产者发送消息到Topic
 */
@Component("aTopicProducer")
public class ATopicProducer {

    @Autowired
    @Qualifier("activeTopicTemplate")
    private JmsTemplate jmsTemplate;

    /**
     * 发送一条消息到指定的队列(目标)
     * @param queueName 队列名称
     * @param message 消息内容
     */
    public void send(String topicName,final String message){
        jmsTemplate.send(topicName, new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                return session.createTextMessage(message);
            }
        });
    }

}
TopicConsumer
/**
 * @description  Topic消息监听器
 */
@Component("aTopicConsumer1")
public class ATopicConsumer1 implements MessageListener{

    @Override
    public void onMessage(Message message) {
        try {
            System.out.println("ActiveMQ Topic 1接收到消息:"+((TextMessage)message).getText());
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }

}

Controller

/**
 * @description controller测试
 */
@Controller
@RequestMapping("/activeMQ")
public class ActiveMQController {

    @Resource 
    AQueueProducer aQueueProducer;
    @Resource 
    ATopicProducer aTopicProducer;

    /**
     * 发送消息到队列
     * Queue队列:仅有一个订阅者会收到消息,消息一旦被处理就不会存在队列中
     * @param message
     * @return String
     */
    @ResponseBody
    @RequestMapping("queueSender")
    public String queueSender(@RequestParam("message")String message){
        String opt="";
        try {
            aQueueProducer.send("active.queue", message);
            opt = "suc";
        } catch (Exception e) {
            opt = e.getCause().toString();
        }
        return opt;
    }

    /**
     * 发送消息到主题
     * Topic主题 :放入一个消息,所有订阅者都会收到 
     * 这个是主题目的地是一对多的
     * @param message
     * @return String
     */
    @ResponseBody
    @RequestMapping("topicSender")
    public String topicSender(@RequestParam("message")String message){
        String opt = "";
        try {
            aTopicProducer.send("active.topic", message);
            opt = "suc";
        } catch (Exception e) {
            opt = e.getCause().toString();
        }
        return opt;
    }

}

XML配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    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"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans     http://www.springframework.org/schema/beans/spring-beans-4.0.xsd   
        http://www.springframework.org/schema/context   http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/jms       http://www.springframework.org/schema/jms/spring-jms-4.0.xsd
        http://activemq.apache.org/schema/core          http://activemq.apache.org/schema/core/activemq-core-5.8.0.xsd">

    <!-- ActiveMQ 连接工厂 -->
    <!-- 真正可以产生Connection的ConnectionFactory,由对应的 JMS服务厂商提供-->
    <!-- 如果连接网络:tcp://ip:61616;未连接网络:tcp://localhost:61616 以及用户名,密码-->
    <amq:connectionFactory id="amqConnectionFactory"
        brokerURL="tcp://localhost:61616" userName="admin" password="admin"  />

    <!-- Spring Caching连接工厂 -->
    <!-- Spring用于管理真正的ConnectionFactory的ConnectionFactory -->  
    <bean id="connectionFactory" class="org.springframework.jms.connection.CachingConnectionFactory">
        <!-- 目标ConnectionFactory对应真实的可以产生JMS Connection的ConnectionFactory -->  
        <property name="targetConnectionFactory" ref="amqConnectionFactory"></property>
        <!-- 同上,同理 -->
        <!-- <constructor-arg ref="amqConnectionFactory" /> -->
        <!-- Session缓存数量 -->
        <property name="sessionCacheSize" value="100" />
    </bean>

    <!-- Spring JmsTemplate 的消息生产者 start-->
    <!-- 定义JmsTemplate的Queue类型 -->
    <bean id="activeQueueTemplate" class="org.springframework.jms.core.JmsTemplate">
        <!-- 这个connectionFactory对应的是我们定义的Spring提供的那个ConnectionFactory对象 -->  
        <constructor-arg ref="connectionFactory" />
        <!-- 非pub/sub模型(发布/订阅),即队列模式 -->
        <property name="pubSubDomain" value="false" />
    </bean>

    <!-- 定义JmsTemplate的Topic类型 -->
    <bean id="activeTopicTemplate" class="org.springframework.jms.core.JmsTemplate">
         <!-- 这个connectionFactory对应的是我们定义的Spring提供的那个ConnectionFactory对象 -->  
        <constructor-arg ref="connectionFactory" />
        <!-- pub/sub模型(发布/订阅) -->
        <property name="pubSubDomain" value="true" />
    </bean>
    <!--Spring JmsTemplate 的消息生产者 end-->

    <!-- 消息消费者 start-->
    <!-- 定义Queue监听器 -->
    <jms:listener-container destination-type="queue" container-type="default" connection-factory="connectionFactory" acknowledge="auto">
        <jms:listener destination="active.queue" ref="aQueueConsumer1"/>
        <jms:listener destination="active.queue" ref="aQueueConsumer2"/>
    </jms:listener-container>

    <!-- 定义Topic监听器 -->
    <jms:listener-container destination-type="topic" container-type="default" connection-factory="connectionFactory" acknowledge="auto">
        <jms:listener destination="active.topic" ref="aTopicConsumer1"/>
        <jms:listener destination="active.topic" ref="aTopicConsumer2"/>
    </jms:listener-container>
    <!-- 消息消费者 end -->
</beans>  

html 测试页面

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

< !DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
< html>
< head>
< base href="<%=basePath%>">

< title>ActiveMQ Demo程序< /title>

< meta http-equiv="pragma" content="no-cache">
< meta http-equiv="cache-control" content="no-cache">
< meta http-equiv="expires" content="0">
< script src="<%=request.getContextPath()%>/script/jquery-3.1.1.min.js"></script> 
< style type="text/css">
.h1 {
    margin: 0 auto;
}

 #producer{
    width: 48%;
    border: 1px solid blue; 
    height: 80%;
    align:center;
    margin:0 auto;
}

body{
    text-align :center;
} 
div {
    text-align :center;
}
textarea{
    width:80%;
    height:100px;
    border:1px solid gray;
}
button{
    background-color: rgb(62, 156, 66);
    border: none;
    font-weight: bold;
    color: white;
    height:30px;
}
< /style>
< script type="text/javascript">

    function send(controller){
        if($("#message").val()==""){
            $("#message").css("border","1px solid red");
            return;
        }else{
            $("#message").css("border","1px solid gray");
        }
        $.ajax({
            type: 'post',
            url:'<%=basePath%>activeMQ/'+controller,
            dataType:'text', 
            data:{"message":$("#message").val()},
            success:function(data){
                if(data=="suc"){
                    $("#status").html("<font color=green>发送成功</font>");
                    setTimeout(clear,1000);
                }else{
                    $("#status").html("<font color=red>"+data+"</font>");
                    setTimeout(clear,5000);
                }
            },
            error:function(data){
                $("#status").html("<font color=red>ERROR:"+data["status"]+","+data["statusText"]+"</font>");
                setTimeout(clear,5000);
            }

        });
    }

    function clear(){
        $("#status").html("");
    }

</script>
</head>

<body>
    <h1>Hello ActiveMQ</h1>
    <div id="producer">
        <h2>Producer</h2>
        <textarea id="message"></textarea>
        <br>
        <button onclick="send('queueSender')">发送Queue消息</button>
        <button onclick="send('topicSender')">发送Topic消息</button>
        <br>
        <span id="status"></span>
    </div>
</body>
</html>

测试结果

这里写图片描述
这里写图片描述

源码下载

源码地址 : http://download.csdn.net/detail/hq0556/9820148

本示例包括ActiveMQ、RabbitMQ、AliyunMQ。不需要可删除包。
这里写图片描述

注:如果仅测试ActiveMQ。需将web.xml 中 “classpath:rabbitMQ.xml”删除,并需修改Spring配置为

<context:component-scan base-package="com.heqing.jms.activeMQ" />
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值