Spring集成ActiveMQ消息队列使用

导入maven坐标

        <dependency>
            <groupId>org.apache.activemqgroupId>
            <artifactId>activemq-allartifactId>
            <version>${activemq.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-jmsartifactId>
            <version>${spring.version}version>
        dependency>

applicationContext.xml配置


    <context:component-scan base-package="com.kayo.bos.mq" />

    
    
    
    <amq:connectionFactory id="amqConnectionFactory"
        brokerURL="tcp://localhost:61616" userName="admin" password="admin"  />

    
      
    <bean id="connectionFactory" class="org.springframework.jms.connection.CachingConnectionFactory">
          
        <property name="targetConnectionFactory" ref="amqConnectionFactory">property>
        
        
        
        <property name="sessionCacheSize" value="100" />
    bean>

     

    
    <jms:listener-container destination-type="queue" container-type="default" 
        connection-factory="connectionFactory" acknowledge="auto">
        
        <jms:listener destination="bos_sms" ref="smsConsumer"/>
    jms:listener-container>

    






    

方法调用
生产者:
依赖注入:

    @Autowired
    @Qualifier("jmsQueueTemplate")
    private JmsTemplate jmsTemplate;
        // 调用MQ服务,发送一条消息
        jmsTemplate.send("bos_sms", new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                MapMessage mapMessage = session.createMapMessage();
                mapMessage.setString(key1, value1);
                mapMessage.setString(key2, value2);
                return mapMessage;
            }
        });

消费者:

package com.kayo.bos.mq;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageListener;

import org.springframework.stereotype.Service;

@Service("smsConsumer")
public class SmsConsumer implements MessageListener {

    @Override
    public void onMessage(Message message) {
        MapMessage mapMessage = (MapMessage) message;
        try {
            String value1= mapMessage.getString("key1");
            String value2= mapMessage.getString("key2");

        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
}


}

你可能感兴趣的:(ssh框架搭建,activemq-spring)