`

spring 消息

 
阅读更多

一、 JMS提供了应用之间的异步通信机制 : 当一个应用通过jms向另一个应用发送消息时,两个应用之间没有直接的联系。而是,发送方应用会将消息交给一个服务,由服务确保将消息投递给接收方应用。

 

1 : JMS 中有两个主要概念 : 消息代理和目的地 , 当一个应用发送消息时,会将消息交给一个消息代理。消息代理可以确保消息被投递目的地,同时释放发送者,使其能够继续其他业务。jms 有两种目的地 队列和主题。

 

2: 点对点消息模式 : 每一个消息都有一个发送者和一个接受者。当消息代理得到消息时,它将消息放入一个队列中。当接受者请求队列中的下一条消息,消息会从队列中取出,投递给接受者。消息投递后会从队列中删除。

 

3:发布-订阅消息模式:消息会发送给一个主题。与队列类似,多个接受者都可以都可以监听一个主题。与队列不同的是,消息不再是只投递给一个接受者,所有主题的订阅者都会接受到此消息。

 

二、Spring 中搭建消息代理 : ActiveMQ 是一个伟大的开源消息代理

1、创建连接工厂 : 

<bean id = "connectionFactory" class = "org.apache.activemq.spring.ActiveMQConnectionFactory">

<property name = "brokerURL" value = "tcp : //localhost : 61616"/>

</bean>

也可以使用:activemq 自己的Spring 配置命名空间来声明连接工厂

xmln : amq = “http://activemq.apache.org/schema/code”

<amq : connectionFactory id = "connectionFactory" brokerURL = "tcp : //localhost : 61616">

 

2、声明activemq消息目的地

1: 队列

<bean id = "queue" class = "org.apache.activemq.command.ActiveMQQueue">

<constructor - arg  value = "spitter.queue">

</bean> 

 

<amq : queue = "queue" physicalName = "spitter.queue">

 

2: 主题

<bean id = "topic" class = "org.apache.activemq.command.ActiveMQTopic">

<constructor - arg  value = "spitter.topic"> value 是名称

</bean> 

 <amq : queue = "topic" physicalName = "spitter.topic">

 

三、使用spring的jms模版  : spring 给出的解决方案是jmstemplate 。 jmsTemplate 可以创建连接,获取会话,以及发送和接受消息。

 

1:  装配jms模板 : 可以创建连接、获得会话以及发送和接受消息。

为了使用jmstemplate , 我们需要在spring的配置文件中将它声明为一个bean

<bean id = "jmsTemplate" class = "org.springframework.jms.core.JmsTemplate">

      <property name= "connectionFactory"  ref = "connectionFactory"/>

      <property name= "defaultDestinationName" value = "spittle.alert.queue"/>

</bean>

 

2:发送信息

过程 : 

消息发送者 -- >  JmsTemplate -- > 队列/主题

 

jmsTemplate.send(

      new MessageCreator(){

      }

)

 

3: 接受信息 

过程:

队列/主题 -- > JmsTemplate -- > 消息接受者

jmstemplate.receive()

 

四、使用基于消息的RPC : spring 提供了两种基于消息的RPC方案

1 :使用spirng 基于消息的RPC :导出基于jms的服务 , 使用JmsInvokerServiceExporter,可以导出基于jms的服务。

 

发布

<bean id = "" class = " JmsInvokerServiceExporter"  p: service-ref = "实现类" p: serviceInterface = "接口" >

 

<jms : listener- container>  增加jms 相关信息

 

访问

<bean id = "" class = "JmsInvokerProxyFactoryBean" >

 

 

2: 使用Lingo实现异步RPC

<amq : queue id = "alterServiceQueue" physicalName = "spitter.alter.queue">

 

<bean id = "alertServiceExporter" class = "JmsServiceExporter"

p: connectionFactory-ref = "connectionFactory"

p:destincaton-ref = "alertServiceQueue"

p:service-ref = "实现类"

p:serviceInterface = "接口" 

>

 

代理异步服务

<bean id = "alterService" class = " JmsProxyFactoryBean"

p: connectionFactory-ref = "connectionFactory"

p: destination-ref = "queue"

p: serviceInterface = "接口"

>

 <property name = "metadataStrategy">

  <bean id = "metadataStrategy" class = "SimpleMetaStrategy" >

  <constructor-arg value = "true"> 

  </bean>

 </property>

</bean>

 

 

 

 

 

 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics