1. ActiveMQ

1). ActiveMQ

ActiveMQ是Apache所提供的一个开源的消息系统,完全采用Java来实现,因此,它能很好地支持J2EE提出的JMS(Java Message Service,即Java消息服务)规范。JMS是一组Java应用程序接口,它提供消息的创建、发送、读取等一系列服务。JMS提供了一组公共应用程序接口和响应的语法,类似于Java数据库的统一访问接口JDBC,它是一种与厂商无关的API,使得Java程序能够与不同厂商的消息组件很好地进行通信。

2). Java Message Service(JMS)

JMS支持两种消息发送和接收模型。

  • 一种称为P2P(Ponit to Point)模型,即采用点对点的方式发送消息。P2P模型是基于队列的,消息生产者发送消息到队列,消息消费者从队列中接收消息,队列的存在使得消息的异步传输称为可能,P2P模型在点对点的情况下进行消息传递时采用。

     
    图1.png
  • 另一种称为Pub/Sub(Publish/Subscribe,即发布-订阅)模型,发布-订阅模型定义了如何向一个内容节点发布和订阅消息,这个内容节点称为topic(主题)。主题可以认为是消息传递的中介,消息发布这将消息发布到某个主题,而消息订阅者则从主题订阅消息。主题使得消息的订阅者与消息的发布者互相保持独立,不需要进行接触即可保证消息的传递,发布-订阅模型在消息的一对多广播时采用。

     
    图2.png
3). JMS术语
  • Provider/MessageProvider:生产者
  • Consumer/MessageConsumer:消费者
  • PTP:Point To Point,点对点通信消息模型
  • Pub/Sub:Publish/Subscribe,发布订阅消息模型
  • Queue:队列,目标类型之一,和PTP结合
  • Topic:主题,目标类型之一,和Pub/Sub结合
  • ConnectionFactory:连接工厂,JMS用它创建连接
  • Connnection:JMS Client到JMS Provider的连接
  • Destination:消息目的地,由Session创建
  • Session:会话,由Connection创建,实质上就是发送、接受消息的一个线程,因此生产者、消费者都是Session创建的
4). ActiveMQ下载
 
图3.png
  • bin (windows下面的bat(分32、64位)和unix/linux下面的sh)
  • conf (activeMQ配置目录,包含最基本的activeMQ配置文件)
  • data (默认是空的)
  • docs (index,replease版本里面没有文档,-.-b不知道为啥不带)
  • example (几个例子)
  • lib (activemMQ使用到的lib)
  • webapps 注意ActiveMQ自带Jetty提供Web管控台
  • webapps-demo 示例
  • activemq-all-5.15.3.jar
  • LICENSE.txt
  • README.txt
5). 配置
  • Web控制台账号和密码(apache-activemq-5.15.3\conf)

     
    图4.png
  • 网络端口(apache-activemq-5.15.3\conf)--默认为8161
     
    图5.png
6). 启动

\apache-activemq-5.15.3\bin\win64\目录下双击activemq.bat文件,在浏览器中输入http://localhost:8161/admin/, 用户名和密码输入admin即可

 
图6.png
7). 消息中间件(MOM:Message Orient middleware)

消息中间件有很多的用途和优点:

  • 1 将数据从一个应用程序传送到另一个应用程序,或者从软件的一个模块传送到另外一个模块;
    1. 负责建立网络通信的通道,进行数据的可靠传送。
    1. 保证数据不重发,不丢失
    1. 能够实现跨平台操作,能够为不同操作系统上的软件集成技工数据传送服务
8).什么情况下使用ActiveMQ?
  • 多个项目之间集成
    (1) 跨平台
    (2) 多语言
    (3) 多项目
  • 降低系统间模块的耦合度,解耦
    (1) 软件扩展性
  • 系统前后端隔离
    (1) 前后端隔离,屏蔽高安全区

2. ActiveMQ 示例

1). P2P 示例

I. 导包--activemq-all-5.15.3.jar
II. Producer

  1. /**
  2. * 定义消息的生产者
  3. * @author mazaiting
  4. */
  5. public class Producer {
  6. // 用户名
  7. private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;
  8. // 密码
  9. private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;
  10. // 链接
  11. private static final String BROKENURL = ActiveMQConnection.DEFAULT_BROKER_URL;
  12. /**
  13. * 定义消息并发送,等待消息的接收者(消费者)消费此消息
  14. * @param args
  15. * @throws JMSException
  16. */
  17. public static void main(String[] args) throws JMSException {
  18. // 消息中间件的链接工厂
  19. ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
  20. USERNAME, PASSWORD, BROKENURL);
  21. // 连接
  22. Connection connection = null;
  23. // 会话
  24. Session session = null;
  25. // 消息的目的地
  26. Destination destination = null;
  27. // 消息生产者
  28. MessageProducer messageProducer = null;
  29. try {
  30. // 通过连接工厂获取链接
  31. connection = connectionFactory.createConnection();
  32. // 创建会话,进行消息的发送
  33. // 参数一:是否启用事务
  34. // 参数二:设置自动签收
  35. session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
  36. // 创建消息队列
  37. destination = session.createQueue("talkWithMo");
  38. // 创建一个消息生产者
  39. messageProducer = session.createProducer(destination);
  40. // 设置持久化/非持久化, 如果非持久化,MQ重启后可能后导致消息丢失
  41. messageProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
  42. // 模拟发送消息
  43. for (int i = 0; i < 5; i++) {
  44. TextMessage textMessage = session.createTextMessage("给妈妈发送的消息:"+i);
  45. System.out.println("textMessage: " + textMessage);
  46. messageProducer.send(textMessage);
  47. }
  48. // 如果设置了事务,会话就必须提交
  49. session.commit();
  50. } catch (JMSException e) {
  51. e.printStackTrace();
  52. } finally {
  53. if (null != connection) {
  54. connection.close();
  55. }
  56. }
  57. }
  58. }

III. Consumer

  1. /**
  2. * 定义消息的消费者
  3. * @author mazaiting
  4. */
  5. public class Consumer {
  6. // 用户名
  7. private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;
  8. // 密码
  9. private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;
  10. // 链接
  11. private static final String BROKENURL = ActiveMQConnection.DEFAULT_BROKER_URL;
  12. /**
  13. * 接收消息
  14. * @param args
  15. * @throws JMSException
  16. */
  17. public static void main(String[] args) throws JMSException {
  18. // 消息中间件的链接工厂
  19. ConnectionFactory connectionFactory = null;
  20. // 链接
  21. Connection connection = null;
  22. // 会话
  23. Session session = null;
  24. // 消息的目的地
  25. Destination destination = null;
  26. // 消息的消费者
  27. MessageConsumer messageConsumer = null;
  28. // 实例化链接工厂,创建一个链接
  29. connectionFactory = new ActiveMQConnectionFactory(USERNAME, PASSWORD, BROKENURL);
  30. try {
  31. // 通过工厂获取链接
  32. connection = connectionFactory.createConnection();
  33. // 启动链接
  34. connection.start();
  35. // 创建会话,进行消息的接收
  36. session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
  37. // 创建消息队列
  38. destination = session.createQueue("talkWithMo");
  39. // 创建一个消息的消费者
  40. messageConsumer = session.createConsumer(destination);
  41. // 模拟接收消息
  42. while (true) {
  43. TextMessage textMessage = (TextMessage) messageConsumer.receive(10000);
  44. if (null != textMessage) {
  45. System.out.println("收到消息: " + textMessage);
  46. } else {
  47. break;
  48. }
  49. }
  50. // 提交
  51. session.commit();
  52. } catch (JMSException e) {
  53. e.printStackTrace();
  54. } finally {
  55. if (null != connection) {
  56. connection.close();
  57. }
  58. }
  59. }
  60. }

IV. 测试

  • 先运行生产者Producer

     
    图7.png

ActiveMQ控制台

 
图8.png
  • 再运行消费者Consumer

     
    图9.png

    ActiveMQ控制台

     
    图10.png

V. 消息类型

  • StreamMessage Java原始值的数据流
  • MapMessage 一套名称-键值对
  • TextMessage 一个字符串对象
  • ObjectMessage 一个序列号的Java对象
  • BytesMessage 一个未解释字节的数据流
    VI. 控制台 Queue
  • Messages Enqueued:表示生产了多少条消息,记做P
  • Messages Dequeued:表示消费了多少条消息,记做C
  • Number Of Consumers:表示在该队列上还有多少消费者在等待接受消息
  • Number Of Pending Messages:表示还有多少条消息没有被消费,实际上是表示消息的积压程度,就是P-C
    VII. 签收
    签收就是消费者接受到消息后,需要告诉消息服务器,我收到消息了。当消息服务器收到回执后,本条消息将失效。因此签收将对PTP模式产生很大影响。如果消费者收到消息后,并不签收,那么本条消息继续有效,很可能会被其他消费者消费掉!
  • AUTO_ACKNOWLEDGE:表示在消费者receive消息的时候自动的签收
  • CLIENT_ACKNOWLEDGE:表示消费者receive消息后必须手动的调用acknowledge()方法进行签收
  • DUPS_OK_ACKNOWLEDGE:签不签收无所谓了,只要消费者能够容忍重复的消息接受,当然这样会降低Session的开销
2). request/reply模型

I. 实现思路

 
图11.png

Client的Producer发出一个JMS message形式的request,request上附加了一些额外的属性:

  • correlation ID(用来和返回的correlation ID对比进行验证),
  • JMSReplyTo属性(放置jms message的destination,这样worker的Consumer获得jms message就能得到destination)

Worker的consumer收到requset,处理request并用producer发出reply,destination就从requset的JMSReplyTo属性中得到。

II. Server代码

  1. public class Server implements MessageListener {
  2. // 经纪人链接
  3. private static final String BROKER_URL = "tcp://localhost:61616";
  4. // 请求队列
  5. private static final String REQUEST_QUEUE = "requestQueue";
  6. // 经纪人服务
  7. private BrokerService brokerService;
  8. // 会话
  9. private Session session;
  10. // 生产者
  11. private MessageProducer producer;
  12. // 消费者
  13. private MessageConsumer consumer;
  14. private void start() throws Exception {
  15. createBroker();
  16. setUpConsumer();
  17. }
  18. /**
  19. * 创建经纪人
  20. * @throws Exception
  21. */
  22. private void createBroker() throws Exception {
  23. // 创建经纪人服务
  24. brokerService = new BrokerService();
  25. // 设置是否持久化
  26. brokerService.setPersistent(false);
  27. // 设置是否使用JMX
  28. brokerService.setUseJmx(false);
  29. // 添加链接
  30. brokerService.addConnector(BROKER_URL);
  31. // 启动
  32. brokerService.start();
  33. }
  34. /**
  35. * 设置消费者
  36. * @throws JMSException
  37. */
  38. private void setUpConsumer() throws JMSException {
  39. // 创建连接工厂
  40. ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(BROKER_URL);
  41. // 创建连接
  42. Connection connection = connectionFactory.createConnection();
  43. // 启动连接
  44. connection.start();
  45. // 创建Session
  46. session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
  47. // 创建队列
  48. Destination adminQueue = session.createQueue(REQUEST_QUEUE);
  49. // 创建生产者
  50. producer = session.createProducer(null);
  51. // 设置持久化模式
  52. producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
  53. // 创建消费者
  54. consumer = session.createConsumer(adminQueue);
  55. // 消费者设置消息监听
  56. consumer.setMessageListener(this);
  57. }
  58. public void stop() throws Exception {
  59. producer.close();
  60. consumer.close();
  61. session.close();
  62. brokerService.stop();
  63. }
  64. @Override
  65. public void onMessage(Message message) {
  66. try {
  67. // 创建新消息
  68. TextMessage response = this.session.createTextMessage();
  69. // 判断消息是否是文本消息
  70. if (message instanceof TextMessage) {
  71. // 强转为文本消息
  72. TextMessage textMessage = (TextMessage) message;
  73. // 获取消息内容
  74. String text = textMessage.getText();
  75. // 设置消息
  76. response.setText(handleRequest(text));
  77. }
  78. response.setJMSCorrelationID(message.getJMSCorrelationID());
  79. producer.send(message.getJMSReplyTo(), response);
  80. } catch (JMSException e) {
  81. e.printStackTrace();
  82. }
  83. }
  84. /**
  85. * 构建消息内容
  86. * @param text 文本
  87. * @return
  88. */
  89. private String handleRequest(String text) {
  90. return "Response to '" + text + "'";
  91. }
  92. public static void main(String[] args) throws Exception {
  93. Server server = new Server();
  94. // 启动
  95. server.start();
  96. System.out.println();
  97. System.out.println("Press any key to stop the server");
  98. System.out.println();
  99. System.in.read();
  100. server.stop();
  101. }
  102. }

III. Client代码

  1. public class Client implements MessageListener {
  2. // 经纪人链接
  3. private static final String BROKER_URL = "tcp://localhost:61616";
  4. // 请求队列
  5. private static final String REQUEST_QUEUE = "requestQueue";
  6. // 连接
  7. private Connection connection;
  8. // 会话
  9. private Session session;
  10. // 生产者
  11. private MessageProducer producer;
  12. // 消费者
  13. private MessageConsumer consumer;
  14. // 请求队列
  15. private Queue tempDest;
  16. public void start() throws JMSException {
  17. // 连接工厂
  18. ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(BROKER_URL);
  19. // 创建连接
  20. connection = activeMQConnectionFactory.createConnection();
  21. // 开启连接
  22. connection.start();
  23. // 创建会话
  24. session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
  25. // 创建队列
  26. Destination adminQueue = session.createQueue(REQUEST_QUEUE);
  27. // 创建生产者
  28. producer = session.createProducer(adminQueue);
  29. // 设置持久化模式
  30. producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
  31. // 创建模板队列
  32. tempDest = session.createTemporaryQueue();
  33. // 创建消费者
  34. consumer = session.createConsumer(tempDest);
  35. // 设置消息监听
  36. consumer.setMessageListener(this);
  37. }
  38. /**
  39. * 停止
  40. * @throws JMSException
  41. */
  42. public void stop() throws JMSException {
  43. producer.close();
  44. consumer.close();
  45. session.close();
  46. }
  47. /**
  48. * 请求
  49. * @param request
  50. * @throws JMSException
  51. */
  52. public void request(String request) throws JMSException {
  53. System.out.println("Request: " + request);
  54. // 创建文本消息
  55. TextMessage textMessage = session.createTextMessage();
  56. // 设置文本内容
  57. textMessage.setText(request);
  58. // 设置回复
  59. textMessage.setJMSReplyTo(tempDest);
  60. // 获取UUID
  61. String correlationId = UUID.randomUUID().toString();
  62. // 设置JMS id
  63. textMessage.setJMSCorrelationID(correlationId);
  64. // 发送消息
  65. this.producer.send(textMessage);
  66. }
  67. @Override
  68. public void onMessage(Message message) {
  69. try {
  70. System.out.println("Received response for: " + ((TextMessage)message).getText());
  71. } catch (JMSException e) {
  72. e.printStackTrace();
  73. }
  74. }
  75. public static void main(String[] args) throws JMSException, InterruptedException {
  76. Client client = new Client();
  77. // 启动
  78. client.start();
  79. int i = 0;
  80. while(i++ < 10) {
  81. client.request("REQUEST- " + i);
  82. }
  83. Thread.sleep(3000);
  84. client.stop();
  85. }
  86. }

IV. 测试

  • 启动Server

     
    图12.png
  • 启动Client

     
    图13.png

代码下载


如果您觉得我的

作者:_凌浩雨
链接:https://www.jianshu.com/p/8b9bfe865e38
来源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

分布式--ActiveMQ 消息中间件(一) https://www.jianshu.com/p/8b9bfe865e38的更多相关文章

  1. [转]https://www.jianshu.com/p/06443248f4d8

    eos是什么? 原文 https://www.jianshu.com/p/06443248f4d8 简介 用一句话来定义eos,即:区块链操作系统,支持在它之上构建dapp,支持智能合约.帐户.身份验 ...

  2. fastdfs(https://www.jianshu.com/p/1c71ae024e5e)

    参考 官方网站:https://github.com/happyfish100/ 配置文档:https://github.com/happyfish100/fastdfs/wiki/ 参考资料:htt ...

  3. 分布式ActiveMQ集群

    分布式ActiveMQ集群的部署配置细节: 官方资料:http://activemq.apache.org/clustering.html 基本上看这个就足够了,本文就不具体分析配置文件了. 1.Qu ...

  4. 分布式ActiveMQ集群--转载

    原文地址:http://shensy.iteye.com/blog/1752529 回顾总结前一段时间学习的ActiveMQ分布式集群相关的知识,分享出来希望对看到的人有所帮助. 一.分布式Activ ...

  5. Zabbix调优不完全指南(https://www.jianshu.com/p/2d911d55448f)

    从学习搭建zabbix到完成各类监控.调优.二次开发已经过去了两年,期间通过QQ学习群.zabbix官方社区.各个技术博客整理学习了不少关于各种报错的处理方法,现在将常见的一些报错处理方法整理出来分享 ...

  6. 接口测试之——Charles抓包及常见问题解决(转载自https://www.jianshu.com/p/831c0114179f)

    简介 Charles其实是一款代理服务器,通过成为电脑或者浏览器的代理,然后截取请求和请求结果达到分析抓包的目的.该软件是用Java写的,能够在Windows,Mac,Linux上使用,安装Charl ...

  7. jar与war包区别,转自https://www.jianshu.com/p/3b5c45e8e5bd

    https://www.jianshu.com/p/3b5c45e8e5bd

  8. spring boot整合activemq消息中间件

    spring boot整合activemq消息中间件 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi ...

  9. https://www.jianshu.com/p/1038c6170775

    import os # 方法一: os.walk实现 def items_dir(rootname): l = [] for main_dir, dirs, file_name_list in os. ...

随机推荐

  1. Python学习day42-数据库的基本操作(1)

    figure:last-child { margin-bottom: 0.5rem; } #write ol, #write ul { position: relative; } img { max- ...

  2. .net core 使用swagger生成API文档

    [1]安装Swashbuckle.AspNetCore包 [2]在Startup.cs中注册swagger //注册Swagger生成器,定义一个和多个Swagger 文档 services.AddS ...

  3. NopCommerce3.9安装

    除非另外说明,否则本分类所有博文的NopCommerce都基于3.9版本. 用vs2015打开,其他版本的vs没试过. 首先打开解决方案,然后设置Nop.web为启动项目. 启动项目,项目即可自动编译 ...

  4. Ubuntu安装CUDA9.2(不更新驱动)

    1.先装驱动,以为安装CUDA时安装最新驱动导致CUDA用不了 sudo apt-get install nvidia-396 2.参考这,安装好CUDA 9.2 https://developer. ...

  5. 原声js实现nodejs中qs模块中的parse和stringfiy方法

    function stringify(obj, sep, eq) { sep = sep || '&'; eq = eq || '='; let str = ""; for ...

  6. 基于阿里云安装脚本扩展 之 自动安装mongodb及php扩展

    好久没有发布文章了,有点跟不上当初这个博客的初衷.为了使自己的博客更新不半途而废,今天特意再写了一个自动安装脚本,一样是基于阿里云的服务端安装脚本进行的扩展.闲话不说,直接放代码: #!/bin/ba ...

  7. Idea SSH框架整合基础代码

    第一步 pom.xml注入jar包依赖 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi=" ...

  8. LOJ 6497 图

    LOJ 6497 图 题意 有图\(n\)点,每点可为黑或白,其中一些点颜色已定. 初时图无边,于每对\(i<j\),可由\(i\)向\(j\)连有向边,或不连. 称黑白相间之路径为交错路径. ...

  9. Laravel Carbon获取 某个时间后N个月的时间

    $time = "2020-11-20 00:00:00"; $res = (new Carbon)->setTimeFromTimeString($time)->ad ...

  10. 生成中国地区随机IP

    #随机生成IP 中国区    public function randip($member){        if($member['user_ip']){            if($member ...