~~~
package me.jollyfly.rocketmq.starter.core.consumer;
import com.alibaba.rocketmq.client.consumer.DefaultMQPushConsumer;
import com.alibaba.rocketmq.client.exception.MQClientException;
import me.jollyfly.rocketmq.starter.ConsumerOperator;
import me.jollyfly.rocketmq.starter.RocketMqConsumerListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.SmartLifecycle;
import java.util.AbstractMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* @author jolly
*/
public class RocketMessageListenerContainer implements InitializingBean, DisposableBean, BeanNameAware,
SmartLifecycle, ApplicationContextAware, ConsumerOperator {
private final Logger logger = LoggerFactory.getLogger(getClass());
private String nameSrvAddr;
private int consumeThreadMin;
private int consumeThreadMax;
private final Object monitor = new Object();
private final Object mapMonitor = new Object();
private volatile boolean running = false;
private volatile boolean initialized = false;
private List<DefaultMQPushConsumer> pushConsumers = new CopyOnWriteArrayList<>();
private Map<String, DefaultMQPushConsumer> pushConsumerMap = new ConcurrentHashMap<>();
private Map<String, DefaultMQPushConsumer> removedMap = new ConcurrentHashMap<>();
private Map<String, DefaultMQPushConsumer> runningMap = new ConcurrentHashMap<>();
private Map<String, Map.Entry<DefaultMQPushConsumer, String>> startErrMap = new ConcurrentHashMap<>();
private MqPushConsumerFactory consumerFactory;
private ApplicationContext applicationContext;
private String beanName;
@Override
public void start() {
if (!isRunning()) {
running = true;
synchronized (monitor) {
registMessageListener();
startAllListener();
}
}
}
private void startAllListener() {
pushConsumerMap.forEach((topic, consumer) -> {
try {
consumer.start();
runningMap.put(topic, consumer);
} catch (MQClientException e) {
logger.error(e.getErrorMessage());
Map.Entry<DefaultMQPushConsumer, String> errEntry =
new AbstractMap.SimpleEntry<>(consumer, e.getErrorMessage());
startErrMap.put(topic, errEntry);
}
});
}
@Override
public void stop() {
if (isRunning()) {
running = false;
pushConsumers.forEach(DefaultMQPushConsumer::shutdown);
}
if (logger.isDebugEnabled()) {
logger.debug("Stopped RocketMessageListenerContainer");
}
}
@Override
public boolean isRunning() {
return running;
}
@Override
public void setBeanName(String name) {
this.beanName = name;
}
@Override
public void destroy() {
this.initialized = false;
stop();
}
@Override
public void afterPropertiesSet() {
initMqPushConsumerFactory();
this.initialized = true;
}
private void initMqPushConsumerFactory() {
this.consumerFactory = new MqPushConsumerFactory(this.nameSrvAddr);
this.consumerFactory.setApplicationContext(applicationContext);
this.consumerFactory.setConsumeThreadMax(this.consumeThreadMax);
this.consumerFactory.setConsumeThreadMin(this.consumeThreadMin);
this.consumerFactory.afterPropertiesSet();
}
@Override
public boolean isAutoStartup() {
return true;
}
@Override
public void stop(Runnable callback) {
stop();
callback.run();
}
@Override
public int getPhase() {
return Integer.MAX_VALUE;
}
private void registMessageListener() {
SimpleListenerFactory listenerFactory = consumerFactory.getListenerFactory();
pushConsumers.addAll(consumerFactory.getAllMQPushConsumer());
pushConsumerMap.putAll(consumerFactory.getPushConsumerMap());
Map<String, RocketMqConsumerListener> listenerMap = listenerFactory.getAllListeners();
pushConsumerMap.forEach((topic, consumer) -> {
RocketMqConsumerListener listener = listenerMap.get(topic);
if (listener.getConsumerConfig().isOrderlyMessage()) {
consumer.registerMessageListener(new MessageListenerOrderlyImpl(listener));
} else {
consumer.registerMessageListener(new MessageListenerConcurrentlyImpl(listener));
}
});
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@Override
public OperationResult suspendConsumer(String topic) {
return analyzeResult(topic, OperatinType.SUSPEND, () -> {
DefaultMQPushConsumer consumer = runningMap.get(topic);
consumer.suspend();
runningMap.remove(topic);
removedMap.put(topic, consumer);
});
}
@Override
public OperationResult resumeConsumer(String topic) {
return analyzeResult(topic, OperatinType.RESUME, () -> {
DefaultMQPushConsumer consumer = removedMap.get(topic);
consumer.resume();
removedMap.remove(topic);
runningMap.put(topic, consumer);
});
}
private OperationResult analyzeResult(String topic, OperatinType operatinType, Runnable runnable) {
if (initialized) {
FindResult findResult = findInMap(topic);
OperationResult result = new OperationResult();
switch (findResult) {
case NONE:
result.setSuccess(false);
result.setMessage("未找到对应的消费者");
break;
case ERROR:
result.setSuccess(false);
result.setMessage("该消费者启动异常");
break;
case RUNNING:
if (operatinType.equals(OperatinType.SUSPEND)) {
runnable.run();
result.setSuccess(true);
result.setMessage("暂停成功");
} else {
result.setMessage("该消费者正在运行中");
result.setSuccess(false);
}
break;
case SUSPEND:
if (operatinType.equals(OperatinType.RESUME)) {
synchronized (mapMonitor) {
runnable.run();
result.setSuccess(true);
result.setMessage("运行成功");
}
} else {
result.setSuccess(false);
result.setMessage("该消费者正在暂停中");
}
break;
default:
result.setMessage("未知异常");
result.setSuccess(false);
break;
}
return result;
}
return OperationResult.result(false, "容器未初始化");
}
private FindResult findInMap(String topic) {
if (!pushConsumerMap.containsKey(topic)) {
return FindResult.NONE;
} else {
if (startErrMap.containsKey(topic)) {
return FindResult.START_ERROR;
}
if (runningMap.containsKey(topic)) {
return FindResult.RUNNING;
}
if (removedMap.containsKey(topic)) {
return FindResult.SUSPEND;
}
}
return FindResult.ERROR;
}
private enum FindResult {
//未找到
NONE,
//启动异常
START_ERROR,
//运行中
RUNNING,
//停止
SUSPEND,
//其他异常
ERROR
}
private enum OperatinType {
//恢复
RESUME,
//暂停
SUSPEND
}
public String getNameSrvAddr() {
return nameSrvAddr;
}
public void setNameSrvAddr(String nameSrvAddr) {
this.nameSrvAddr = nameSrvAddr;
}
public MqPushConsumerFactory getConsumerFactory() {
return consumerFactory;
}
public void setConsumerFactory(MqPushConsumerFactory consumerFactory) {
this.consumerFactory = consumerFactory;
}
public int getConsumeThreadMin() {
return consumeThreadMin;
}
public void setConsumeThreadMin(int consumeThreadMin) {
this.consumeThreadMin = consumeThreadMin;
}
public int getConsumeThreadMax() {
return consumeThreadMax;
}
public void setConsumeThreadMax(int consumeThreadMax) {
this.consumeThreadMax = consumeThreadMax;
}
}
~~~
1. afterPropertiesSet先调用
2. isRunning
3. start
- Docker
- 什么是docker
- Docker安装、组件启动
- docker网络
- docker命令
- docker swarm
- dockerfile
- mesos
- 运维
- Linux
- Linux基础
- Linux常用命令_1
- Linux常用命令_2
- ip命令
- 什么是Linux
- SELinux
- Linux GCC编译警告:Clock skew detected. 错误解决办法
- 文件描述符
- find
- 资源统计
- LVM
- Linux相关配置
- 服务自启动
- 服务器安全
- 字符集
- shell脚本
- shell命令
- 实用脚本
- shell 数组
- 循环与判断
- 系统级别进程开启和停止
- 函数
- java调用shell脚本
- 发送邮件
- Linux网络配置
- Ubuntu
- Ubuntu发送邮件
- 更换apt-get源
- centos
- 防火墙
- 虚拟机下配置网络
- yum重新安装
- 安装mysql5.7
- 配置本地yum源
- 安装telnet
- 忘记root密码
- rsync+ crontab
- Zabbix
- Zabbix监控
- Zabbix安装
- 自动报警
- 自动发现主机
- 监控MySQL
- 安装PHP常见错误
- 基于nginx安装zabbix
- 监控Tomcat
- 监控redis
- web监控
- 监控进程和端口号
- zabbix自定义监控
- 触发器函数
- zabbix监控mysql主从同步状态
- Jenkins
- 安装Jenkins
- jenkins+svn+maven
- jenkins执行shell脚本
- 参数化构建
- maven区分环境打包
- jenkins使用注意事项
- nginx
- nginx认证功能
- ubuntu下编译安装Nginx
- 编译安装
- Nginx搭建本地yum源
- 文件共享
- Haproxy
- 初识Haproxy
- haproxy安装
- haproxy配置
- virtualbox
- virtualbox 复制新的虚拟机
- ubuntu下vitrualbox安装redhat
- centos配置双网卡
- 配置存储
- Windows
- Windows安装curl
- VMware vSphere
- 磁盘管理
- 增加磁盘
- gitlab
- 安装
- tomcat
- Squid
- bigdata
- FastDFS
- FastFDS基础
- FastFDS安装及简单实用
- api介绍
- 数据存储
- FastDFS防盗链
- python脚本
- ELK
- logstash
- 安装使用
- kibana
- 安准配置
- elasticsearch
- elasticsearch基础_1
- elasticsearch基础_2
- 安装
- 操作
- java api
- 中文分词器
- term vector
- 并发控制
- 对text字段排序
- 倒排和正排索引
- 自定义分词器
- 自定义dynamic策略
- 进阶练习
- 共享锁和排它锁
- nested object
- 父子关系模型
- 高亮
- 搜索提示
- Redis
- redis部署
- redis基础
- redis运维
- redis-cluster的使用
- redis哨兵
- redis脚本备份还原
- rabbitMQ
- rabbitMQ安装使用
- rpc
- RocketMQ
- 架构概念
- 安装
- 实例
- 好文引用
- 知乎
- ACK
- postgresql
- 存储过程
- 编程语言
- 计算机网络
- 基础_01
- tcp/ip
- http转https
- Let's Encrypt免费ssl证书(基于haproxy负载)
- what's the http?
- 网关
- 网络IO
- http
- 无状态网络协议
- Python
- python基础
- 基础数据类型
- String
- List
- 遍历
- Python基础_01
- python基础_02
- python基础03
- python基础_04
- python基础_05
- 函数
- 网络编程
- 系统编程
- 类
- Python正则表达式
- pymysql
- java调用python脚本
- python操作fastdfs
- 模块导入和sys.path
- 编码
- 安装pip
- python进阶
- python之setup.py构建工具
- 模块动态导入
- 内置函数
- 内置变量
- path
- python模块
- 内置模块_01
- 内置模块_02
- log模块
- collections
- Twisted
- Twisted基础
- 异步编程初探与reactor模式
- yield-inlineCallbacks
- 系统编程
- 爬虫
- urllib
- xpath
- scrapy
- 爬虫基础
- 爬虫种类
- 入门基础
- Rules
- 反反爬虫策略
- 模拟登陆
- problem
- 分布式爬虫
- 快代理整站爬取
- 与es整合
- 爬取APP数据
- 爬虫部署
- collection for ban of web
- crawlstyle
- API
- 多次请求
- 向调度器发送请求
- 源码学习
- LinkExtractor源码分析
- 构建工具-setup.py
- selenium
- 基础01
- 与scrapy整合
- Django
- Django开发入门
- Django与MySQL
- java
- 设计模式
- 单例模式
- 工厂模式
- java基础
- java位移
- java反射
- base64
- java内部类
- java高级
- 多线程
- springmvc-restful
- pfx数字证书
- 生成二维码
- 项目中使用log4j
- 自定义注解
- java发送post请求
- Date时间操作
- spring
- 基础
- spring事务控制
- springMVC
- 注解
- 参数绑定
- springmvc+spring+mybatis+dubbo
- MVC模型
- SpringBoot
- java配置入门
- SpringBoot基础入门
- SpringBoot web
- 整合
- SpringBoot注解
- shiro权限控制
- CommandLineRunner
- mybatis
- 静态资源
- SSM整合
- Aware
- Spring API使用
- Aware接口
- mybatis
- 入门
- mybatis属性自动映射、扫描
- 问题
- @Param 注解在Mybatis中的使用 以及传递参数的三种方式
- mybatis-SQL
- 逆向生成dao、model层代码
- 反向工程中Example的使用
- 自增id回显
- SqlSessionDaoSupport
- invalid bound statement(not found)
- 脉络
- beetl
- beetl是什么
- 与SpringBoot整合
- shiro
- 什么是shiro
- springboot+shrio+mybatis
- 拦截url
- 枚举
- 图片操作
- restful
- java项目中日志处理
- JSON
- 文件工具类
- KeyTool生成证书
- 兼容性问题
- 开发规范
- 工具类开发规范
- 压缩图片
- 异常处理
- web
- JavaScript
- 基础语法
- 创建对象
- BOM
- window对象
- DOM
- 闭包
- form提交-文件上传
- td中内容过长
- 问题1
- js高级
- js文件操作
- 函数_01
- session
- jQuery
- 函数01
- data()
- siblings
- index()与eq()
- select2
- 动态样式
- bootstrap
- 表单验证
- 表格
- MUI
- HTML
- iframe
- label标签
- 规范编程
- layer
- sss
- 微信小程序
- 基础知识
- 实践
- 自定义组件
- 修改自定义组件的样式
- 基础概念
- appid
- 跳转
- 小程序发送ajax
- 微信小程序上下拉刷新
- if
- 工具
- idea
- Git
- maven
- svn
- Netty
- 基础概念
- Handler
- SimpleChannelInboundHandler 与 ChannelInboundHandler
- 网络编程
- 网络I/O
- database
- oracle
- 游标
- PLSQL Developer
- mysql
- MySQL基准测试
- mysql备份
- mysql主从不同步
- mysql安装
- mysql函数大全
- SQL语句
- 修改配置
- 关键字
- 主从搭建
- centos下用rpm包安装mysql
- 常用sql
- information_scheme数据库
- 值得学的博客
- mysql学习
- 运维
- mysql权限
- 配置信息
- 好文mark
- jsp
- jsp EL表达式
- C
- test