声明:

上一篇文章是springboot集成阿里ons发布订阅消息,此篇文章是mns发布订阅功能先简单记录一下ons与mns有什么区别

这里是在网上找的对比图:

此处为具体区别文章链接:点击打开链接

但是其实我在实际使用的时候发现区别还是有的。

1、ons的sdk 集成需要配置生产者消费者config文件加载produce和consumer

而mns的sdk 集成到项目里只需要一个MnsConfig文件加载MNSClient

2、ons需要阿里云账户控制台配置获取 ACCESS_KEY 、SECRET_KEY、ONS_ADDR

创建PRODUCER_ID、CONSUMER_ID、TOPIC、TAG(可不建)

mns只需要ACCESS_ID、ACCESS_KEY、ACCOUNT_ENDPOINT 通过控制台生产唯一的。可以在控制台创建队列queue也可以在代码中创建queue和删除队列queue

3.ons的消息发送和接收到topic、mns的消息发送和接收到queue或者topic中 mns有两种发布订阅的方式:

消息服务MNS提供了两种API接口,一种是队列接口,一种是主题接口。

队列接口适用于点对点的消息收发,当接收消息时,需要应用端自行轮询获取消息(拉模式)。

主题接口适用于一对多的消息收发,应用端只需要在某个地址上启动监听,服务端就会主动将消息推送过去(推模式)。

1,其实使用两种方式都有自己的利弊,不然提供两种方式也就没有什么区别了。

2,队列模型保证消息至少会被消费一次, 支持多个生产者和消费者并发操作同一个消息队列。消费消息时尽量做到先进先出,正是因为分布式    消息队列的一些特性并不能保证你能按照消息的发送顺序消费消息,如果你的业务必需先进先出, 建议在消息中加入序号信息以便消费消息后    进行重新排序。

3,主题模型支持服务端主动将消息推送给用户指定的回调地址(Endpoint),消除用户程序不必要的轮询和资源消耗。
    主题模型保证通知消息按照指定的策略推送给用户,支持多个消息发布者并发操作同一个主题。主题模式支持一对多广播消息,一条通知消息可    以同时被多个订阅者接收和消费。

4.ons需要在消费者自定义的实现MessageListener监听器的listener中写自己的业务逻辑

mns的queue不用可以,直接获取到数据,然后随意使用可以封装方法获取到值在自己的实现层调用获取数据编写逻辑

5其他暂时没有遇到,这里暂留

一springboot配置MNS的queue模式发布订阅

查看官网的的操作文档:https://help.aliyun.com/document_detail/32449.html?spm=a2c4g.11174283.6.649.92Il3N

点击打开链接

配置之前的工作,获取到ACCESS_ID、ACCESS_KEY、ACCOUNT_ENDPOINT 通过控制台生产唯一的。可以在控制台创建队列queue也可以在代码中创建queue和删除队列queue

第一步配置pom文件:

<!-- Mq sdk-mns--><dependency><groupId>com.aliyun.mns</groupId><artifactId>aliyun-sdk-mns</artifactId><version>1.1.8</version><classifier>jar-with-dependencies</classifier></dependency>

第二步配置参数类:

第三步配置自动加载创建bean的config类:

@Configuration注解就是启动时自动运行 @Bean创建类到spring上下文中 (注:使用此类时用@Autowired 引入即可,不能用new方法)

import com.aliyun.mns.client.MNSClient;
import com.aliyun.mns.common.utils.ServiceSettings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
public class MnsConfig {private static final Logger LOGGER = LoggerFactory.getLogger(MnsConfig.class);@Bean(name = "client") //获取到本地路径下的配置文件属性内容public MNSClient getClient() {LOGGER.info("start");CloudAccount account = new CloudAccount(ServiceSettings.getMNSAccessKeyId(),ServiceSettings.getMNSAccessKeySecret(),ServiceSettings.getMNSAccountEndpoint());MNSClient client = account.getMNSClient();// 在程序中,CloudAccount以及MNSClient单例实现即可,多线程安全LOGGER.info("信息:{}",client);return client;}

第四步:封装发送消息方法

import com.aliyun.mns.client.CloudAccount;
import com.aliyun.mns.client.CloudQueue;
import com.aliyun.mns.client.MNSClient;
import com.aliyun.mns.common.ClientException;
import com.aliyun.mns.common.ServiceException;
import com.renrenche.databus.common.MnsParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;/*** @author Mood* @date: 2018/6/28 15:30* @version: 1.0* @description: 推送消息给队列通用方法*/
@Service
public class MnsProducer {private final static Logger logger = LoggerFactory.getLogger(MnsProducer.class);@Autowiredprivate MNSClient  client ;//配置文件mnsconfig中配置好,这里使用的时候这样引入就可以了public void sendMessageByConfig(String queueName,String msg) {try {CloudQueue queue = client.getQueueRef(queueName);com.aliyun.mns.model.Message message = new com.aliyun.mns.model.Message();message.setMessageBody(msg);com.aliyun.mns.model.Message putMsg = queue.putMessage(message);System.out.println("Send message id is: " + putMsg.getMessageId());} catch (ClientException ce){System.out.println("Something wrong with the network connection between client and MNS service."+ "Please check your network and DNS availablity.");ce.printStackTrace();} catch (ServiceException se){se.printStackTrace();logger.error("MNS exception requestId:" + se.getRequestId(), se);if (se.getErrorCode() != null) {if (se.getErrorCode().equals("QueueNotExist")){System.out.println("Queue is not exist.Please create before use");} else if (se.getErrorCode().equals("TimeExpired")){System.out.println("The request is time expired. Please check your local machine timeclock");}/*you can get more MNS service error code from following link:https://help.aliyun.com/document_detail/mns/api_reference/error_code/error_code.html*/}} catch (Exception e){System.out.println("Unknown exception happened!");e.printStackTrace();}//client.close();  // 程序退出时,需主动调用client的close方法进行资源释放 配置文件中创建client的话方法应注释掉close 不然调用一次后close了就无法调用第二次了。还要重新new}}

第五步:封装接收消息方法

import com.aliyun.mns.client.CloudAccount;
import com.aliyun.mns.client.CloudQueue;
import com.aliyun.mns.client.MNSClient;
import com.aliyun.mns.common.ClientException;
import com.aliyun.mns.common.ServiceException;
import com.aliyun.mns.model.Message;
import com.renrenche.databus.common.MnsParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;/*** Created by qixin on 2018/6/28.*/
@Service
public class MnsConsumer {private final static Logger logger = LoggerFactory.getLogger(MnsConsumer.class);@Autowiredprivate MNSClient  client ;//配置文件mnsconfig中配置好,这里使用的时候这样引入就可以了public void getMessage(String queueName){/* CloudAccount account = new CloudAccount(MnsParams.ACCESS_ID, MnsParams.ACCESS_KEY, MnsParams.ACCOUNT_ENDPOINT);MNSClient client = account.getMNSClient(); // 在程序中,CloudAccount以及MNSClient单例实现即可,多线程安全*/try{CloudQueue queue = client.getQueueRef(queueName);Message popMsg = queue.popMessage();if (popMsg != null){System.out.println("message handle: " + popMsg.getReceiptHandle());System.out.println("message body: " + popMsg.getMessageBodyAsString());System.out.println("message id: " + popMsg.getMessageId());System.out.println("message dequeue count:" + popMsg.getDequeueCount());//删除已经取出消费的消息queue.deleteMessage(popMsg.getReceiptHandle());System.out.println("delete message successfully.\n");}else{System.out.println("message not exist in TestQueue.\n");}} catch (ClientException ce){System.out.println("Something wrong with the network connection between client and MNS service."+ "Please check your network and DNS availablity.");ce.printStackTrace();} catch (ServiceException se){se.printStackTrace();logger.error("MNS exception requestId:" + se.getRequestId(), se);if (se.getErrorCode() != null) {if (se.getErrorCode().equals("QueueNotExist")){System.out.println("Queue is not exist.Please create before use");} else if (se.getErrorCode().equals("TimeExpired")){System.out.println("The request is time expired. Please check your local machine timeclock");}/*you can get more MNS service error code from following link:https://help.aliyun.com/document_detail/mns/api_reference/error_code/error_code.html*/}} catch (Exception e){System.out.println("Unknown exception happened!");e.printStackTrace();}//client.close();//配置文件中创建client的话方法应注释掉close 不然调用一次后close了就无法调用第二次了。还要重新new}
}

第六步调试发送接收消息(注此处调用发送接收要用注入的方式引入发送接收类不能用new 否则注入失效报null指针异常)

import com.renrenche.databus.consumer.MnsConsumer;
import com.renrenche.databus.producer.MnsProducer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {@Autowiredprivate MnsProducer mnsProducer;@Autowiredprivate MnsConsumer mnsConsumer;@RequestMapping(value = "/sendMessageByConfig", method = RequestMethod.GET)public void sendMessageByConfig() {mnsProducer.sendMessageByConfig("MyQueue","配置文件注入和消费");}@RequestMapping(value = "/getMessageByMns", method = RequestMethod.GET)public void getMessageByMns() {mnsConsumer.getMessage("MyQueue");}}

启动项目可以查看到队列运行日志

postman调用调用发送消息 发送成功返回messageID

postman调用调用接收消息 发送成功返回message信息

二、springboot配置MNS的Topic模式发布订阅

首先与第一种queue第一步和第二步一样。

此处暂留本人还未调试过,等调试之后再补充,

可以参考其他文章 https://blog.csdn.net/syx1065001748/article/details/77453563

点击打开链接

结束!

感谢观看

springboot集成阿里MNS消息队列发布订阅消息功能相关推荐

  1. springboot集成阿里ons消息队列发布订阅消息功能

    此处的项目是springboot项目.使用队列的产品是阿里云ons 消息队列 阿里云的ons消息队列是基于rockermq 项目环境.jdk1.8 使用阿里ons开发的api接口实现发布定于功能生产和 ...

  2. 消息队列——发布订阅模式

    在 Redis 中提供了专门的类型:Publisher(发布者)和 Subscriber(订阅者)来实现消息队列. 在文章开始之前,先来介绍消息队列中有几个基础概念,以便大家更好的理解本文的内容. 首 ...

  3. Java实现redis消息队列发布/订阅模式

    最近在一个老项目中需要用消息队列,本来想着用卡夫卡,但是试了几个版本之后发现jdk和卡夫卡版本一直对不上,最后选择用redis来实现消息队列的发布/订阅模式.感谢这位大佬的博客给了我很多的帮助,htt ...

  4. redis进阶之实现消息队列发布/订阅模式使用(七)

    Redis发布订阅 Redis 发布订阅(pub/sub)是一种消息通信模式:发送者(pub)发送消息,订阅者(sub)接收消息.微信. 微博.关注系统! Redis 客户端可以订阅任意数量的频道. ...

  5. 调试笔记 — Redis 消息队列发布信息被消费者重复订阅多次牵扯到的 Tomcat 配置问题 [#00001]

    最近在项目中发现了一个奇葩的 BUG ,当用户调用后台时,后台向消息队列中发布一条消息,这条消息会被监听器(消费者)监听到,有趣的事情就在这里,此时由于只发送了一条消息,照理说监听器应该只会触发一次, ...

  6. 搭建高吞吐量 Kafka 分布式发布订阅消息 集群

    搭建高吞吐量 Kafka 分布式发布订阅消息 集群 简介 Kafka 是一种高吞吐的分布式发布订阅消息系统,能够替代传统的消息队列用于解耦合数据处理,缓存未处理消息等,同时具有更高的吞吐率,支持分区. ...

  7. Springboot集成rabbitmq实现延时队列

    Springboot集成rabbitmq实现延时队列 什么是延时队列? 列举几个使用场景: 常见的种类有: 延时任务-实现方式: 详细信息:[https://www.cnblogs.com/JonaL ...

  8. 雅虎开源发布/订阅消息平台Pulsar

    雅虎发布了其发布-订阅消息平台Pulsar,这个平台在他们内部已经用在了多项服务的生产环境之中. \\ 按照雅虎的说法,Pulsar是一个低延迟的发布/订阅消息系统,它可以进行水平扩展,跨多个主机和数 ...

  9. ActiveMQ之发布- 订阅消息模式实现

    一.概念 发布者/订阅者模型支持向一个特定的消息主题发布消息.0或多个订阅者可能对接收来自特定消息主题的消息感兴趣.在这种模型下,发布者和订阅者彼此不知道对方.这种模式好比是匿名公告板.这种模式被概括 ...

最新文章

  1. Dialplan 编程基础
  2. LeetCode - 69. x 的平方根
  3. 发挥主观能动性,才可以能常人之所不能 - 阿里云MVP 杨洋专访
  4. Sprint Three 回顾与总结发表评论团队贡献分
  5. [YTU]_2435 ( C++ 习题 输出日期时间--友元函数)
  6. linux 查看nexus状态,在linux上搭建nexus私服(CentOS7)
  7. 考研失败了,该何去何从?
  8. oracle11g dataguard物理备库搭建
  9. 操作对象_DOM进阶——HTML属性操作(对象属性)
  10. 【今日CV 计算机视觉论文速览】Wed, 20 Mar 2019
  11. SpringBoot 2.0 Actuator监控系统
  12. 苹果发明超薄触摸显示技术:iPhone 12系列有望首发搭载
  13. 查python的软件_Python制作天气查询软件【python实战必学】
  14. Spring boot 的profile功能如何实现多环境配置自动切换
  15. Android应用案例开发大全 吴亚峰 苏亚光
  16. 人脸识别门禁系统需求分析文档
  17. FlexPaper pdf文档转换swf
  18. npm WARN read-shrinkwrap This version of npm is compatible with lockfileVersion@1, but package-lock
  19. unity 中Line Renderser初始化有额外线段
  20. QNX 7.1 交叉编译 cron

热门文章

  1. 专升本英语 学习笔记
  2. 小程序的缓存数据什么情况会被清除
  3. 下载任意网站内容到本地
  4. 检查两台主机是否同处于一个局域网
  5. AES加密算法及逆向
  6. 第1讲 快速入门 《Kotlin 极简教程 》
  7. 麦子学院自动化测试-selenium视频教程
  8. C++ STL标准模板库简介
  9. html中调用广告居中,修改CSS让AdSense广告内容居中
  10. 中国电子学会2022年12月份青少年软件编程Scratch图形化等级考试试卷二级真题(含答案)