activeMQ-09整合spring

  • spring整合activeMQ,主要是将连接信息配置到spring配置文件中,通过jsmTemplet来进行生产者发布消息。对于消费者,只需要实现MessageListener接口,在配置文件中配置监听即可,接下来看下具体实现代码:
    1)首先看下pom文件,导入需要的依赖
        
            org.springframework
            spring-jms
            4.1.8.RELEASE
        
        
            org.springframework
            spring-context-support
            5.1.5.RELEASE
        
        
        
            org.apache.activemq
            activemq-core
            5.7.0
        
        
            org.apache.activemq
            activemq-pool
            5.12.1
        

2)配置文件application.xml



    
    
    
         
    
    
    
        
    

    
    
        
        
    
    
    
        
        
    
    
    
        
        
        
        
    
    
    
        
        
        
        
    
    
    

3)看下生产者代码

package com.jjclub.spring_activemq;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Component;

@Component
public class springProducer {
    @Autowired
    private JmsTemplate jmsTemplate;
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
        springProducer springProducer = (com.jjclub.spring_activemq.springProducer) context.getBean("springProducer");
        springProducer.jmsTemplate.send(new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                TextMessage textMessage = session.createTextMessage("测试信息");
                return textMessage;
            }
        });
        System.out.println("已发送");
    }
}

4)消费监听者

package com.jjclub.spring_activemq;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
public class SpringConsumer implements MessageListener {
    public void onMessage(Message message) {
        if (message != null && message instanceof TextMessage){
            TextMessage textMessage = (TextMessage) message;
            try {
                System.out.println("监听器接受内容是:" + textMessage.getText());
            } catch (JMSException e) {
                e.printStackTrace();
            }
        }
    }
}

你可能感兴趣的:(activeMQ-09整合spring)