ActiveMQ(二)-Spring集成JMS

一、Spring JMS概论

    Spring提供了ConnectionFactory、JmsTemplate、MessageListener。

1. ConnectionFactory

    Spring提供的连接池,用于管理连接的连接工厂。因为JmsTemplate每次发消息都会重新创建连接,会话和Productor。

    实现类:SingleConnectionFactory、CachingConnectionFactory。

SingleConnectionFactory对于建立JMS服务器连接的请求只会返回同一个Connection。

CachingConnectionFactory继承了SingleConnectionFactory,具有了SingleConnectionFactory的所有功能,同时还新增了缓存功能(会话,Producer,Consumer)。

2. JmsTemplate

    Spring提供的发送接收消息的模板类。只需要向Spring容器中注册该类就可以使用JmsTemplate方便的操作JMS。

    线程安全,可以在整个应用范围使用,但不代表只能创建一个。

3. MessageListener

    消息监听器,只需要实现onMessage方法接受Message参数即可处理消息

二、实战

1. 新建一个Maven项目,导入依赖的jar包。

    ActiveMQ(二)-Spring集成JMS

2. common.xml

    因为无论是生产者还是消费者都需要使用ConnectionFactory和目的地,所以抽出来形成一个common.xml。

    ActiveMQ(二)-Spring集成JMS

3. 生产者

    编写接口类,定义通用方法

    ActiveMQ(二)-Spring集成JMS

    继承生产者接口,实现接口方法

    ActiveMQ(二)-Spring集成JMS

    定义producer.xml,使用Spring jms提供的JmsTemplate

    ActiveMQ(二)-Spring集成JMS

4. 生产者测试类

    ActiveMQ(二)-Spring集成JMS

5. 运行生产者测试类

    ActiveMQ(二)-Spring集成JMS

    ActiveMQ(二)-Spring集成JMS

6. 消息监听器

    ActiveMQ(二)-Spring集成JMS

    定义consumer.xml,配置消息监听器及消息监听器容器

    ActiveMQ(二)-Spring集成JMS

7. 消费者测试类

    ActiveMQ(二)-Spring集成JMS

8. 运行消费者测试类

    ActiveMQ(二)-Spring集成JMS

    以上是使用队列模式完成的生产者消费者,使用主题模式和队列模式相同,只需要在common.xml中定义一个TopicDestination,然后在生产者的Destination定义时使用@Resource(name=”topicDestination”),而消费者的消息监听容器的destination属性中引入topicDestination即可。