一.ActiveMQ整合Spring基础
ActiveMQ和Spring的整合,其实是把activemq的一些对象交给spring来管理,比如连接工厂,queue,top等等
二.依赖
除了activemq本身提供的jar包外,还需要两个spring整合activemq的jar:
org.springframework spring-jmsorg.springframework spring-context-supportorg.apache.activemq activemq-all
三.在spring配置文件中,配置activemq相关的对象
》生产者需要配置的对象:activemq原生连接工厂,spring包装过的工厂,JmsTemplate(生产者),queue,topic
测试代码:
//测试生产者发生queue
@Test
public void testJMSTemplateByQueue() throws Exception {
//创建spring容器
ApplicationContext ioc = new ClassPathXmlApplicationContext("classpath:spring/applicationContext-activemq.xml");
//获取jmstemplate
JmsTemplate jmsTemplate = ioc.getBean(JmsTemplate.class);
//获取目的对象
Destination queue = (Destination) ioc.getBean("queueDestination");
//发送消息,并设置目的对象和消息
jmsTemplate.send(queue,new MessageCreator() {
public Message createMessage(Session session) throws JMSException {
TextMessage message = session.createTextMessage();
message.setText("hello spring activemq");
return message;
}
});
小结:生产者是需要在特定的时间发送指定的消息内容,因此是需要书写代码的
》消费者需要配置的对象:activemq原生连接工厂,spring包装过的工厂,监听容器(消费者),监听器,queue,topic
》之前监听器我们是直接实现匿名内部类的方式,但是在spring这就不能了,还是书写一个实现类并继承messageListener接口
测试代码:
@Test
public void testListener() throws IOException {
ApplicationContext ioc = new ClassPathXmlApplicationContext("classpath:spring/applicationContext-activemq.xml");
System.in.read();
}
小结:我们的测试代码很简单,只要把容器启动了,监听器就会一致监听着。不需要写任何代码,监听器只要一直关注目的对象Destination是否有消息发送过来
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。



