1 Star 0 Fork 72

没什么好笑的 / 短信协议中间件

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
Apache-2.0

短信协议中间件

介绍

此项目是基于netty的短信协议处理中间件,支持CMPP/SMGP/SGIP/SMPP等协议,集成了流速控制,实现了短信滑动窗口机制。此中间件已经成功应用在日发送量上亿的短信平台中,并且经受住了考验。

项目说明

此项目为完全开源项目,您可以完全基于此开发您自己的商业项目。此项目仅仅是短信协议处理的中间件,如果您需要完整的短信解决方案,请参考我司开源的短信平台单机版 在了解此项目前,您需要熟悉相关的协议细节和短信发送流程。

初衷

github上已经有开源的短信中间件了,为什么还要再开发一套?因为我们发现好多新手包括有一定基础的开发者在内经常为短信提交速度上不去,连接莫名断开等问题困扰。 这个中间件就是要为开发者处理好这些坑点,屏蔽这些细节,让开发者更专注于业务本身。如果你不是netty老手,那选择我们的中间件吧!

项目特点

  1. 为开发者屏蔽了底层协议开发的繁琐和难点,开发者不必花精力解决控速和滑动窗口等难点。
  2. 基于事件注册模式,所有response处理只需要注册相关事件处理器即可,全异步处理。
  3. 支持基于滑动窗口的控速
  4. 支持长短信的自动和并和拆分
  5. 支持上游固定签名通道
  6. 自动的连接重试机制
  7. 丰富的自定义业务实现接口 使用此项目将极大简化您的协议开发流程,减少项目风险。此项目已经在我司开源的短信平台单机版中应用,您可参考项目中的应用来实现自己的业务需求。

使用说明

此项目支持两种发送模式,一种是提供消息提供者实现,

  1. 消息提供者模式(推荐) 由于上下游处理消息的能力不对等,短信项目中一般会将下游提交的短信放置于缓存和队列中,针对此特点我们设计出消息提供者模式,此模式只需要实现MessageProvider从缓存或者队列中获取要发送的消息即可,无需关心速度控制等细节,我司系统都是基于此模式实现。
  2. 主动发送模式 您需要自己实现发送的流速控制,不推荐使用

滑动窗口原理

滑动窗口是为了控制在收到对方response之前,我方系统同时发送的数据包的数量,同时也可起到平滑发送短信的目的。可类比TCP的滑动窗口原理,如下图所示: image

  1. 初始化一个大小为4的队列Queue
  2. 短信发送后放入队列Queue中,如果队列内已经包含4个消息那么不允许再发送短信,上图中已经包含t1,t2,t3,t4四条短信,不允许再发送
  3. 当收到对方的Response响应后释放对应Queue中对象,这样Queue中有空闲未知即可再次发送短信,上图中t1收到response后删除,窗口空余1个,可以发送t5
  4. 针对长期没有Response的对象有单独的线程定时扫描Queue,并对超时的对象做超时处理,并释放

代码示例

CMPP服务器端监听

此程序用于监听下游发送的短信请求,并向下游发送回执和上行,完整程序请参考com.drondea.sms.cmpp.CmppServerPullModeTest类

        //监听端口
        CmppServerSocketConfig socketConfig = new CmppServerSocketConfig("test", 7891);
        //自定义实现的短信接受处理程序(会添加handler处理下游短信请求)
        CmppServerCustomHandler customHandler = new CmppServerCustomHandler();
        //服务器端默认版本号2.0
        socketConfig.setVersion(CmppConstants.VERSION_20);
        CmppServerSessionManager sessionManager = new CmppServerSessionManager(name -> {
            //用户认证逻辑
            if (name.startsWith("100003")) {
                UserChannelConfig userChannelConfig = new UserChannelConfig();
                userChannelConfig.setUserName(name);
                userChannelConfig.setId(name);
                //设置滑动窗口数量
                userChannelConfig.setWindowSize(32);
                userChannelConfig.setPassword("123123");
                //设置用户限速
                userChannelConfig.setQpsLimit(5000);
                return userChannelConfig;
            }
            return null;
        }, socketConfig, customHandler);

        //设置消息提供者(从数据库或者缓存获取消息即可),这里获取的消息是回执或者上行短信
        sessionManager.setMessageProvider(new MessageProvider() {
            @Override
            public List<IMessage> getTcpMessages(ChannelSession channelSession) {

                int i = sum.incrementAndGet();
                if (i > 2) {
                    return null;
                }

                CmppDeliverRequestMessage mo = new CmppDeliverRequestMessage();
                SequenceNumber sequenceNumber = channelSession.getSequenceNumber();
                mo.getHeader().setSequenceId(sequenceNumber.next());
                mo.setRegisteredDelivery((short) 0);
                mo.setMsgContent("TEST");
                mo.setDestId("18010181663");
                //收到响应的回调
                mo.setMessageResponseHandler(new IMessageResponseHandler() {
                    @Override
                    public void messageComplete(IMessage request, IMessage response) {
                        System.out.println("完成:" + request.getSequenceId());
                    }

                    @Override
                    public void messageExpired(String key, IMessage request) {
                        System.out.println("短信超时======" + request.getSequenceId());
                    }

                    @Override
                    public void sendMessageFailed(IMessage request) {
                        System.out.println("send failure:" + request);
                    }
                });
                mo.setMsgFmt(SmsDcs.getGeneralDataCodingDcs(SmsAlphabet.RESERVED));
                return CommonUtil.getLongMsgSlices(mo, channelSession.getConfiguration(), sequenceNumber);
            }

            @Override
            public void responseMessageMatchFailed(String requestKey, IMessage response) {

            }
        });
        sessionManager.doOpen();

CMPP发送短信示例

此程序是向上游通道发送短信的入口程序,负责提交短信和接收上游的回执和上行短信,完整示例请参考com.drondea.sms.cmpp.CmppClientPullModeTest类

        String host = "127.0.0.1";
        //滑动窗口建议值为16
        CmppClientSocketConfig socketConfig = new CmppClientSocketConfig("test",
                10 * 1000, 16, host, 7891);
        socketConfig.setChannelSize(1);
        socketConfig.setUserName("100506");
        socketConfig.setPassword("123123");
        socketConfig.setVersion(CmppConstants.VERSION_20);
        //限速 条/s
        socketConfig.setQpsLimit(100);
        //固定签名设置
//        socketConfig.setSignatureDirection(SignatureDirection.CHANNEL_FIXED);
//        socketConfig.setSignaturePosition(SignaturePosition.PREFIX);
//        socketConfig.setSmsSignature("【庄点科技】");
        //开启超时监控,设置监控间隔时间,这个值最好是RequestExpiryTimeout的1/2
        socketConfig.setWindowMonitorInterval(10 * 1000);
        //设置响应超时时间
        socketConfig.setRequestExpiryTimeout(20 * 1000);
        //注册通道登陆事件,添加回执和上行的处理器
        CmppClientCustomHandler cmppCustomHandler = new CmppClientCustomHandler();

        CmppClientSessionManager sessionManager = new CmppClientSessionManager(socketConfig, cmppCustomHandler);
        //注册消息提供者,一般从MQ、缓存、数据库中获取数据
        sessionManager.setMessageProvider(new MessageProvider() {
            @Override
            public List<IMessage> getTcpMessages(ChannelSession channelSession) {
                int i = sum.incrementAndGet();
                if (i > 5) {
                    return null;
                }
                CmppSubmitRequestMessage requestMessage = new CmppSubmitRequestMessage();
                SequenceNumber sequenceNumber = channelSession.getSequenceNumber();
                requestMessage.getHeader().setSequenceId(sequenceNumber.next());
                String message = i + Math.random() + "第二次李白字太白,号青莲居士,【庄点】";
                requestMessage.setMsgContent(message);
                requestMessage.setServiceId("1");
                requestMessage.setMsgSrc("AAAA");
                requestMessage.setSrcId("" + (int) (Math.random() * 1000));
                requestMessage.setRegisteredDelivery((short) 1);
                requestMessage.setDestUsrTl((short) 1);
                requestMessage.setDestTerminalId(new String[]{"17303110626"});
                requestMessage.setSignature("【庄点科技】");
                //收到响应的回调
                requestMessage.setMessageResponseHandler(new IMessageResponseHandler() {
                    @Override
                    public void messageComplete(IMessage request, IMessage response) {
                        System.out.println("收到response:" + request.getSequenceId());
                    }
                    @Override
                    public void messageExpired(String key,IMessage request) {
                        System.out.println("短信超时======" + request.getSequenceId());
                    }
                    @Override
                    public void sendMessageFailed(IMessage request) {
                        System.out.println("短信发送失败:" + request);
                    }
                });
                requestMessage.setMsgFmt(SmsDcs.getGeneralDataCodingDcs(SmsAlphabet.RESERVED));
                //长短信拆分
                List<IMessage> longMsgSlices = CommonUtil.getLongMsgSlices(requestMessage, channelSession.getConfiguration(), channelSession.getSequenceNumber());
                return longMsgSlices;
            }

            @Override
            public void responseMessageMatchFailed(String requestKey, IMessage response) {
                System.out.println("上游没有response的情况处理");
            }
        });

        //创建链接
        sessionManager.doOpen();
        //定时检测连接,断开自动重连
        sessionManager.doCheckSessions();

技术讨论

交流QQ群: image

致谢

  • cloudhopper-smpp smpp的协议处理很多都是参考了这个项目
  • SMSGate 业务很多思路都借鉴了李黄河大佬的SMSGate,重点感谢
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

简介

此项目是基于netty的短信协议处理中间件,支持CMPP2.0/CMPP3.0/SMGP/SGIP1.2/SMPP等协议,集成了流速控制,实现了短信滑动窗口机制。此中间件已经成功应用在日发送量上亿的短信平台中,并且经受住了考验。 展开 收起
Java
Apache-2.0
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
Java
1
https://gitee.com/xintao/quick-sms.git
git@gitee.com:xintao/quick-sms.git
xintao
quick-sms
短信协议中间件
master

搜索帮助