近日总有些人来问我一些关于MQ的问题,我整理总结了一些,来跟大家分享一下,如有错误还希望各位大牛指正。探讨的同胞们可以加QQ群:315309006
MQ的概念中大致有这么三类对象,分别是broker、producer、consumer,这三类对象的用途分别是:
1.broker:开启MQ服务,简单点理解相当于启动了一个服务中转站;
2.producer:message产生;
3.consumer:message消费。
消息发送的过程简单点来说,由客户端的producer产生一个消息,发送到broker上,consumer会到broker上把这条消息拿走。这里说的当然是最简单的一种理解,在实际应用中这个过程是很复杂的,一般来说在实际应用中,提供服务的客户端应该同时包括producer和consumer,既可以发送、也可以接收。
消息发送根据应用场景不同,分为“直接发送”、“发送立即反馈”、“发送异步反馈”:
1.直接发送:“Topic发布订阅”或者“向broker的Destination发送单向消息”,可以用来做广播、或者在服务端启动consumer消费(处理)提交上来的消息、或者可以做站内消息
2.发送立即反馈:客户端发送消息后、服务端接收到消息立即处理,并返回处理结果给客户端,服务端处理过程中客户端和服务端保持连接状态、直到返回消息为止
3.发送异步反馈:客户端定义异步接受监听方法、接着发送消息、操作结束,服务器接收到消息后处理消息内容,并根据消息来源重新组装一个反馈消息、发送回提交客户端,期间是异步的
MQ技术其实不是一个新鲜的东西,只不过近些年来对它的用途越来越多的被人们发掘出来,现在炒的很热的云平台、云计算很多都有着MQ技术的身影。
下面几个是我做MQ的简单实现,包括了上述的几种情况的处理,供大家参考:
| 01 | @Service // 异步发送调用:new AsynRequestClient().request(); |
| 02 | public class AsynRequestClient extends AsynRequestClientFactory/*封装了request方法*/ { |
| 04 | public void doMessage(Message message) { |
| 05 | TextMessage m = (TextMessage) message; |
| 09 | } catch (JMSException e) { |
| 12 | log.info("client: Asyn get server message - " + text); |
| 16 | public void setProperties(String ip, String messageBody, int destinationType) { |
| 18 | this.messageBody = messageBody; |
| 19 | this.destinationType = destinationType; |
| 1 | @Service // 直接发送:new SendClient().sendMessage(); |
| 2 | public class SendClient extends SendClientFactory/*封装了sendMessage方法*/ { |
| 3 | public void setProperties(String ip, String messageBody, int destinationType) { |
| 5 | this.messageBody = messageBody; |
| 6 | this.destinationType = destinationType; |
| 01 | @Service // 同步发送:new SynRequestClient().request(); |
| 02 | public class SynRequestClient extends SynRequestClientFactory/*封装了request方法*/ { |
| 05 | * this.ip=ip 设置通讯目的地ip地址 |
| 07 | * this.messageBody=messageBody 通讯内容 |
| 08 | * @param destinationType |
| 09 | * this.destinationType=destinationType 目标队列类型 |
| 12 | public void setProperties(String ip, String messageBody, int destinationType) { |
| 14 | this.messageBody = messageBody; |
| 15 | this.destinationType = destinationType; |
| 02 | public class ServerResponse extends ServerResponseFactory { |
| 05 | public void onMessageBusiness(Message msg) { |
| 06 | TextMessage m = (TextMessage) msg; |
| 10 | } catch (JMSException e) { |
| 13 | log.info("server: receive message is " + text); |
| 16 | @Override // 异步提交内容的处理、返回处理结果 |
| 17 | public String onAsynResponseBusiness(Message msg) { |
| 18 | TextMessage m = (TextMessage) msg; |
| 22 | } catch (JMSException e) { |
| 25 | return "server: return AsynResponse is " + text; |
| 28 | @Override // 同步提交内容的处理、并返回处理结果 |
| 29 | public String onSynResponseBusiness(Message msg) { |
| 30 | TextMessage m = (TextMessage) msg; |
| 34 | } catch (JMSException e) { |
| 37 | return "server: return SynResponse is " + text; |
顺便提一下,我整理了些基础的Spring和ActiveMQ整合的例子,如果想探讨的同胞们可以加QQ群:315309006 向我索取。顺便鄙视一下那些不肯和别人分享的大牛们