├── .github └── ISSUE_TEMPLATE │ ├── ask-question.md │ ├── bug_report.md │ └── feature_request.md ├── .gitignore ├── .middleware-common ├── .travis.settings.xml ├── AlipayFormatter.xml ├── check_format.sh ├── intro.png ├── invoke_types.png ├── msg_protocol.png └── pmd_rule_set.xml ├── .travis.yml ├── CONTRIBUTING.md ├── HEADER ├── LICENSE ├── README.md ├── assembly └── assembly.xml ├── doc ├── Bolt-Command.png ├── Bolt-Protocol.png ├── ByteBuf.png ├── 背景.jpg ├── 背景图.jpg └── 蚂蚁通讯框架SOFABolt之私有通讯协议设计.md ├── pom.xml └── src ├── main ├── java │ └── com │ │ └── alipay │ │ └── remoting │ │ ├── AbstractRemotingProcessor.java │ │ ├── AbstractRemotingServer.java │ │ ├── AsyncContext.java │ │ ├── BaseRemoting.java │ │ ├── BizContext.java │ │ ├── CommandCode.java │ │ ├── CommandDecoder.java │ │ ├── CommandEncoder.java │ │ ├── CommandFactory.java │ │ ├── CommandHandler.java │ │ ├── CommonCommandCode.java │ │ ├── Connection.java │ │ ├── ConnectionEventHandler.java │ │ ├── ConnectionEventListener.java │ │ ├── ConnectionEventProcessor.java │ │ ├── ConnectionEventType.java │ │ ├── ConnectionHeartbeatManager.java │ │ ├── ConnectionManager.java │ │ ├── ConnectionMonitorStrategy.java │ │ ├── ConnectionPool.java │ │ ├── ConnectionSelectStrategy.java │ │ ├── CustomSerializer.java │ │ ├── CustomSerializerManager.java │ │ ├── DefaultBizContext.java │ │ ├── DefaultConnectionManager.java │ │ ├── DefaultConnectionMonitor.java │ │ ├── DefaultCustomSerializer.java │ │ ├── HeartbeatTrigger.java │ │ ├── InvokeCallback.java │ │ ├── InvokeCallbackListener.java │ │ ├── InvokeContext.java │ │ ├── InvokeFuture.java │ │ ├── NamedThreadFactory.java │ │ ├── ProcessorManager.java │ │ ├── Protocol.java │ │ ├── ProtocolCode.java │ │ ├── ProtocolManager.java │ │ ├── RandomSelectStrategy.java │ │ ├── ReconnectManager.java │ │ ├── RemotingAddressParser.java │ │ ├── RemotingCommand.java │ │ ├── RemotingContext.java │ │ ├── RemotingProcessor.java │ │ ├── RemotingServer.java │ │ ├── ResponseStatus.java │ │ ├── Scannable.java │ │ ├── ScheduledDisconnectStrategy.java │ │ ├── ServerIdleHandler.java │ │ ├── TimerHolder.java │ │ ├── Url.java │ │ ├── codec │ │ ├── AbstractBatchDecoder.java │ │ ├── Codec.java │ │ ├── ProtocolCodeBasedDecoder.java │ │ └── ProtocolCodeBasedEncoder.java │ │ ├── config │ │ ├── AbstractConfigurableInstance.java │ │ ├── ConfigManager.java │ │ ├── Configs.java │ │ ├── ConfigurableInstance.java │ │ ├── configs │ │ │ ├── ConfigContainer.java │ │ │ ├── ConfigItem.java │ │ │ ├── ConfigType.java │ │ │ ├── DefaultConfigContainer.java │ │ │ └── NettyConfigure.java │ │ └── switches │ │ │ ├── GlobalSwitch.java │ │ │ ├── ProtocolSwitch.java │ │ │ └── Switch.java │ │ ├── connection │ │ ├── AbstractConnectionFactory.java │ │ ├── ConnectionFactory.java │ │ └── DefaultConnectionFactory.java │ │ ├── exception │ │ ├── CodecException.java │ │ ├── ConnectionClosedException.java │ │ ├── DeserializationException.java │ │ ├── RemotingException.java │ │ └── SerializationException.java │ │ ├── log │ │ └── BoltLoggerFactory.java │ │ ├── rpc │ │ ├── DefaultInvokeFuture.java │ │ ├── HeartbeatAckCommand.java │ │ ├── HeartbeatCommand.java │ │ ├── HeartbeatHandler.java │ │ ├── RequestCommand.java │ │ ├── ResponseCommand.java │ │ ├── RpcAddressParser.java │ │ ├── RpcClient.java │ │ ├── RpcClientRemoting.java │ │ ├── RpcCodec.java │ │ ├── RpcCommand.java │ │ ├── RpcCommandFactory.java │ │ ├── RpcCommandType.java │ │ ├── RpcConfigManager.java │ │ ├── RpcConfigs.java │ │ ├── RpcConnectionEventHandler.java │ │ ├── RpcConnectionFactory.java │ │ ├── RpcHandler.java │ │ ├── RpcInvokeCallbackListener.java │ │ ├── RpcRemoting.java │ │ ├── RpcResponseFuture.java │ │ ├── RpcResponseResolver.java │ │ ├── RpcServer.java │ │ ├── RpcServerRemoting.java │ │ ├── RpcTaskScanner.java │ │ ├── exception │ │ │ ├── InvokeException.java │ │ │ ├── InvokeSendFailedException.java │ │ │ ├── InvokeServerBusyException.java │ │ │ ├── InvokeServerException.java │ │ │ ├── InvokeTimeoutException.java │ │ │ └── RpcServerException.java │ │ └── protocol │ │ │ ├── AbstractMultiInterestUserProcessor.java │ │ │ ├── AbstractUserProcessor.java │ │ │ ├── AsynMultiInterestUserProcessor.java │ │ │ ├── AsyncUserProcessor.java │ │ │ ├── MultiInterestUserProcessor.java │ │ │ ├── RpcAsyncContext.java │ │ │ ├── RpcCommandCode.java │ │ │ ├── RpcCommandDecoder.java │ │ │ ├── RpcCommandDecoderV2.java │ │ │ ├── RpcCommandEncoder.java │ │ │ ├── RpcCommandEncoderV2.java │ │ │ ├── RpcCommandHandler.java │ │ │ ├── RpcDeserializeLevel.java │ │ │ ├── RpcHeartBeatProcessor.java │ │ │ ├── RpcHeartbeatTrigger.java │ │ │ ├── RpcProtocol.java │ │ │ ├── RpcProtocolDecoder.java │ │ │ ├── RpcProtocolManager.java │ │ │ ├── RpcProtocolV2.java │ │ │ ├── RpcRequestCommand.java │ │ │ ├── RpcRequestProcessor.java │ │ │ ├── RpcResponseCommand.java │ │ │ ├── RpcResponseProcessor.java │ │ │ ├── SyncMutiInterestUserProcessor.java │ │ │ ├── SyncUserProcessor.java │ │ │ ├── UserProcessor.java │ │ │ └── UserProcessorRegisterHelper.java │ │ ├── serialization │ │ ├── HessianSerializer.java │ │ ├── Serializer.java │ │ └── SerializerManager.java │ │ └── util │ │ ├── ConcurrentHashSet.java │ │ ├── ConnectionUtil.java │ │ ├── CrcUtil.java │ │ ├── FutureTaskNotRunYetException.java │ │ ├── FutureTaskUtil.java │ │ ├── IDGenerator.java │ │ ├── NettyEventLoopUtil.java │ │ ├── RemotingUtil.java │ │ ├── RunStateRecordedFutureTask.java │ │ ├── StringUtils.java │ │ └── TraceLogUtil.java └── resources │ └── com │ └── alipay │ └── remoting │ └── log │ ├── log4j │ └── log-conf.xml │ ├── log4j2 │ └── log-conf.xml │ └── logback │ └── log-conf.xml └── test ├── java └── com │ └── alipay │ └── remoting │ ├── ProcessorManagerTest.java │ ├── RemotingServerTest.java │ ├── compatible │ └── BasicUsageTest.java │ ├── config │ └── DefaultConfigContainerTest.java │ ├── demo │ ├── BasicUsageDemoByJunit.java │ ├── RpcClientDemoByMain.java │ └── RpcServerDemoByMain.java │ ├── inner │ ├── connection │ │ ├── ConcurrentCreateConnectionTest.java │ │ ├── ConnectionTest.java │ │ ├── RpcConnectionManagerTest.java │ │ └── UrlTest.java │ └── utiltest │ │ ├── ConfigManagerTest.java │ │ ├── GlobalSwitchTest.java │ │ ├── ProtocolSwitchTest.java │ │ ├── RemotingUtilTest.java │ │ └── StringUtilsTest.java │ ├── rpc │ ├── BasicUsageTest.java │ ├── BasicUsage_AsyncProcessor_Test.java │ ├── BasicUsage_ProtocolV1_Test.java │ ├── BasicUsage_ProtocolV2_1_Test.java │ ├── BasicUsage_ProtocolV2_2_Test.java │ ├── BasicUsage_SHARE_SAME_SERVER_Test.java │ ├── RpcConfigManagerTest.java │ ├── RpcServerTest.java │ ├── ServerBasicUsageTest.java │ ├── addressargs │ │ ├── AddressArgs_CONNECTIONNUM_Test.java │ │ ├── RpcAddressParserTest.java │ │ └── RpcAddressParser_SOFTREF_Test.java │ ├── callback │ │ └── InvokeCallbackTest.java │ ├── client │ │ └── ClientConnectionTest.java │ ├── common │ │ ├── AsyncClientUserProcessor.java │ │ ├── AsyncExceptionUserProcessor.java │ │ ├── AsyncServerUserProcessor.java │ │ ├── BoltServer.java │ │ ├── CONNECTEventProcessor.java │ │ ├── ConcurrentServerUserProcessor.java │ │ ├── DISCONNECTEventProcessor.java │ │ ├── ExceptionUserProcessor.java │ │ ├── NullUserProcessor.java │ │ ├── PortScan.java │ │ ├── RequestBody.java │ │ ├── SimpleClientUserProcessor.java │ │ └── SimpleServerUserProcessor.java │ ├── connectionmanage │ │ ├── ReconnectManagerTest.java │ │ └── ScheduledDisconnectStrategyTest.java │ ├── exception │ │ ├── BadServerIpTest.java │ │ ├── BasicUsage_AsyncProcessor_Exception_Test.java │ │ ├── BasicUsage_AsyncProcessor_Null_Test.java │ │ ├── ExceptionTest.java │ │ ├── ServerBusyTest.java │ │ ├── ServerInvokeExceptionTest.java │ │ └── ServerUnsupportedOperationExceptionTest.java │ ├── heartbeat │ │ ├── ClientHeartBeatTest.java │ │ ├── CustomHeartBeatProcessor.java │ │ ├── HeartBeatDisableTest.java │ │ ├── RuntimeClientHeartBeatTest.java │ │ └── ServerHeartBeatTest.java │ ├── invokecontext │ │ ├── BasicUsage_InvokeContext_Test.java │ │ ├── BasicUsage_InvokeContext_Url_Test.java │ │ └── BasicUsage_InvokeContext_resuable_Test.java │ ├── lock │ │ └── CreateConnLockTest.java │ ├── prehandle │ │ ├── PreHandleUserProcessor.java │ │ └── PrehandleTest.java │ ├── resrelease │ │ └── ServerClientStopTest.java │ ├── serializer │ │ ├── ClassCustomSerializerTest.java │ │ ├── CodecTest.java │ │ ├── CustomSerializerCodecTest.java │ │ ├── ExceptionRequestBodyCustomSerializer.java │ │ ├── ExceptionStringCustomSerializer.java │ │ ├── NormalRequestBodyCustomSerializer.java │ │ ├── NormalRequestBodyCustomSerializer_InvokeContext.java │ │ ├── NormalStringCustomSerializer.java │ │ └── NormalStringCustomSerializer_InvokeContext.java │ ├── timeout │ │ ├── ServerTimeoutSwitchTest.java │ │ ├── ServerTimeoutTest.java │ │ └── TimeoutTest.java │ ├── userprocessor │ │ ├── UserProcessorRegisterHelperTest.java │ │ ├── executorselector │ │ │ ├── BasicUsage_ExecutorSelector_Test.java │ │ │ ├── CustomHeaderSerializer.java │ │ │ ├── DefaultExecutorSelector.java │ │ │ ├── SpecificClientUserProcessor.java │ │ │ └── SpecificServerUserProcessor.java │ │ ├── multiinterestprocessor │ │ │ ├── BasicUsage_MultiInterestUserProcessorTest.java │ │ │ ├── MultiInterestBaseRequestBody.java │ │ │ ├── RequestBodyC1.java │ │ │ ├── RequestBodyC2.java │ │ │ ├── SimpleClientMultiInterestUserProcessor.java │ │ │ └── SimpleServerMultiInterestUserProcessor.java │ │ └── processinio │ │ │ ├── BasicUsage_ProcessInIoThread_Test.java │ │ │ ├── SpecificClientUserProcessor.java │ │ │ └── SpecificServerUserProcessor.java │ └── watermark │ │ ├── WaterMarkInitTest.java │ │ ├── WaterMarkTest.java │ │ ├── WaterMark_SystemProperty_ExceptionTest.java │ │ └── WaterMark_UserProperty_ExceptionTest.java │ └── util │ └── ThreadTestUtils.java └── resources └── log4j2.xml /.github/ISSUE_TEMPLATE/ask-question.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Ask Question 3 | about: Describe this issue template's purpose here. 4 | 5 | --- 6 | 7 | ### Your question 8 | 9 | describe your question clearly 10 | 11 | ### Your scenes 12 | 13 | describe your use scenes (why need this feature) 14 | 15 | ### Your advice 16 | 17 | describe the advice or solution you'd like 18 | 19 | ### Environment 20 | 21 | - SOFABolt version: 22 | - JVM version (e.g. `java -version`): 23 | - OS version (e.g. `uname -a`): 24 | - Maven version: 25 | - IDE version: 26 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | 5 | --- 6 | 7 | **Describe the bug** 8 | A clear and concise description of what the bug is. 9 | 10 | ### Expected behavior 11 | 12 | ### Actual behavior 13 | 14 | ### Steps to reproduce 15 | 16 | ### Minimal yet complete reproducer code (or GitHub URL to code) 17 | 18 | ### Environment 19 | 20 | - SOFABolt version: 21 | - JVM version (e.g. `java -version`): 22 | - OS version (e.g. `uname -a`): 23 | - Maven version: 24 | - IDE version: 25 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | 5 | --- 6 | 7 | **Is your feature request related to a problem? Please describe.** 8 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 9 | 10 | **Describe the solution you'd like** 11 | A clear and concise description of what you want to happen. 12 | 13 | **Describe alternatives you've considered** 14 | A clear and concise description of any alternative solutions or features you've considered. 15 | 16 | **Additional context** 17 | Add any other context or screenshots about the feature request here. 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | bin 3 | bak 4 | .pmd 5 | .project 6 | .settings 7 | .classpath 8 | .idea.xml 9 | .idea 10 | *.class 11 | *.bak 12 | *.iml 13 | *.ipr 14 | *.iws 15 | bak 16 | null/ 17 | tree.log 18 | tmp/ 19 | velocity.log 20 | coverage-report 21 | test-output 22 | *.txt 23 | -------------------------------------------------------------------------------- /.middleware-common/check_format.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # make sure git has no un commit files 4 | if [ -n "$(git status --untracked-files=no --porcelain)" ]; then 5 | echo "Please commit your change before run this shell, un commit files:" 6 | git status --untracked-files=no --porcelain 7 | exit -1 8 | fi -------------------------------------------------------------------------------- /.middleware-common/intro.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sanshengshui/bolt/7dfa9a1481ceda16a6d1b502891723066d6c9f10/.middleware-common/intro.png -------------------------------------------------------------------------------- /.middleware-common/invoke_types.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sanshengshui/bolt/7dfa9a1481ceda16a6d1b502891723066d6c9f10/.middleware-common/invoke_types.png -------------------------------------------------------------------------------- /.middleware-common/msg_protocol.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sanshengshui/bolt/7dfa9a1481ceda16a6d1b502891723066d6c9f10/.middleware-common/msg_protocol.png -------------------------------------------------------------------------------- /.middleware-common/pmd_rule_set.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | customize rule set priority 6 | 7 | 8 | 1 9 | 10 | 11 | 1 12 | 13 | 14 | 1 15 | 16 | 17 | 1 18 | 19 | 20 | 1 21 | 22 | 23 | 1 24 | 25 | 26 | 1 27 | 28 | 29 | 1 30 | 31 | 32 | 1 33 | 34 | 35 | 1 36 | 37 | 38 | 1 39 | 40 | 41 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | #.travis.yml 2 | language: java 3 | 4 | addons: 5 | apt: 6 | packages: 7 | - openjdk-6-jdk 8 | 9 | jdk: 10 | - oraclejdk8 11 | - openjdk7 12 | - openjdk6 13 | 14 | before_install: 15 | - echo "Downloading Maven 3.2.5" 16 | && wget https://archive.apache.org/dist/maven/maven-3/3.2.5/binaries/apache-maven-3.2.5-bin.zip 17 | && unzip -q apache-maven-3.2.5-bin.zip 18 | && export M2_HOME=$PWD/apache-maven-3.2.5 19 | && export PATH=$M2_HOME/bin:$PATH 20 | && cp ./.middleware-common/.travis.settings.xml $HOME/.m2/settings.xml 21 | && mvn -version 22 | 23 | install: 24 | - mvn clean install -DskipTests=true -Dmaven.javadoc.skip=true -B -V 25 | 26 | script: 27 | - sh ./.middleware-common/check_format.sh 28 | - mvn cobertura:cobertura 29 | 30 | after_success: 31 | - bash <(curl -s https://codecov.io/bash) -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | ## Contributing to SOFABolt 2 | SOFABolt is released under the Apache 2.0 license, and follows a very 3 | standard Github development process, using Github tracker for issues and 4 | merging pull requests into master . If you would like to contribute something, 5 | or simply want to hack on the code this document should help you get started. 6 | 7 | ### Sign the Contributor License Agreement 8 | Before we accept a non-trivial patch or pull request we will need you to 9 | sign the Contributor License Agreement. Signing the contributor’s agreement 10 | does not grant anyone commit rights to the main repository, but it does mean 11 | that we can accept your contributions, and you will get an author credit if 12 | we do. Active contributors might be asked to join the core team, and given 13 | the ability to merge pull requests. 14 | 15 | ### Code Conventions 16 | None of these is essential for a pull request, but they will all help. 17 | 18 | 1. we provided a [code formatter file](./.middleware-common/AlipayFormatter.xml), it will formatting 19 | automatically your project when during process of building. 20 | 21 | 2. Make sure all new `.java` files to have a simple Javadoc class comment 22 | with at least an `@author` tag identifying you, and preferably at least a 23 | paragraph on what the class is for. 24 | 25 | 3. Add the ASF license header comment to all new `.java` files (copy from existing files in the project) 26 | 27 | 4. Add yourself as an `@author` to the `.java` files that you modify substantially (more than cosmetic changes). 28 | 29 | 5. Add some Javadocs. 30 | 31 | 6. A few unit tests would help a lot as well — someone has to do it. 32 | 33 | 7. When writing a commit message please follow [these conventions](https://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html), if 34 | you are fixing an existing issue please add Fixes gh-XXXX at the end 35 | of the commit message (where XXXX is the issue number). -------------------------------------------------------------------------------- /HEADER: -------------------------------------------------------------------------------- 1 | Licensed to the Apache Software Foundation (ASF) under one or more 2 | contributor license agreements. See the NOTICE file distributed with 3 | this work for additional information regarding copyright ownership. 4 | The ASF licenses this file to You under the Apache License, Version 2.0 5 | (the "License"); you may not use this file except in compliance with 6 | the License. You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SOFABolt Project 2 | 3 | [![Build Status](https://travis-ci.org/alipay/sofa-bolt.svg?branch=master)](https://travis-ci.org/alipay/sofa-bolt) 4 | [![Coverage Status](https://codecov.io/gh/alipay/sofa-bolt/branch/master/graph/badge.svg)](https://codecov.io/gh/alipay/sofa-bolt) 5 | ![license](https://img.shields.io/badge/license-Apache--2.0-green.svg) 6 | ![version](https://img.shields.io/badge/bolt-1.5.1-blue.svg) 7 | 8 | # 1. 介绍 9 | SOFABolt 是蚂蚁金融服务集团开发的一套基于 Netty 实现的网络通信框架。 10 | * 为了让 Java 程序员能将更多的精力放在基于网络通信的业务逻辑实现上,而不是过多的纠结于网络底层 NIO 的实现以及处理难以调试的网络问题,Netty 应运而生。 11 | * 为了让中间件开发者能将更多的精力放在产品功能特性实现上,而不是重复地一遍遍制造通信框架的轮子,SOFABolt 应运而生。 12 | 13 | Bolt 名字取自迪士尼动画-闪电狗,是一个基于 Netty 最佳实践的轻量、易用、高性能、易扩展的通信框架。 14 | 这些年我们在微服务与消息中间件在网络通信上解决过很多问题,积累了很多经验,并持续的进行着优化和完善,我们希望能把总结出的解决方案沉淀到 SOFABolt 这个基础组件里,让更多的使用网络通信的场景能够统一受益。 15 | 目前该产品已经运用在了蚂蚁中间件的微服务 ([SOFARPC](https://github.com/alipay/sofa-rpc))、消息中心、分布式事务、分布式开关、以及配置中心等众多产品上。 16 | 17 | # 2. 功能介绍 18 | ![intro](.middleware-common/intro.png) 19 | 20 | ## SOFABolt 的基础功能包括: 21 | * 基础通信功能 ( remoting-core ) 22 | * 基于 Netty 高效的网络 IO 与线程模型运用 23 | * 连接管理 (无锁建连,定时断链,自动重连) 24 | * 基础通信模型 ( oneway,sync,future,callback ) 25 | * 超时控制 26 | * 批量解包与批量提交处理器 27 | * 心跳与 IDLE 事件处理 28 | * 协议框架 ( protocol-skeleton ) 29 | * 命令与命令处理器 30 | * 编解码处理器 31 | * 心跳触发器 32 | * 私有协议定制实现 - RPC 通信协议 ( protocol-implementation ) 33 | * RPC 通信协议的设计 34 | * 灵活的反序列化时机控制 35 | * 请求处理超时 FailFast 机制 36 | * 用户请求处理器 ( UserProcessor ) 37 | * 双工通信 38 | 39 | ## 用法1 40 | 将 SOFABolt 用作一个远程通信框架,使用者可以不用关心如何实现一个私有协议的细节,直接使用我们内置的 RPC 通信协议。可以非常简单的启动客户端与服务端,同时注册一个用户请求处理器,即可完成远程调用。同时,像连接管理、心跳等基础功能特性都默认可以使用。 41 | 当前支持的调用类型如下图所示: 42 | 43 | ![invoke_type](.middleware-common/invoke_types.png) 44 | 45 | * 示例 Demo 请参考我们的 [用户手册](https://github.com/alipay/sofa-bolt/wiki/SOFA-Bolt-Handbook#14-%E5%9F%BA%E7%A1%80%E9%80%9A%E4%BF%A1%E6%A8%A1%E5%9E%8B) 46 | 47 | ## 用法2 48 | 将 SOFABolt 用作一个协议框架,使用者可以复用基础的通信模型、协议包含的接口定义等基础功能。然后根据自己设计的私有协议自定义 Command 类型、Command 处理器、编解码处理器等。如下图所示,RPC 和消息的 Command 定义结构: 49 | 50 | ![msg_protocol](.middleware-common/msg_protocol.png) 51 | 52 | # 4. 如何贡献 53 | 开放代码允许在签署协议之后,提交贡献代码. 54 | 具体参考[如何参与贡献 SOFABolt 代码](./CONTRIBUTING.md) 55 | 56 | # 5. 版权协议 57 | 对 SOFABolt 代码的修改和变更,需要遵守[版权协议](./LICENSE) 58 | 59 | # 6. 有用的链接 60 | * [ISSUES](https://github.com/alipay/sofa-bolt/issues) 61 | * [用户手册](https://github.com/alipay/sofa-bolt/wiki/SOFA-Bolt-Handbook) 62 | * [中文介绍文章: 蚂蚁通信框架实践](http://mp.weixin.qq.com/s/JRsbK1Un2av9GKmJ8DK7IQ) -------------------------------------------------------------------------------- /assembly/assembly.xml: -------------------------------------------------------------------------------- 1 | 19 | 23 | release 24 | 25 | dir 26 | 27 | 28 | 29 | src\main\java 30 | 31 | *.xml 32 | 33 | \ 34 | 35 | 36 | 37 | 38 | 39 | true 40 | lib 41 | runtime 42 | 43 | 44 | -------------------------------------------------------------------------------- /doc/Bolt-Command.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sanshengshui/bolt/7dfa9a1481ceda16a6d1b502891723066d6c9f10/doc/Bolt-Command.png -------------------------------------------------------------------------------- /doc/Bolt-Protocol.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sanshengshui/bolt/7dfa9a1481ceda16a6d1b502891723066d6c9f10/doc/Bolt-Protocol.png -------------------------------------------------------------------------------- /doc/ByteBuf.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sanshengshui/bolt/7dfa9a1481ceda16a6d1b502891723066d6c9f10/doc/ByteBuf.png -------------------------------------------------------------------------------- /doc/背景.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sanshengshui/bolt/7dfa9a1481ceda16a6d1b502891723066d6c9f10/doc/背景.jpg -------------------------------------------------------------------------------- /doc/背景图.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sanshengshui/bolt/7dfa9a1481ceda16a6d1b502891723066d6c9f10/doc/背景图.jpg -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/AsyncContext.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting; 18 | 19 | /** 20 | * Async context for biz. 21 | * 22 | * @author xiaomin.cxm 23 | * @version $Id: AsyncContext.java, v 0.1 May 19, 2016 2:19:05 PM xiaomin.cxm Exp $ 24 | */ 25 | public interface AsyncContext { 26 | /** 27 | * send response back 28 | * 29 | * @param responseObject 30 | */ 31 | void sendResponse(Object responseObject); 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/BizContext.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting; 18 | 19 | /** 20 | * basic info for biz 21 | * 22 | * @author xiaomin.cxm 23 | * @version $Id: BizContext.java, v 0.1 Jan 6, 2016 10:35:04 PM xiaomin.cxm Exp $ 24 | */ 25 | public interface BizContext { 26 | /** 27 | * get remote address 28 | * 29 | * @return 30 | */ 31 | String getRemoteAddress(); 32 | 33 | /** 34 | * get remote host ip 35 | * 36 | * @return 37 | */ 38 | String getRemoteHost(); 39 | 40 | /** 41 | * get remote port 42 | * 43 | * @return 44 | */ 45 | int getRemotePort(); 46 | 47 | /** 48 | * get the connection of this request 49 | * 50 | * @return 51 | */ 52 | Connection getConnection(); 53 | 54 | /** 55 | * check whether request already timeout 56 | * 57 | * @return true if already timeout, you can log some useful info and then discard this request. 58 | */ 59 | boolean isRequestTimeout(); 60 | 61 | /** 62 | * get the timeout value from rpc client. 63 | * 64 | * @return 65 | */ 66 | int getClientTimeout(); 67 | 68 | /** 69 | * get the arrive time stamp 70 | * 71 | * @return 72 | */ 73 | long getArriveTimestamp(); 74 | 75 | /** 76 | * put a key and value 77 | * 78 | * @return 79 | */ 80 | void put(String key, String value); 81 | 82 | /** 83 | * get value 84 | * 85 | * @param key 86 | * @return 87 | */ 88 | String get(String key); 89 | 90 | /** 91 | * get invoke context. 92 | * 93 | * @return 94 | */ 95 | InvokeContext getInvokeContext(); 96 | } -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/CommandCode.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting; 18 | 19 | /** 20 | * Remoting command code stands for a specific remoting command, and every kind of command has its own code. 21 | * 远程命令代码代表一种特定的远程命令,每种命令有自己的编号 22 | * @author jiangping 23 | * @version $Id: CommandCode.java, v 0.1 2015-9-7 PM7:10:18 tao Exp $ 24 | */ 25 | public interface CommandCode { 26 | /** 27 | * 0 被心跳占用,不能被其他命令所使用 28 | */ 29 | // value 0 is occupied by heartbeat, don't use value 0 for other commands 30 | short HEARTBEAT_VALUE = 0; 31 | 32 | /** 33 | * 34 | * @return the short value of the code 35 | */ 36 | short value(); 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/CommandDecoder.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting; 18 | 19 | import java.util.List; 20 | 21 | import io.netty.buffer.ByteBuf; 22 | import io.netty.channel.ChannelHandlerContext; 23 | 24 | /** 25 | * Decode command. 26 | * 解码命令 27 | * @author jiangping 28 | * @version $Id: CommandDecoder.java, v 0.1 Mar 10, 2016 11:32:46 AM jiangping Exp $ 29 | */ 30 | public interface CommandDecoder { 31 | /** 32 | * Decode bytes into object. 33 | * 解码字节数组成实体类 34 | * @param ctx 35 | * @param in 36 | * @param out 37 | * @throws Exception 38 | */ 39 | void decode(ChannelHandlerContext ctx, ByteBuf in, List out) throws Exception; 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/CommandEncoder.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting; 18 | 19 | import java.io.Serializable; 20 | 21 | import io.netty.buffer.ByteBuf; 22 | import io.netty.channel.ChannelHandlerContext; 23 | 24 | /** 25 | * Encode command. 26 | * 编码代码 27 | * @author jiangping 28 | * @version $Id: CommandEncoder.java, v 0.1 Mar 10, 2016 11:33:02 AM jiangping Exp $ 29 | */ 30 | public interface CommandEncoder { 31 | 32 | /** 33 | * Encode object into bytes. 34 | * 编码实体成字节数组 35 | * @param ctx 36 | * @param msg 37 | * @param out 38 | * @throws Exception 39 | */ 40 | void encode(ChannelHandlerContext ctx, Serializable msg, ByteBuf out) throws Exception; 41 | 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/CommandFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting; 18 | 19 | import java.net.InetSocketAddress; 20 | 21 | /** 22 | * Command factory 23 | * 命令工厂 24 | * @author xiaomin.cxm 25 | * @version $Id: CommandFactory.java, v 0.1 Mar 10, 2016 11:24:24 AM yunliang.shi Exp $ 26 | */ 27 | public interface CommandFactory { 28 | // ~~~ create request command 29 | 30 | /** 31 | * create a request command with request object 32 | * 用请求实体生成请求命令 33 | * @param requestObject the request object included in request command 34 | * @param 35 | * @return 36 | */ 37 | T createRequestCommand(final Object requestObject); 38 | 39 | // ~~~ create response command 40 | 41 | /** 42 | * create a normal response with response object 43 | * 用回复实体生成一个正常的回复 44 | * @param responseObject 45 | * @param requestCmd 46 | * @param 47 | * @return 48 | */ 49 | T createResponse(final Object responseObject, 50 | RemotingCommand requestCmd); 51 | 52 | T createExceptionResponse(int id, String errMsg); 53 | 54 | T createExceptionResponse(int id, final Throwable t, String errMsg); 55 | 56 | T createExceptionResponse(int id, ResponseStatus status); 57 | 58 | T createExceptionResponse(int id, ResponseStatus status, 59 | final Throwable t); 60 | 61 | T createTimeoutResponse(final InetSocketAddress address); 62 | 63 | T createSendFailedResponse(final InetSocketAddress address, 64 | Throwable throwable); 65 | 66 | T createConnectionClosedResponse(final InetSocketAddress address, 67 | String message); 68 | } 69 | -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/CommandHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting; 18 | 19 | import java.util.concurrent.ExecutorService; 20 | 21 | /** 22 | * Command handler. 23 | * 命令处理类 24 | * @author jiangping 25 | * @version $Id: CommandHandler.java, v 0.1 2015-12-14 PM4:03:55 tao Exp $ 26 | */ 27 | public interface CommandHandler { 28 | /** 29 | * Handle the command. 30 | * 处理命令 31 | * @param ctx 32 | * @param msg 33 | * @throws Exception 34 | */ 35 | void handleCommand(RemotingContext ctx, Object msg) throws Exception; 36 | 37 | /** 38 | * Register processor for command with specified code. 39 | * 注册命令特定代码的处理器 40 | * @param cmd 41 | * @param processor 42 | */ 43 | void registerProcessor(CommandCode cmd, RemotingProcessor processor); 44 | 45 | /** 46 | * Register default executor for the handler. 47 | * 注册处理类的默认执行者 48 | * @param executor 49 | */ 50 | void registerDefaultExecutor(ExecutorService executor); 51 | 52 | /** 53 | * Get default executor for the handler. 54 | * 得到处理类的默认执行者 55 | */ 56 | ExecutorService getDefaultExecutor(); 57 | 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/CommonCommandCode.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting; 18 | 19 | /** 20 | * The common command code, especially for heart beat command. 21 | * 通用命令代码,专为心跳命令 22 | * @author jiangping 23 | * @version $Id: CommonCommandCode.java, v 0.1 2015-9-21 PM5:05:59 tao Exp $ 24 | */ 25 | public enum CommonCommandCode implements CommandCode { 26 | 27 | HEARTBEAT(CommandCode.HEARTBEAT_VALUE); 28 | 29 | private short value; 30 | 31 | CommonCommandCode(short value) { 32 | this.value = value; 33 | } 34 | 35 | @Override 36 | public short value() { 37 | return this.value; 38 | } 39 | 40 | public static CommonCommandCode valueOf(short value) { 41 | switch (value) { 42 | case CommandCode.HEARTBEAT_VALUE: 43 | return HEARTBEAT; 44 | } 45 | throw new IllegalArgumentException("Unknown Rpc command code value ," + value); 46 | } 47 | 48 | } -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/ConnectionEventListener.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting; 18 | 19 | import java.util.ArrayList; 20 | import java.util.List; 21 | import java.util.concurrent.ConcurrentHashMap; 22 | 23 | /** 24 | * Listen and dispatch connection events. 25 | * @author jiangping 26 | * @version $Id: DefaultConnectionEventListener.java, v 0.1 Mar 5, 2016 10:56:20 AM tao Exp $ 27 | */ 28 | public class ConnectionEventListener { 29 | 30 | private ConcurrentHashMap> processors = new ConcurrentHashMap>( 31 | 3); 32 | 33 | /** 34 | * Dispatch events. 35 | * 36 | * @param type 37 | * @param remoteAddr 38 | * @param conn 39 | */ 40 | public void onEvent(ConnectionEventType type, String remoteAddr, Connection conn) { 41 | List processorList = this.processors.get(type); 42 | if (processorList != null) { 43 | for (ConnectionEventProcessor processor : processorList) { 44 | processor.onEvent(remoteAddr, conn); 45 | } 46 | } 47 | } 48 | 49 | /** 50 | * Add event processor. 51 | * 52 | * @param type 53 | * @param processor 54 | */ 55 | public void addConnectionEventProcessor(ConnectionEventType type, 56 | ConnectionEventProcessor processor) { 57 | List processorList = this.processors.get(type); 58 | if (processorList == null) { 59 | this.processors.putIfAbsent(type, new ArrayList(1)); 60 | processorList = this.processors.get(type); 61 | } 62 | processorList.add(processor); 63 | } 64 | 65 | } 66 | -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/ConnectionEventProcessor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting; 18 | 19 | /** 20 | * Process connection events. 21 | * @author jiangping 22 | * @version $Id: ConnectionEventProcessor.java, v 0.1 Mar 5, 2016 11:01:07 AM tao Exp $ 23 | */ 24 | public interface ConnectionEventProcessor { 25 | /** 26 | * Process event.
27 | * 28 | * @param remoteAddr 29 | * @param conn 30 | */ 31 | void onEvent(String remoteAddr, Connection conn); 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/ConnectionEventType.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting; 18 | 19 | /** 20 | * Event triggered by connection state. 21 | * 22 | * @author jiangping 23 | * @version $Id: ConnectionEventType.java, v 0.1 Mar 4, 2016 8:03:27 PM tao Exp $ 24 | */ 25 | public enum ConnectionEventType { 26 | CONNECT, CLOSE, EXCEPTION; 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/ConnectionHeartbeatManager.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting; 18 | 19 | /** 20 | * Connection heart beat manager, operate heart beat whether enabled for a certain connection at runtime 21 | * 22 | * @author xiaomin.cxm 23 | * @version $Id: ConnectionHeartbeatManager.java, v 0.1 Apr 12, 2016 6:55:56 PM xiaomin.cxm Exp $ 24 | */ 25 | public interface ConnectionHeartbeatManager { 26 | 27 | /** 28 | * disable heart beat for a certain connection 29 | * 30 | * @param connection 31 | */ 32 | void disableHeartbeat(Connection connection); 33 | 34 | /** 35 | * enable heart beat for a certain connection 36 | * 37 | * @param connection 38 | */ 39 | void enableHeartbeat(Connection connection); 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/ConnectionMonitorStrategy.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting; 18 | 19 | import java.util.List; 20 | import java.util.Map; 21 | 22 | import com.alipay.remoting.util.RunStateRecordedFutureTask; 23 | 24 | /** 25 | * The strategy of connection monitor 26 | * 27 | * @author tsui 28 | * @version $Id: ConnectionMonitorStrategy.java, v 0.1 2017-02-21 12:06 tsui Exp $ 29 | */ 30 | public interface ConnectionMonitorStrategy { 31 | 32 | /** 33 | * Filter connections to monitor 34 | * 35 | * @param connections 36 | */ 37 | Map> filter(List connections); 38 | 39 | /** 40 | * Add a set of connections to monitor. 41 | *

42 | * The previous connections in monitor of this protocol, 43 | * will be dropped by monitor automatically. 44 | * 45 | * @param connPools 46 | */ 47 | void monitor(Map> connPools); 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/ConnectionSelectStrategy.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting; 18 | 19 | import java.util.List; 20 | 21 | /** 22 | * Select strategy from connection pool 23 | * 24 | * @author xiaomin.cxm 25 | * @version $Id: ConnectionSelectStrategy.java, v 0.1 Mar 14, 2016 11:06:57 AM xiaomin.cxm Exp $ 26 | */ 27 | public interface ConnectionSelectStrategy { 28 | /** 29 | * select strategy 30 | * 31 | * @param conns 32 | * @return 33 | */ 34 | Connection select(List conns); 35 | } -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/HeartbeatTrigger.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting; 18 | 19 | import io.netty.channel.ChannelHandlerContext; 20 | 21 | /** 22 | * Heartbeat triggers here. 23 | * 心跳触发器 24 | * @author jiangping 25 | * @version $Id: HeartbeatTrigger.java, v 0.1 2015-12-14 PM3:40:38 tao Exp $ 26 | */ 27 | public interface HeartbeatTrigger { 28 | void heartbeatTriggered(final ChannelHandlerContext ctx) throws Exception; 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/InvokeCallback.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting; 18 | 19 | import java.util.concurrent.Executor; 20 | 21 | /** 22 | * Invoke callback. 23 | * 24 | * @author jiangping 25 | * @version $Id: InvokeCallback.java, v 0.1 2015-9-30 AM10:24:26 tao Exp $ 26 | */ 27 | public interface InvokeCallback { 28 | 29 | /** 30 | * Response received. 31 | * 32 | * @param result 33 | */ 34 | void onResponse(final Object result); 35 | 36 | /** 37 | * Exception caught. 38 | * 39 | * @param e 40 | */ 41 | void onException(final Throwable e); 42 | 43 | /** 44 | * User defined executor. 45 | * 46 | * @return 47 | */ 48 | Executor getExecutor(); 49 | 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/InvokeCallbackListener.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting; 18 | 19 | /** 20 | * Listener to listen response and invoke callback. 21 | * 22 | * @author jiangping 23 | * @version $Id: InvokeCallbackListener.java, v 0.1 2015-9-21 PM5:17:08 tao Exp $ 24 | */ 25 | public interface InvokeCallbackListener { 26 | /** 27 | * Response arrived. 28 | * 29 | * @param future 30 | */ 31 | void onResponse(final InvokeFuture future); 32 | 33 | /** 34 | * Get the remote address. 35 | * 36 | * @return 37 | */ 38 | String getRemoteAddress(); 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/NamedThreadFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting; 18 | 19 | import java.util.concurrent.ThreadFactory; 20 | import java.util.concurrent.atomic.AtomicInteger; 21 | 22 | /** 23 | * Thread factory to name the thread purposely 24 | * 创建命名线程工厂 25 | * @author jiangping 26 | * @version $Id: NamedThreadFactory.java, v 0.1 Sept 5, 2016 10:17:10 PM tao Exp $ 27 | */ 28 | public class NamedThreadFactory implements ThreadFactory { 29 | 30 | private static final AtomicInteger poolNumber = new AtomicInteger(1); 31 | private final AtomicInteger threadNumber = new AtomicInteger(1); 32 | private final ThreadGroup group; 33 | private final String namePrefix; 34 | private final boolean isDaemon; 35 | 36 | public NamedThreadFactory() { 37 | this("ThreadPool"); 38 | } 39 | 40 | public NamedThreadFactory(String name) { 41 | this(name, false); 42 | } 43 | 44 | public NamedThreadFactory(String preffix, boolean daemon) { 45 | SecurityManager s = System.getSecurityManager(); 46 | group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup(); 47 | namePrefix = preffix + "-" + poolNumber.getAndIncrement() + "-thread-"; 48 | isDaemon = daemon; 49 | } 50 | 51 | /** 52 | * Create a thread. 53 | * 54 | * @see java.util.concurrent.ThreadFactory#newThread(java.lang.Runnable) 55 | */ 56 | @Override 57 | public Thread newThread(Runnable r) { 58 | Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0); 59 | t.setDaemon(isDaemon); 60 | if (t.getPriority() != Thread.NORM_PRIORITY) { 61 | t.setPriority(Thread.NORM_PRIORITY); 62 | } 63 | return t; 64 | } 65 | 66 | } -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/Protocol.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting; 18 | 19 | /** 20 | * A protocol contains a group of commands. 21 | * 22 | * @author jiangping 23 | * @version $Id: Protocol.java, v 0.1 2015-12-11 PM5:02:48 tao Exp $ 24 | */ 25 | public interface Protocol { 26 | /** 27 | * Get the newEncoder for the protocol. 28 | * 协议编码器方式 29 | * @return 30 | */ 31 | CommandEncoder getEncoder(); 32 | 33 | /** 34 | * Get the decoder for the protocol. 35 | * 协议解码器方式 36 | * @return 37 | */ 38 | CommandDecoder getDecoder(); 39 | 40 | /** 41 | * Get the heartbeat trigger for the protocol. 42 | * 协议相关的心跳触发和处理 43 | * @return 44 | */ 45 | HeartbeatTrigger getHeartbeatTrigger(); 46 | 47 | /** 48 | * Get the command handler for the protocol. 49 | * 命令处理器管理 50 | * @return 51 | */ 52 | CommandHandler getCommandHandler(); 53 | 54 | /** 55 | * Get the command factory for the protocol. 56 | * 可扩展的命令 57 | * @return 58 | */ 59 | CommandFactory getCommandFactory(); 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/ProtocolCode.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting; 18 | 19 | import java.util.Arrays; 20 | 21 | /** 22 | * Protocol code definition, you can define your own protocol code in byte array {@link ProtocolCode#version} 23 | * We suggest to use just one byte for simplicity. 24 | * 25 | * @author tsui 26 | * @version $Id: ProtocolCode.java, v 0.1 2018-03-27 17:23 tsui Exp $ 27 | */ 28 | public class ProtocolCode { 29 | /** bytes to represent protocol code */ 30 | byte[] version; 31 | 32 | private ProtocolCode(byte... version) { 33 | this.version = version; 34 | } 35 | 36 | public static ProtocolCode fromBytes(byte... version) { 37 | return new ProtocolCode(version); 38 | } 39 | 40 | /** 41 | * get the first single byte if your protocol code is single code. 42 | * @return 43 | */ 44 | public byte getFirstByte() { 45 | return this.version[0]; 46 | } 47 | 48 | public int length() { 49 | return this.version.length; 50 | } 51 | 52 | @Override 53 | public boolean equals(Object o) { 54 | if (this == o) { 55 | return true; 56 | } 57 | if (o == null || getClass() != o.getClass()) { 58 | return false; 59 | } 60 | ProtocolCode that = (ProtocolCode) o; 61 | return Arrays.equals(version, that.version); 62 | } 63 | 64 | @Override 65 | public int hashCode() { 66 | return Arrays.hashCode(version); 67 | } 68 | 69 | @Override 70 | public String toString() { 71 | return "ProtocolVersion{" + "version=" + Arrays.toString(version) + '}'; 72 | } 73 | } -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/ProtocolManager.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting; 18 | 19 | import java.util.concurrent.ConcurrentHashMap; 20 | import java.util.concurrent.ConcurrentMap; 21 | 22 | /** 23 | * Manager of all protocols 24 | * 25 | * @author tsui 26 | * @version $Id: ProtocolManager.java, v 0.1 2018-03-27 15:18 tsui Exp $ 27 | */ 28 | public class ProtocolManager { 29 | 30 | private static final ConcurrentMap protocols = new ConcurrentHashMap(); 31 | 32 | public static Protocol getProtocol(ProtocolCode protocolCode) { 33 | return protocols.get(protocolCode); 34 | } 35 | 36 | public static void registerProtocol(Protocol protocol, byte... protocolCodeBytes) { 37 | registerProtocol(protocol, ProtocolCode.fromBytes(protocolCodeBytes)); 38 | } 39 | 40 | public static void registerProtocol(Protocol protocol, ProtocolCode protocolCode) { 41 | if (null == protocolCode || null == protocol) { 42 | throw new RuntimeException("Protocol: " + protocol + " and protocol code:" 43 | + protocolCode + " should not be null!"); 44 | } 45 | Protocol exists = ProtocolManager.protocols.putIfAbsent(protocolCode, protocol); 46 | if (exists != null) { 47 | throw new RuntimeException("Protocol for code: " + protocolCode + " already exists!"); 48 | } 49 | } 50 | 51 | public static Protocol unRegisterProtocol(byte protocolCode) { 52 | return ProtocolManager.protocols.remove(ProtocolCode.fromBytes(protocolCode)); 53 | } 54 | } -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/RemotingAddressParser.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting; 18 | 19 | /** 20 | * Remoting address parser 21 | * 22 | * Implement this to generate a {@link Url} 23 | * 24 | * @author xiaomin.cxm 25 | * @version $Id: RemotingAddressParser.java, v 0.1 Mar 11, 2016 5:56:55 PM xiaomin.cxm Exp $ 26 | */ 27 | public interface RemotingAddressParser { 28 | /** 29 | * Parse a simple string url to get {@link Url} 30 | * 31 | * @param url 32 | * @return parsed {@link Url} 33 | */ 34 | Url parse(String url); 35 | 36 | /** 37 | * Parse a simple string url to get a unique key of a certain address 38 | * 39 | * @param url 40 | * @return 41 | */ 42 | String parseUniqueKey(String url); 43 | 44 | /** 45 | * Parse to get property value according to specified property key 46 | * 47 | * @param url 48 | * @param propKey 49 | * @return propValue 50 | */ 51 | String parseProperty(String url, String propKey); 52 | 53 | /** 54 | * Initialize {@link Url} arguments 55 | * 56 | * @param url 57 | */ 58 | void initUrlArgs(Url url); 59 | 60 | /** symbol : */ 61 | char COLON = ':'; 62 | 63 | /** symbol = */ 64 | char EQUAL = '='; 65 | 66 | /** symbol & */ 67 | char AND = '&'; 68 | 69 | /** symbol ? */ 70 | char QUES = '?'; 71 | } 72 | -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/RemotingProcessor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting; 18 | 19 | import java.util.concurrent.ExecutorService; 20 | 21 | /** 22 | * Remoting processor processes remoting commands. 23 | * 远程处理器处理远程处理命令 24 | * @author jiangping 25 | * @version $Id: RemotingProcessor.java, v 0.1 Dec 22, 2015 11:48:43 AM tao Exp $ 26 | */ 27 | public interface RemotingProcessor { 28 | 29 | /** 30 | * Process the remoting command. 31 | * 处理远程命令 32 | * @param ctx 33 | * @param msg 34 | * @param defaultExecutor 35 | * @throws Exception 36 | */ 37 | void process(RemotingContext ctx, T msg, ExecutorService defaultExecutor) throws Exception; 38 | 39 | /** 40 | * Get the executor. 41 | * 获取线程池 42 | * @return 43 | */ 44 | ExecutorService getExecutor(); 45 | 46 | /** 47 | * Set executor. 48 | * 设置线程池 49 | * @param executor 50 | */ 51 | void setExecutor(ExecutorService executor); 52 | 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/RemotingServer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting; 18 | 19 | import java.util.concurrent.ExecutorService; 20 | 21 | import com.alipay.remoting.rpc.protocol.UserProcessor; 22 | 23 | /** 24 | * @author chengyi (mark.lx@antfin.com) 2018-06-16 06:55 25 | */ 26 | public interface RemotingServer { 27 | 28 | /** 29 | * init the server 30 | */ 31 | @Deprecated 32 | void init(); 33 | 34 | /** 35 | * Start the server. 36 | */ 37 | boolean start(); 38 | 39 | /** 40 | * Stop the server. 41 | * 42 | * Remoting server can not be used any more after stop. 43 | * If you need, you should destroy it, and instantiate another one. 44 | */ 45 | boolean stop(); 46 | 47 | /** 48 | * Get the ip of the server. 49 | * 50 | * @return ip 51 | */ 52 | String ip(); 53 | 54 | /** 55 | * Get the port of the server. 56 | * 57 | * @return listened port 58 | */ 59 | int port(); 60 | 61 | /** 62 | * Register processor for command with the command code. 63 | * 64 | * @param protocolCode protocol code 65 | * @param commandCode command code 66 | * @param processor processor 67 | */ 68 | void registerProcessor(byte protocolCode, CommandCode commandCode, 69 | RemotingProcessor processor); 70 | 71 | /** 72 | * Register default executor service for server. 73 | * 74 | * @param protocolCode protocol code 75 | * @param executor the executor service for the protocol code 76 | */ 77 | void registerDefaultExecutor(byte protocolCode, ExecutorService executor); 78 | 79 | /** 80 | * Register user processor. 81 | * 82 | * @param processor user processor which can be a single-interest processor or a multi-interest processor 83 | */ 84 | void registerUserProcessor(UserProcessor processor); 85 | 86 | } 87 | -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/Scannable.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting; 18 | 19 | /** 20 | * Can be scanned. 21 | * 22 | * @author jiangping 23 | * @version $Id: Scannable.java, v 0.1 Mar 4, 2016 4:46:41 PM tao Exp $ 24 | */ 25 | public interface Scannable { 26 | /** 27 | * Scan it. 28 | */ 29 | void scan(); 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/ServerIdleHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting; 18 | 19 | import org.slf4j.Logger; 20 | 21 | import com.alipay.remoting.log.BoltLoggerFactory; 22 | import com.alipay.remoting.util.RemotingUtil; 23 | 24 | import io.netty.channel.ChannelDuplexHandler; 25 | import io.netty.channel.ChannelHandler.Sharable; 26 | import io.netty.channel.ChannelHandlerContext; 27 | import io.netty.handler.timeout.IdleStateEvent; 28 | 29 | /** 30 | * Server Idle handler. 31 | * 32 | * In the server side, the connection will be closed if it is idle for a certain period of time. 33 | * 34 | * @author jiangping 35 | * @version $Id: ServerIdleHandler.java, v 0.1 Nov 3, 2015 05:23:19 PM tao Exp $ 36 | */ 37 | @Sharable 38 | public class ServerIdleHandler extends ChannelDuplexHandler { 39 | 40 | private static final Logger logger = BoltLoggerFactory.getLogger("CommonDefault"); 41 | 42 | /** 43 | * 44 | * @see io.netty.channel.ChannelInboundHandlerAdapter#userEventTriggered(io.netty.channel.ChannelHandlerContext, java.lang.Object) 45 | */ 46 | @Override 47 | public void userEventTriggered(final ChannelHandlerContext ctx, Object evt) throws Exception { 48 | if (evt instanceof IdleStateEvent) { 49 | try { 50 | logger.warn("Connection idle, close it from server side: {}", 51 | RemotingUtil.parseRemoteAddress(ctx.channel())); 52 | ctx.close(); 53 | } catch (Exception e) { 54 | logger.warn("Exception caught when closing connection in ServerIdleHandler.", e); 55 | } 56 | } else { 57 | super.userEventTriggered(ctx, evt); 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/TimerHolder.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting; 18 | 19 | import java.util.concurrent.TimeUnit; 20 | 21 | import io.netty.util.HashedWheelTimer; 22 | import io.netty.util.Timer; 23 | 24 | /** 25 | * A singleton holder of the timer for timeout. 26 | * 超时的单例持有者 27 | * 28 | * @author jiangping 29 | * @version $Id: TimerHolder.java, v 0.1 2015-09-28 2:02:20 tao Exp $ 30 | */ 31 | public class TimerHolder { 32 | 33 | private final static long defaultTickDuration = 10; 34 | 35 | // Netty时间轮算法实现 36 | private static class DefaultInstance { 37 | static final Timer INSTANCE = new HashedWheelTimer(new NamedThreadFactory( 38 | "DefaultTimer" + defaultTickDuration, true), 39 | defaultTickDuration, TimeUnit.MILLISECONDS); 40 | } 41 | 42 | private TimerHolder() { 43 | } 44 | 45 | /** 46 | * Get a singleton instance of {@link Timer}.
47 | * The tick duration is {@link #defaultTickDuration}. 48 | * 49 | * @return Timer 50 | */ 51 | public static Timer getTimer() { 52 | return DefaultInstance.INSTANCE; 53 | } 54 | } -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/codec/Codec.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.codec; 18 | 19 | import io.netty.channel.ChannelHandler; 20 | 21 | /** 22 | * Codec interface. 23 | * 24 | * @author chengyi (mark.lx@antfin.com) 2018-06-20 21:07 25 | */ 26 | public interface Codec { 27 | 28 | /** 29 | * Create an encoder instance. 30 | * 31 | * @return new encoder instance 32 | */ 33 | ChannelHandler newEncoder(); 34 | 35 | /** 36 | * Create an decoder instance. 37 | * 38 | * @return new decoder instance 39 | */ 40 | ChannelHandler newDecoder(); 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/codec/ProtocolCodeBasedEncoder.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.codec; 18 | 19 | import java.io.Serializable; 20 | 21 | import com.alipay.remoting.Connection; 22 | import com.alipay.remoting.Protocol; 23 | import com.alipay.remoting.ProtocolCode; 24 | import com.alipay.remoting.ProtocolManager; 25 | 26 | import io.netty.buffer.ByteBuf; 27 | import io.netty.channel.ChannelHandler; 28 | import io.netty.channel.ChannelHandlerContext; 29 | import io.netty.handler.codec.MessageToByteEncoder; 30 | import io.netty.util.Attribute; 31 | 32 | /** 33 | * Protocol code based newEncoder, the main newEncoder for a certain protocol, which is lead by one or multi bytes (magic code). 34 | * 35 | * Notice: this is stateless can be noted as {@link io.netty.channel.ChannelHandler.Sharable} 36 | * @author jiangping 37 | * @version $Id: ProtocolCodeBasedEncoder.java, v 0.1 2015-12-11 PM 7:30:30 tao Exp $ 38 | */ 39 | @ChannelHandler.Sharable 40 | public class ProtocolCodeBasedEncoder extends MessageToByteEncoder { 41 | 42 | /** default protocol code */ 43 | protected ProtocolCode defaultProtocolCode; 44 | 45 | public ProtocolCodeBasedEncoder(ProtocolCode defaultProtocolCode) { 46 | super(); 47 | this.defaultProtocolCode = defaultProtocolCode; 48 | } 49 | 50 | @Override 51 | protected void encode(ChannelHandlerContext ctx, Serializable msg, ByteBuf out) 52 | throws Exception { 53 | Attribute att = ctx.channel().attr(Connection.PROTOCOL); 54 | ProtocolCode protocolCode; 55 | if (att == null || att.get() == null) { 56 | protocolCode = this.defaultProtocolCode; 57 | } else { 58 | protocolCode = att.get(); 59 | } 60 | Protocol protocol = ProtocolManager.getProtocol(protocolCode); 61 | protocol.getEncoder().encode(ctx, msg, out); 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/config/AbstractConfigurableInstance.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.config; 18 | 19 | import com.alipay.remoting.config.configs.ConfigContainer; 20 | import com.alipay.remoting.config.configs.ConfigItem; 21 | import com.alipay.remoting.config.configs.ConfigType; 22 | import com.alipay.remoting.config.configs.DefaultConfigContainer; 23 | import com.alipay.remoting.config.switches.GlobalSwitch; 24 | 25 | /** 26 | * common implementation for a configurable instance 27 | * 28 | * @author tsui 29 | * @version $Id: AbstractConfigurableInstance.java, v 0.1 2018-07-30 21:11 tsui Exp $$ 30 | */ 31 | public class AbstractConfigurableInstance implements ConfigurableInstance { 32 | private ConfigContainer configContainer = new DefaultConfigContainer(); 33 | private GlobalSwitch globalSwitch = new GlobalSwitch(); 34 | private ConfigType configType; 35 | 36 | protected AbstractConfigurableInstance(ConfigType configType) { 37 | this.configType = configType; 38 | } 39 | 40 | @Override 41 | public ConfigContainer conf() { 42 | return this.configContainer; 43 | } 44 | 45 | @Override 46 | public GlobalSwitch switches() { 47 | return this.globalSwitch; 48 | } 49 | 50 | @Override 51 | public void initWriteBufferWaterMark(int low, int high) { 52 | this.configContainer.set(configType, ConfigItem.NETTY_BUFFER_LOW_WATER_MARK, low); 53 | this.configContainer.set(configType, ConfigItem.NETTY_BUFFER_HIGH_WATER_MARK, high); 54 | } 55 | 56 | @Override 57 | public int netty_buffer_low_watermark() { 58 | if (null != configContainer 59 | && configContainer.contains(configType, ConfigItem.NETTY_BUFFER_LOW_WATER_MARK)) { 60 | return (Integer) configContainer 61 | .get(configType, ConfigItem.NETTY_BUFFER_LOW_WATER_MARK); 62 | } else { 63 | return ConfigManager.netty_buffer_low_watermark(); 64 | } 65 | } 66 | 67 | @Override 68 | public int netty_buffer_high_watermark() { 69 | if (null != configContainer 70 | && configContainer.contains(configType, ConfigItem.NETTY_BUFFER_HIGH_WATER_MARK)) { 71 | return (Integer) configContainer.get(configType, 72 | ConfigItem.NETTY_BUFFER_HIGH_WATER_MARK); 73 | } else { 74 | return ConfigManager.netty_buffer_high_watermark(); 75 | } 76 | } 77 | } -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/config/ConfigurableInstance.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.config; 18 | 19 | import com.alipay.remoting.config.configs.ConfigContainer; 20 | import com.alipay.remoting.config.configs.NettyConfigure; 21 | import com.alipay.remoting.config.switches.GlobalSwitch; 22 | 23 | /** 24 | * define an interface which can be used to implement configurable apis. 25 | * 26 | * @author tsui 27 | * @version $Id: ConfigurableInstance.java, v 0.1 2018-07-30 21:09 tsui Exp $$ 28 | */ 29 | public interface ConfigurableInstance extends NettyConfigure { 30 | 31 | /** 32 | * get the config container for current instance 33 | * 34 | * @return the config container 35 | */ 36 | ConfigContainer conf(); 37 | 38 | /** 39 | * get the global switch for current instance 40 | * @return the global switch 41 | */ 42 | GlobalSwitch switches(); 43 | } -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/config/configs/ConfigContainer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.config.configs; 18 | 19 | /** 20 | * the interface of a config container 21 | * 22 | * Mainly used to manage config by user api, this is instance related, not globally. 23 | * That is to say, different remoting instance client or server hold different ConfigContainer. 24 | * 25 | * @author tsui 26 | * @version $Id: ConfigContainer.java, v 0.1 2018-07-28 18:31 tsui Exp $$ 27 | */ 28 | public interface ConfigContainer { 29 | /** 30 | * check whether a config item of a certain config type exist. 31 | * @param configType config types in the config container, different config type can hold the same config item key 32 | * @param configItem config items in the config container 33 | * @return exist then return true, not exist return alse 34 | */ 35 | boolean contains(ConfigType configType, ConfigItem configItem); 36 | 37 | /** 38 | * try to get config value using config type and config item. 39 | * @param configType config types in the config container, different config type can hold the same config item key 40 | * @param configItem config items in the config container 41 | * @param the generics of return value 42 | * @return the right value and cast to type T, if no mappings, then return null 43 | */ 44 | T get(ConfigType configType, ConfigItem configItem); 45 | 46 | /** 47 | * init a config item with certain config type, and the value can be any type. 48 | * Notice: the value can be overwrite if you set more than once. 49 | * 50 | * @param configType config types in the config container, different config type can hold the same config item key 51 | * @param configItem config items in the config container 52 | */ 53 | void set(ConfigType configType, ConfigItem configItem, Object value); 54 | } -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/config/configs/ConfigItem.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.config.configs; 18 | 19 | /** 20 | * Items of config. 21 | * 22 | * Mainly used to define some config items managed by {@link ConfigContainer}. 23 | * You can define new config items based on this if need. 24 | * 25 | * @author tsui 26 | * @version $Id: ConfigItem.java, v 0.1 2018-07-28 17:43 tsui Exp $$ 27 | */ 28 | public enum ConfigItem { 29 | // ~~~ netty related 30 | NETTY_BUFFER_LOW_WATER_MARK, // netty writer buffer low water mark 31 | NETTY_BUFFER_HIGH_WATER_MARK // netty writer buffer high water mark 32 | } -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/config/configs/ConfigType.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.config.configs; 18 | 19 | /** 20 | * type of config 21 | * 22 | * @author tsui 23 | * @version $Id: ConfigType.java, v 0.1 2018-07-28 17:41 tsui Exp $$ 24 | */ 25 | public enum ConfigType { 26 | CLIENT_SIDE, // configs of this type can only be used in client side 27 | SERVER_SIDE // configs of this type can only be used in server side 28 | } -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/config/configs/NettyConfigure.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.config.configs; 18 | 19 | /** 20 | * netty related configuration items 21 | * 22 | * @author tsui 23 | * @version $Id: NettyConfigure.java, v 0.1 2018-07-30 21:42 tsui Exp $$ 24 | */ 25 | public interface NettyConfigure { 26 | /** 27 | * Initialize netty write buffer water mark for remoting instance. 28 | *

29 | * Notice: This api should be called before init remoting instance. 30 | * 31 | * @param low [0, high] 32 | * @param high [high, Integer.MAX_VALUE) 33 | */ 34 | void initWriteBufferWaterMark(int low, int high); 35 | 36 | /** 37 | * get the low water mark for netty write buffer 38 | * @return low watermark 39 | */ 40 | int netty_buffer_low_watermark(); 41 | 42 | /** 43 | * get the high water mark for netty write buffer 44 | * @return high watermark 45 | */ 46 | int netty_buffer_high_watermark(); 47 | } -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/config/switches/GlobalSwitch.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.config.switches; 18 | 19 | import java.util.BitSet; 20 | 21 | import com.alipay.remoting.config.ConfigManager; 22 | 23 | /** 24 | * Global switches used in client or server 25 | *

26 | * NOTICE:
27 | * 1. system settings will take effect in all bolt client or server instances in one process
28 | * 2. user settings will only take effect in the current instance of bolt client or server. 29 | *

30 | * 31 | * @author tsui 32 | * @version $Id: GlobalSwitch.java, v 0.1 2017-08-03 15:50 tsui Exp $ 33 | */ 34 | public class GlobalSwitch implements Switch { 35 | 36 | // switches 37 | public static final int CONN_RECONNECT_SWITCH = 0; 38 | public static final int CONN_MONITOR_SWITCH = 1; 39 | public static final int SERVER_MANAGE_CONNECTION_SWITCH = 2; 40 | public static final int SERVER_SYNC_STOP = 3; 41 | 42 | /** user settings */ 43 | private BitSet userSettings = new BitSet(); 44 | 45 | /** 46 | * Init with system default value 47 | * if settings exist by system property then use system property at first; 48 | * if no settings exist by system property then use default value in {@link com.alipay.remoting.config.Configs} 49 | * All these settings can be overwrite by user api settings. 50 | */ 51 | public GlobalSwitch() { 52 | if (ConfigManager.conn_reconnect_switch()) { 53 | userSettings.set(CONN_RECONNECT_SWITCH); 54 | } else { 55 | userSettings.clear(CONN_RECONNECT_SWITCH); 56 | } 57 | 58 | if (ConfigManager.conn_monitor_switch()) { 59 | userSettings.set(CONN_MONITOR_SWITCH); 60 | } else { 61 | userSettings.clear(CONN_MONITOR_SWITCH); 62 | } 63 | } 64 | 65 | // ~~~ public methods 66 | @Override 67 | public void turnOn(int index) { 68 | this.userSettings.set(index); 69 | } 70 | 71 | @Override 72 | public void turnOff(int index) { 73 | this.userSettings.clear(index); 74 | } 75 | 76 | @Override 77 | public boolean isOn(int index) { 78 | return this.userSettings.get(index); 79 | } 80 | } -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/config/switches/Switch.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.config.switches; 18 | 19 | /** 20 | * switch interface 21 | * 22 | * @author tsui 23 | * @version $Id: Switch.java, v 0.1 2018-04-08 11:26 tsui Exp $ 24 | */ 25 | public interface Switch { 26 | /** 27 | * api for user to turn on a feature 28 | * 29 | * @param index the switch index of feature 30 | */ 31 | void turnOn(int index); 32 | 33 | /** 34 | * api for user to turn off a feature 35 | * @param index the switch index of feature 36 | */ 37 | void turnOff(int index); 38 | 39 | /** 40 | * check switch whether on 41 | * 42 | * @param index the switch index of feature 43 | * @return true if either system setting is on or user setting is on 44 | */ 45 | boolean isOn(int index); 46 | } -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/connection/ConnectionFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.connection; 18 | 19 | import com.alipay.remoting.Connection; 20 | import com.alipay.remoting.ConnectionEventHandler; 21 | import com.alipay.remoting.Url; 22 | 23 | /** 24 | * Factory that creates connections. 25 | * 26 | * @author jiangping 27 | * @version $Id: ConnectionFactory.java, v 0.1 2015-9-21 PM7:47:46 tao Exp $ 28 | */ 29 | public interface ConnectionFactory { 30 | 31 | /** 32 | * Initialize the factory. 33 | */ 34 | void init(ConnectionEventHandler connectionEventHandler); 35 | 36 | /** 37 | * Create a connection use #BoltUrl 38 | * 39 | * @param url target url 40 | * @return connection 41 | */ 42 | Connection createConnection(Url url) throws Exception; 43 | 44 | /** 45 | * Create a connection according to the IP and port. 46 | * Note: The default protocol is RpcProtocol. 47 | * 48 | * @param targetIP target ip 49 | * @param targetPort target port 50 | * @param connectTimeout connect timeout in millisecond 51 | * @return connection 52 | */ 53 | Connection createConnection(String targetIP, int targetPort, int connectTimeout) 54 | throws Exception; 55 | 56 | /** 57 | * Create a connection according to the IP and port. 58 | * 59 | * Note: The default protocol is RpcProtocolV2, and you can specify the version 60 | * 61 | * @param targetIP target ip 62 | * @param targetPort target port 63 | * @param version protocol version 64 | * @param connectTimeout connect timeout in millisecond 65 | * @return connection 66 | */ 67 | Connection createConnection(String targetIP, int targetPort, byte version, int connectTimeout) 68 | throws Exception; 69 | } 70 | -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/connection/DefaultConnectionFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.connection; 18 | 19 | import com.alipay.remoting.codec.Codec; 20 | import com.alipay.remoting.config.ConfigurableInstance; 21 | 22 | import io.netty.channel.ChannelHandler; 23 | 24 | /** 25 | * Default connection factory. 26 | * 27 | * @author chengyi (mark.lx@antfin.com) 2018-06-20 15:18 28 | */ 29 | public class DefaultConnectionFactory extends AbstractConnectionFactory { 30 | 31 | public DefaultConnectionFactory(Codec codec, ChannelHandler heartbeatHandler, 32 | ChannelHandler handler, ConfigurableInstance configInstance) { 33 | super(codec, heartbeatHandler, handler, configInstance); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/exception/CodecException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.exception; 18 | 19 | /** 20 | * Exception when codec problems occur 21 | * 当编解码出现问题,抛出此类。 22 | * @author xiaomin.cxm 23 | * @version $Id: CodecException.java, v 0.1 2016-1-3 PM 6:26:12 xiaomin.cxm Exp $ 24 | */ 25 | public class CodecException extends RemotingException { 26 | 27 | /** For serialization */ 28 | private static final long serialVersionUID = -7513762648815278960L; 29 | 30 | /** 31 | * Constructor. 32 | */ 33 | public CodecException() { 34 | } 35 | 36 | /** 37 | * Constructor. 38 | * 39 | * @param message the detail message. 40 | */ 41 | public CodecException(String message) { 42 | super(message); 43 | } 44 | 45 | /** 46 | * Constructor. 47 | * 48 | * @param message the detail message 49 | * @param cause the cause 50 | */ 51 | public CodecException(String message, Throwable cause) { 52 | super(message, cause); 53 | } 54 | 55 | } -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/exception/ConnectionClosedException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.exception; 18 | 19 | /** 20 | * Exception when connection is closed. 21 | * 当连接异常关闭时,抛出此类 22 | * @author jiangping 23 | * @version $Id: ConnectionClosedException.java, v 0.1 Jan 15, 2016 3:13:12 PM tao Exp $ 24 | */ 25 | public class ConnectionClosedException extends RemotingException { 26 | 27 | /** For serialization */ 28 | private static final long serialVersionUID = -2595820033346329315L; 29 | 30 | /** 31 | * Default constructor. 32 | */ 33 | public ConnectionClosedException() { 34 | } 35 | 36 | public ConnectionClosedException(String msg) { 37 | super(msg); 38 | } 39 | 40 | public ConnectionClosedException(String msg, Throwable cause) { 41 | super(msg, cause); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/exception/DeserializationException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.exception; 18 | 19 | /** 20 | * Exception when deserialize failed 21 | * 当反序列化出现异常时,抛出异常类 22 | * @author tsui 23 | * @version $Id: DeserializationException.java, v 0.1 2017-07-26 16:13 tsui Exp $ 24 | */ 25 | public class DeserializationException extends CodecException { 26 | /** For serialization */ 27 | private static final long serialVersionUID = 310446237157256052L; 28 | 29 | private boolean serverSide = false; 30 | 31 | /** 32 | * Constructor. 33 | */ 34 | public DeserializationException() { 35 | 36 | } 37 | 38 | /** 39 | * Constructor. 40 | */ 41 | public DeserializationException(String message) { 42 | super(message); 43 | } 44 | 45 | /** 46 | * Constructor. 47 | */ 48 | public DeserializationException(String message, boolean serverSide) { 49 | this(message); 50 | this.serverSide = serverSide; 51 | } 52 | 53 | /** 54 | * Constructor. 55 | */ 56 | public DeserializationException(String message, Throwable cause) { 57 | super(message, cause); 58 | } 59 | 60 | /** 61 | * Constructor. 62 | */ 63 | public DeserializationException(String message, Throwable cause, boolean serverSide) { 64 | this(message, cause); 65 | this.serverSide = serverSide; 66 | } 67 | 68 | /** 69 | * Getter method for property serverSide. 70 | * 71 | * @return property value of serverSide 72 | */ 73 | public boolean isServerSide() { 74 | return serverSide; 75 | } 76 | } -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/exception/RemotingException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.exception; 18 | 19 | /** 20 | * Exception for default remoting problems 21 | * 当远程调用出现问题时,抛出异常 22 | * @author jiangping 23 | * @version $Id: RemotingException.java, v 0.1 2015-9-21 PM 4:49:46 tao Exp $ 24 | */ 25 | public class RemotingException extends Exception { 26 | 27 | /** 28 | * 用作序列化 29 | */ 30 | /** For serialization */ 31 | private static final long serialVersionUID = 6183635628271812505L; 32 | 33 | /** 34 | * Constructor. 35 | */ 36 | public RemotingException() { 37 | 38 | } 39 | 40 | /** 41 | * Constructor. 42 | */ 43 | public RemotingException(String message) { 44 | super(message); 45 | } 46 | 47 | /** 48 | * Constructor. 49 | */ 50 | public RemotingException(String message, Throwable cause) { 51 | super(message, cause); 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/exception/SerializationException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.exception; 18 | 19 | /** 20 | * Exception when serialize failed 21 | * 当序列化失败时,抛出异常类 22 | * @author tsui 23 | * @version $Id: SerializationException.java, v 0.1 2017-07-26 16:12 tsui Exp $ 24 | */ 25 | public class SerializationException extends CodecException { 26 | /** 27 | * For serialization 28 | */ 29 | private static final long serialVersionUID = 5668965722686668067L; 30 | 31 | private boolean serverSide = false; 32 | 33 | /** 34 | * Constructor. 35 | */ 36 | public SerializationException() { 37 | 38 | } 39 | 40 | /** 41 | * Constructor. 42 | */ 43 | public SerializationException(String message) { 44 | super(message); 45 | } 46 | 47 | /** 48 | * Constructor. 49 | */ 50 | public SerializationException(String message, boolean serverSide) { 51 | this(message); 52 | this.serverSide = serverSide; 53 | } 54 | 55 | /** 56 | * Constructor. 57 | */ 58 | public SerializationException(String message, Throwable cause) { 59 | super(message, cause); 60 | } 61 | 62 | /** 63 | * Constructor. 64 | */ 65 | public SerializationException(String message, Throwable cause, boolean serverSide) { 66 | this(message, cause); 67 | this.serverSide = serverSide; 68 | } 69 | 70 | /** 71 | * Getter method for property serverSide. 72 | * 73 | * @return property value of serverSide 74 | */ 75 | public boolean isServerSide() { 76 | return serverSide; 77 | } 78 | } -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/rpc/HeartbeatAckCommand.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.rpc; 18 | 19 | import com.alipay.remoting.CommonCommandCode; 20 | import com.alipay.remoting.ResponseStatus; 21 | 22 | /** 23 | * Heartbeat ack. 24 | * 心跳回复 25 | * @author jiangping 26 | * @version $Id: HeartbeatAckCommand.java, v 0.1 2015-9-29 AM11:46:11 tao Exp $ 27 | */ 28 | public class HeartbeatAckCommand extends ResponseCommand { 29 | /** For serialization 序列化 */ 30 | private static final long serialVersionUID = 2584912495844320855L; 31 | 32 | /** 33 | * Constructor. 34 | */ 35 | public HeartbeatAckCommand() { 36 | super(CommonCommandCode.HEARTBEAT); 37 | this.setResponseStatus(ResponseStatus.SUCCESS); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/rpc/HeartbeatCommand.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.rpc; 18 | 19 | import com.alipay.remoting.CommonCommandCode; 20 | import com.alipay.remoting.util.IDGenerator; 21 | 22 | /** 23 | * Heart beat. 24 | * 心跳命令 25 | * @author jiangping 26 | * @version $Id: HeartbeatCommand.java, v 0.1 2015-9-10 AM9:46:36 tao Exp $ 27 | */ 28 | public class HeartbeatCommand extends RequestCommand { 29 | 30 | /** For serialization 序列化 */ 31 | private static final long serialVersionUID = 4949981019109517725L; 32 | 33 | /** 34 | * Construction. 35 | */ 36 | public HeartbeatCommand() { 37 | super(CommonCommandCode.HEARTBEAT); 38 | this.setId(IDGenerator.nextId()); 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/rpc/HeartbeatHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.rpc; 18 | 19 | import com.alipay.remoting.Connection; 20 | import com.alipay.remoting.Protocol; 21 | import com.alipay.remoting.ProtocolCode; 22 | import com.alipay.remoting.ProtocolManager; 23 | 24 | import io.netty.channel.ChannelDuplexHandler; 25 | import io.netty.channel.ChannelHandler.Sharable; 26 | import io.netty.channel.ChannelHandlerContext; 27 | import io.netty.handler.timeout.IdleStateEvent; 28 | 29 | /** 30 | * Heart beat triggerd. 31 | * 32 | * @author jiangping 33 | * @version $Id: SharableHandler.java, v 0.1 2015-12-14 PM3:16:00 tao Exp $ 34 | */ 35 | @Sharable 36 | public class HeartbeatHandler extends ChannelDuplexHandler { 37 | 38 | /** 39 | * 40 | * @see io.netty.channel.ChannelInboundHandlerAdapter#userEventTriggered(io.netty.channel.ChannelHandlerContext, java.lang.Object) 41 | */ 42 | @Override 43 | public void userEventTriggered(final ChannelHandlerContext ctx, Object evt) throws Exception { 44 | if (evt instanceof IdleStateEvent) { 45 | ProtocolCode protocolCode = ctx.channel().attr(Connection.PROTOCOL).get(); 46 | Protocol protocol = ProtocolManager.getProtocol(protocolCode); 47 | protocol.getHeartbeatTrigger().heartbeatTriggered(ctx); 48 | } else { 49 | super.userEventTriggered(ctx, evt); 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/rpc/RequestCommand.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.rpc; 18 | 19 | import com.alipay.remoting.CommandCode; 20 | 21 | /** 22 | * Command of request. 23 | * 请求命令 24 | * @author jiangping 25 | * @version $Id: RequestCommand.java, v 0.1 2015-9-10 AM10:27:59 tao Exp $ 26 | */ 27 | public abstract class RequestCommand extends RpcCommand { 28 | 29 | /** For serialization 序列化*/ 30 | private static final long serialVersionUID = -3457717009326601317L; 31 | /** timeout, -1 stands for no timeout 超时,-1 代表不超时*/ 32 | private int timeout = -1; 33 | 34 | public RequestCommand() { 35 | super(RpcCommandType.REQUEST); 36 | } 37 | 38 | public RequestCommand(CommandCode code) { 39 | super(RpcCommandType.REQUEST, code); 40 | } 41 | 42 | public RequestCommand(byte type, CommandCode code) { 43 | super(type, code); 44 | } 45 | 46 | public RequestCommand(byte version, byte type, CommandCode code) { 47 | super(version, type, code); 48 | } 49 | 50 | /** 51 | * Getter method for property timeout. 52 | * 获取timeout属性方法 53 | * @return property value of timeout 超时属性的值 54 | */ 55 | public int getTimeout() { 56 | return timeout; 57 | } 58 | 59 | /** 60 | * Setter method for property timeout. 61 | * 超时 属性的Setter方法 62 | * @param timeout value to be assigned to property timeout 分配给超时属性的值 63 | */ 64 | public void setTimeout(int timeout) { 65 | this.timeout = timeout; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/rpc/RpcCodec.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.rpc; 18 | 19 | import com.alipay.remoting.ProtocolCode; 20 | import com.alipay.remoting.codec.Codec; 21 | import com.alipay.remoting.codec.ProtocolCodeBasedEncoder; 22 | import com.alipay.remoting.rpc.protocol.RpcProtocolDecoder; 23 | import com.alipay.remoting.rpc.protocol.RpcProtocolManager; 24 | import com.alipay.remoting.rpc.protocol.RpcProtocolV2; 25 | 26 | import io.netty.channel.ChannelHandler; 27 | 28 | /** 29 | * @author muyun.cyt 30 | * @version 2018/6/26 下午3:51 31 | */ 32 | public class RpcCodec implements Codec { 33 | 34 | @Override 35 | public ChannelHandler newEncoder() { 36 | return new ProtocolCodeBasedEncoder(ProtocolCode.fromBytes(RpcProtocolV2.PROTOCOL_CODE)); 37 | } 38 | 39 | @Override 40 | public ChannelHandler newDecoder() { 41 | return new RpcProtocolDecoder(RpcProtocolManager.DEFAULT_PROTOCOL_CODE_LENGTH); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/rpc/RpcCommandType.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.rpc; 18 | 19 | /** 20 | * The type of command in the request/response model. 21 | * 请求/响应模型中的命令类型 22 | * @author jiangping 23 | * @version $Id: RpcCommandType.java, v 0.1 2015-9-25 AM10:58:16 tao Exp $ 24 | */ 25 | public class RpcCommandType { 26 | /** rpc response */ 27 | public static final byte RESPONSE = (byte) 0x00; 28 | /** rpc request */ 29 | public static final byte REQUEST = (byte) 0x01; 30 | /** rpc oneway request */ 31 | public static final byte REQUEST_ONEWAY = (byte) 0x02; 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/rpc/RpcConfigManager.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.rpc; 18 | 19 | import com.alipay.remoting.config.ConfigManager; 20 | 21 | /** 22 | * RPC framework config manager. 23 | * @author dennis 24 | */ 25 | public class RpcConfigManager { 26 | public static boolean dispatch_msg_list_in_default_executor() { 27 | return ConfigManager.getBool(RpcConfigs.DISPATCH_MSG_LIST_IN_DEFAULT_EXECUTOR, 28 | RpcConfigs.DISPATCH_MSG_LIST_IN_DEFAULT_EXECUTOR_DEFAULT); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/rpc/RpcConfigs.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.rpc; 18 | 19 | /** 20 | * Constants for rpc. 21 | * 22 | * @author jiangping 23 | * @version $Id: RpcConfigs.java, v 0.1 2015-10-10 PM3:03:47 tao Exp $ 24 | */ 25 | public class RpcConfigs { 26 | /** 27 | * Protocol key in url. 28 | */ 29 | public static final String URL_PROTOCOL = "_PROTOCOL"; 30 | 31 | /** 32 | * Version key in url. 33 | */ 34 | public static final String URL_VERSION = "_VERSION"; 35 | 36 | /** 37 | * Connection timeout key in url. 38 | */ 39 | public static final String CONNECT_TIMEOUT_KEY = "_CONNECTTIMEOUT"; 40 | 41 | /** 42 | * Connection number key of each address 43 | */ 44 | public static final String CONNECTION_NUM_KEY = "_CONNECTIONNUM"; 45 | 46 | /** 47 | * whether need to warm up connections 48 | */ 49 | public static final String CONNECTION_WARMUP_KEY = "_CONNECTIONWARMUP"; 50 | 51 | /** 52 | * Whether to dispatch message list in default executor. 53 | */ 54 | public static final String DISPATCH_MSG_LIST_IN_DEFAULT_EXECUTOR = "bolt.rpc.dispatch-msg-list-in-default-executor"; 55 | public static final String DISPATCH_MSG_LIST_IN_DEFAULT_EXECUTOR_DEFAULT = "true"; 56 | } -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/rpc/RpcConnectionEventHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.rpc; 18 | 19 | import com.alipay.remoting.Connection; 20 | import com.alipay.remoting.ConnectionEventHandler; 21 | import com.alipay.remoting.config.switches.GlobalSwitch; 22 | 23 | import io.netty.channel.ChannelHandlerContext; 24 | 25 | /** 26 | * ConnectionEventHandler for Rpc. 27 | * 28 | * @author jiangping 29 | * @version $Id: RpcConnectionEventHandler.java, v 0.1 2015-10-16 PM4:41:29 tao Exp $ 30 | */ 31 | public class RpcConnectionEventHandler extends ConnectionEventHandler { 32 | 33 | public RpcConnectionEventHandler() { 34 | super(); 35 | } 36 | 37 | public RpcConnectionEventHandler(GlobalSwitch globalSwitch) { 38 | super(globalSwitch); 39 | } 40 | 41 | /** 42 | * @see com.alipay.remoting.ConnectionEventHandler#channelInactive(io.netty.channel.ChannelHandlerContext) 43 | */ 44 | @Override 45 | public void channelInactive(ChannelHandlerContext ctx) throws Exception { 46 | Connection conn = ctx.channel().attr(Connection.CONNECTION).get(); 47 | if (conn != null) { 48 | this.getConnectionManager().remove(conn); 49 | } 50 | super.channelInactive(ctx); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/rpc/RpcConnectionFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.rpc; 18 | 19 | import java.util.concurrent.ConcurrentHashMap; 20 | 21 | import com.alipay.remoting.config.ConfigurableInstance; 22 | import com.alipay.remoting.connection.DefaultConnectionFactory; 23 | import com.alipay.remoting.rpc.protocol.UserProcessor; 24 | 25 | /** 26 | * Default RPC connection factory impl. 27 | * 28 | * @author chengyi (mark.lx@antfin.com) 2018-06-20 15:32 29 | */ 30 | public class RpcConnectionFactory extends DefaultConnectionFactory { 31 | 32 | public RpcConnectionFactory(ConcurrentHashMap> userProcessors, 33 | ConfigurableInstance configInstance) { 34 | super(new RpcCodec(), new HeartbeatHandler(), new RpcHandler(userProcessors), 35 | configInstance); 36 | } 37 | } -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/rpc/RpcHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.rpc; 18 | 19 | import java.util.concurrent.ConcurrentHashMap; 20 | 21 | import com.alipay.remoting.Connection; 22 | import com.alipay.remoting.InvokeContext; 23 | import com.alipay.remoting.Protocol; 24 | import com.alipay.remoting.ProtocolCode; 25 | import com.alipay.remoting.ProtocolManager; 26 | import com.alipay.remoting.RemotingContext; 27 | import com.alipay.remoting.rpc.protocol.UserProcessor; 28 | 29 | import io.netty.channel.ChannelHandler; 30 | import io.netty.channel.ChannelHandlerContext; 31 | import io.netty.channel.ChannelInboundHandlerAdapter; 32 | 33 | /** 34 | * Dispatch messages to corresponding protocol. 35 | * 36 | * @author jiangping 37 | * @version $Id: RpcHandler.java, v 0.1 2015-12-14 PM4:01:37 tao Exp $ 38 | */ 39 | @ChannelHandler.Sharable 40 | public class RpcHandler extends ChannelInboundHandlerAdapter { 41 | private boolean serverSide; 42 | 43 | private ConcurrentHashMap> userProcessors; 44 | 45 | public RpcHandler() { 46 | serverSide = false; 47 | } 48 | 49 | public RpcHandler(ConcurrentHashMap> userProcessors) { 50 | serverSide = false; 51 | this.userProcessors = userProcessors; 52 | } 53 | 54 | public RpcHandler(boolean serverSide, ConcurrentHashMap> userProcessors) { 55 | this.serverSide = serverSide; 56 | this.userProcessors = userProcessors; 57 | } 58 | 59 | @Override 60 | public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { 61 | ProtocolCode protocolCode = ctx.channel().attr(Connection.PROTOCOL).get(); 62 | Protocol protocol = ProtocolManager.getProtocol(protocolCode); 63 | protocol.getCommandHandler().handleCommand( 64 | new RemotingContext(ctx, new InvokeContext(), serverSide, userProcessors), msg); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/rpc/RpcResponseFuture.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.rpc; 18 | 19 | import com.alipay.remoting.InvokeFuture; 20 | import com.alipay.remoting.exception.RemotingException; 21 | import com.alipay.remoting.rpc.exception.InvokeTimeoutException; 22 | 23 | /** 24 | * The future for response. 25 | * 26 | * @author jiangping 27 | * @version $Id: ResponseFuture.java, v 0.1 2015-10-3 PM5:07:05 tao Exp $ 28 | */ 29 | public class RpcResponseFuture { 30 | /** rpc server address */ 31 | private String addr; 32 | 33 | /** rpc server port */ 34 | private InvokeFuture future; 35 | 36 | /** 37 | * Constructor 38 | */ 39 | public RpcResponseFuture(String addr, InvokeFuture future) { 40 | this.addr = addr; 41 | this.future = future; 42 | } 43 | 44 | /** 45 | * Whether the future is done. 46 | */ 47 | public boolean isDone() { 48 | return this.future.isDone(); 49 | } 50 | 51 | /** 52 | * get result with timeout specified 53 | * 54 | * if request done, resolve normal responseObject 55 | * if request not done, throws InvokeTimeoutException 56 | */ 57 | public Object get(int timeoutMillis) throws InvokeTimeoutException, RemotingException, 58 | InterruptedException { 59 | this.future.waitResponse(timeoutMillis); 60 | if (!isDone()) { 61 | throw new InvokeTimeoutException("Future get result timeout!"); 62 | } 63 | ResponseCommand responseCommand = (ResponseCommand) this.future.waitResponse(); 64 | responseCommand.setInvokeContext(this.future.getInvokeContext()); 65 | return RpcResponseResolver.resolveResponseObject(responseCommand, addr); 66 | } 67 | 68 | public Object get() throws RemotingException, InterruptedException { 69 | ResponseCommand responseCommand = (ResponseCommand) this.future.waitResponse(); 70 | responseCommand.setInvokeContext(this.future.getInvokeContext()); 71 | return RpcResponseResolver.resolveResponseObject(responseCommand, addr); 72 | } 73 | 74 | } 75 | -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/rpc/RpcTaskScanner.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.rpc; 18 | 19 | import java.util.LinkedList; 20 | import java.util.List; 21 | import java.util.concurrent.ScheduledExecutorService; 22 | import java.util.concurrent.ScheduledThreadPoolExecutor; 23 | import java.util.concurrent.TimeUnit; 24 | 25 | import org.slf4j.Logger; 26 | 27 | import com.alipay.remoting.NamedThreadFactory; 28 | import com.alipay.remoting.Scannable; 29 | import com.alipay.remoting.log.BoltLoggerFactory; 30 | 31 | /** 32 | * Scanner is used to do scan task. 33 | * 34 | * @author jiangping 35 | * @version $Id: RpcTaskScanner.java, v 0.1 Mar 4, 2016 3:30:52 PM tao Exp $ 36 | */ 37 | public class RpcTaskScanner { 38 | private static final Logger logger = BoltLoggerFactory.getLogger("RpcRemoting"); 39 | 40 | private ScheduledExecutorService scheduledService = new ScheduledThreadPoolExecutor(1, 41 | new NamedThreadFactory( 42 | "RpcTaskScannerThread", true)); 43 | 44 | private List scanList = new LinkedList(); 45 | 46 | /** 47 | * Start! 48 | */ 49 | public void start() { 50 | scheduledService.scheduleWithFixedDelay(new Runnable() { 51 | 52 | @Override 53 | public void run() { 54 | for (Scannable scanned : scanList) { 55 | try { 56 | scanned.scan(); 57 | } catch (Throwable t) { 58 | logger.error("Exception caught when scannings.", t); 59 | } 60 | } 61 | } 62 | 63 | }, 10000, 10000, TimeUnit.MILLISECONDS); 64 | } 65 | 66 | /** 67 | * Add scan target. 68 | * 69 | * @param target 70 | */ 71 | public void add(Scannable target) { 72 | scanList.add(target); 73 | } 74 | 75 | /** 76 | * Shutdown the scheduled service. 77 | */ 78 | public void shutdown() { 79 | scheduledService.shutdown(); 80 | } 81 | 82 | } 83 | -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/rpc/exception/InvokeException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.rpc.exception; 18 | 19 | import com.alipay.remoting.exception.RemotingException; 20 | 21 | /** 22 | * Exception when invoke failed 23 | * 调用失败异常类 24 | * @author jiangping 25 | * @version $Id: InvokeException.java, v 0.1 2015-10-5 PM8:19:36 tao Exp $ 26 | */ 27 | public class InvokeException extends RemotingException { 28 | /** For serialization */ 29 | private static final long serialVersionUID = -3974514863386363570L; 30 | 31 | /** 32 | * Default constructor. 33 | */ 34 | public InvokeException() { 35 | } 36 | 37 | public InvokeException(String msg) { 38 | super(msg); 39 | } 40 | 41 | public InvokeException(String msg, Throwable cause) { 42 | super(msg, cause); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/rpc/exception/InvokeSendFailedException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.rpc.exception; 18 | 19 | import com.alipay.remoting.exception.RemotingException; 20 | 21 | /** 22 | * Exception when invoke send failed 23 | * 当调用发送失败,抛出异常类 24 | * @author jiangping 25 | * @version $Id: InvokeSendFailedException.java, v 0.1 2015-10-3 PM 12:32:45 tao Exp $ 26 | */ 27 | public class InvokeSendFailedException extends RemotingException { 28 | 29 | /** For serialization */ 30 | private static final long serialVersionUID = 4832257777758730796L; 31 | 32 | /** 33 | * Default constructor. 34 | */ 35 | public InvokeSendFailedException() { 36 | } 37 | 38 | public InvokeSendFailedException(String msg) { 39 | super(msg); 40 | } 41 | 42 | public InvokeSendFailedException(String msg, Throwable cause) { 43 | super(msg, cause); 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/rpc/exception/InvokeServerBusyException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.rpc.exception; 18 | 19 | import com.alipay.remoting.exception.RemotingException; 20 | 21 | /** 22 | * Exception when thread pool busy of process server 23 | * 当服务端处理器线程池忙碌时,抛出此类 24 | * @author jiangping 25 | * @version $Id: InvokeServerBusyException.java, v 0.1 2015-10-9 AM11:16:10 tao Exp $ 26 | */ 27 | public class InvokeServerBusyException extends RemotingException { 28 | /** For serialization */ 29 | private static final long serialVersionUID = 4480283862377034355L; 30 | 31 | /** 32 | * Default constructor. 33 | */ 34 | public InvokeServerBusyException() { 35 | } 36 | 37 | public InvokeServerBusyException(String msg) { 38 | super(msg); 39 | } 40 | 41 | public InvokeServerBusyException(String msg, Throwable cause) { 42 | super(msg, cause); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/rpc/exception/InvokeServerException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.rpc.exception; 18 | 19 | import com.alipay.remoting.exception.RemotingException; 20 | 21 | /** 22 | * Server exception caught when invoking 23 | * 当服务端调用出错,抛出异常类 24 | * @author jiangping 25 | * @version $Id: InvokeServerException.java, v 0.1 2015-10-9 AM11:16:10 tao Exp $ 26 | */ 27 | public class InvokeServerException extends RemotingException { 28 | /** For serialization */ 29 | private static final long serialVersionUID = 4480283862377034355L; 30 | 31 | /** 32 | * Default constructor. 33 | */ 34 | public InvokeServerException() { 35 | } 36 | 37 | public InvokeServerException(String msg) { 38 | super(msg); 39 | } 40 | 41 | public InvokeServerException(String msg, Throwable cause) { 42 | super(msg, cause); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/rpc/exception/InvokeTimeoutException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.rpc.exception; 18 | 19 | import com.alipay.remoting.exception.RemotingException; 20 | 21 | /** 22 | * Exception when invoke timeout 23 | * 当调用超时,异常类 24 | * @author jiangping 25 | * @version $Id: InvokeTimeoutException.java, v 0.1 2015-9-28 PM3:35:53 tao Exp $ 26 | */ 27 | public class InvokeTimeoutException extends RemotingException { 28 | 29 | /** For serialization */ 30 | private static final long serialVersionUID = -7772633244795043476L; 31 | 32 | /** 33 | * Default constructor. 34 | */ 35 | public InvokeTimeoutException() { 36 | } 37 | 38 | /** 39 | * Constructor. 40 | * 41 | * @param msg the detail message 42 | */ 43 | public InvokeTimeoutException(String msg) { 44 | super(msg); 45 | } 46 | 47 | /** 48 | * Constructor. 49 | * 50 | * @param msg the detail message 51 | * @param cause the cause 52 | */ 53 | public InvokeTimeoutException(String msg, Throwable cause) { 54 | super(msg, cause); 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/rpc/exception/RpcServerException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.rpc.exception; 18 | 19 | import com.alipay.remoting.exception.RemotingException; 20 | 21 | /** 22 | * Rpc server exception when processing request 23 | * 当RPC服务处理请求出错异常类 24 | * @author jiangping 25 | * @version $Id: InvokeServerException.java, v 0.1 2015-10-9 PM11:16:10 tao Exp $ 26 | */ 27 | public class RpcServerException extends RemotingException { 28 | /** For serialization */ 29 | private static final long serialVersionUID = 4480283862377034355L; 30 | 31 | /** 32 | * Default constructor. 33 | */ 34 | public RpcServerException() { 35 | } 36 | 37 | public RpcServerException(String msg) { 38 | super(msg); 39 | } 40 | 41 | public RpcServerException(String msg, Throwable cause) { 42 | super(msg, cause); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/rpc/protocol/AbstractMultiInterestUserProcessor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.rpc.protocol; 18 | 19 | /** 20 | * Implements common function and provide default value. 21 | * more details in {@link com.alipay.remoting.rpc.protocol.AbstractUserProcessor} 22 | * @author muyun.cyt (muyun.cyt@antfin.com) 2018/7/5 11:17 AM 23 | */ 24 | public abstract class AbstractMultiInterestUserProcessor extends AbstractUserProcessor 25 | implements 26 | MultiInterestUserProcessor { 27 | 28 | /** 29 | * do not need to implement this method because of the multiple interests 30 | * @see com.alipay.remoting.rpc.protocol.UserProcessor#interest() 31 | * */ 32 | @Override 33 | public String interest() { 34 | return null; 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/rpc/protocol/AbstractUserProcessor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.rpc.protocol; 18 | 19 | import java.util.concurrent.Executor; 20 | 21 | import com.alipay.remoting.BizContext; 22 | import com.alipay.remoting.DefaultBizContext; 23 | import com.alipay.remoting.RemotingContext; 24 | 25 | /** 26 | * Implements common function and provide default value. 27 | * 28 | * @author xiaomin.cxm 29 | * @version $Id: AbstractUserProcessor.java, v 0.1 May 19, 2016 3:38:22 PM xiaomin.cxm Exp $ 30 | */ 31 | public abstract class AbstractUserProcessor implements UserProcessor { 32 | 33 | /** executor selector, default null unless provide one using its setter method */ 34 | protected ExecutorSelector executorSelector; 35 | 36 | /** 37 | * Provide a default - {@link DefaultBizContext} implementation of {@link BizContext}. 38 | * 39 | * @see com.alipay.remoting.rpc.protocol.UserProcessor#preHandleRequest(com.alipay.remoting.RemotingContext, java.lang.Object) 40 | */ 41 | @Override 42 | public BizContext preHandleRequest(RemotingContext remotingCtx, T request) { 43 | return new DefaultBizContext(remotingCtx); 44 | } 45 | 46 | /** 47 | * By default return null. 48 | * 49 | * @see UserProcessor#getExecutor() 50 | */ 51 | @Override 52 | public Executor getExecutor() { 53 | return null; 54 | } 55 | 56 | /** 57 | * @see UserProcessor#getExecutorSelector() 58 | */ 59 | @Override 60 | public ExecutorSelector getExecutorSelector() { 61 | return this.executorSelector; 62 | } 63 | 64 | /** 65 | * @see UserProcessor#setExecutorSelector(ExecutorSelector) 66 | */ 67 | @Override 68 | public void setExecutorSelector(ExecutorSelector executorSelector) { 69 | this.executorSelector = executorSelector; 70 | } 71 | 72 | /** 73 | * By default, return false, means not deserialize and process biz logic in io thread 74 | * 75 | * @see UserProcessor#processInIOThread() 76 | */ 77 | @Override 78 | public boolean processInIOThread() { 79 | return false; 80 | } 81 | 82 | /** 83 | * By default, return true, means discard requests which timeout already. 84 | */ 85 | @Override 86 | public boolean timeoutDiscard() { 87 | return true; 88 | } 89 | } -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/rpc/protocol/AsynMultiInterestUserProcessor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.rpc.protocol; 18 | 19 | import java.util.List; 20 | 21 | import com.alipay.remoting.AsyncContext; 22 | import com.alipay.remoting.BizContext; 23 | 24 | /** 25 | * Extends this to process user defined request in ASYNC way.
26 | * If you want process reqeuest in SYNC way, please extends {@link SyncMutiInterestUserProcessor}. 27 | * @author muyun.cyt (muyun.cyt@antfin.com) 2018/7/5 11:19 AM 28 | */ 29 | public abstract class AsynMultiInterestUserProcessor extends 30 | AbstractMultiInterestUserProcessor { 31 | /** 32 | * unsupported here! 33 | * 34 | * @see com.alipay.remoting.rpc.protocol.UserProcessor#handleRequest(com.alipay.remoting.BizContext, java.lang.Object) 35 | */ 36 | @Override 37 | public Object handleRequest(BizContext bizCtx, T request) throws Exception { 38 | throw new UnsupportedOperationException( 39 | "SYNC handle request is unsupported in AsynMultiInterestUserProcessor!"); 40 | } 41 | 42 | /** 43 | * @see com.alipay.remoting.rpc.protocol.UserProcessor#handleRequest(com.alipay.remoting.BizContext, com.alipay.remoting.AsyncContext, java.lang.Object) 44 | */ 45 | @Override 46 | public abstract void handleRequest(BizContext bizCtx, AsyncContext asyncCtx, T request); 47 | 48 | /** 49 | * @see com.alipay.remoting.rpc.protocol.MultiInterestUserProcessor#multiInterest() 50 | */ 51 | @Override 52 | public abstract List multiInterest(); 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/rpc/protocol/AsyncUserProcessor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.rpc.protocol; 18 | 19 | import com.alipay.remoting.AsyncContext; 20 | import com.alipay.remoting.BizContext; 21 | 22 | /** 23 | * Extends this to process user defined request in ASYNC way.
24 | * If you want process reqeuest in SYNC way, please extends {@link SyncUserProcessor}. 25 | * 26 | * @author xiaomin.cxm 27 | * @version $Id: AsyncUserProcessor.java, v 0.1 May 16, 2016 8:18:03 PM xiaomin.cxm Exp $ 28 | */ 29 | public abstract class AsyncUserProcessor extends AbstractUserProcessor { 30 | /** 31 | * unsupported here! 32 | * 33 | * @see com.alipay.remoting.rpc.protocol.UserProcessor#handleRequest(com.alipay.remoting.BizContext, java.lang.Object) 34 | */ 35 | @Override 36 | public Object handleRequest(BizContext bizCtx, T request) throws Exception { 37 | throw new UnsupportedOperationException( 38 | "SYNC handle request is unsupported in AsyncUserProcessor!"); 39 | } 40 | 41 | /** 42 | * @see com.alipay.remoting.rpc.protocol.UserProcessor#handleRequest(com.alipay.remoting.BizContext, com.alipay.remoting.AsyncContext, java.lang.Object) 43 | */ 44 | @Override 45 | public abstract void handleRequest(BizContext bizCtx, AsyncContext asyncCtx, T request); 46 | 47 | /** 48 | * @see com.alipay.remoting.rpc.protocol.UserProcessor#interest() 49 | */ 50 | @Override 51 | public abstract String interest(); 52 | } -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/rpc/protocol/MultiInterestUserProcessor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.rpc.protocol; 18 | 19 | import java.util.List; 20 | 21 | /** 22 | * Support multi-interests feature based on UserProcessor 23 | * 24 | * The implementations of this interface don't need to implement the {@link com.alipay.remoting.rpc.protocol.UserProcessor#interest() interest()} method; 25 | * @author muyun.cyt (muyun.cyt@antfin.com) 2018/7/5 11:19 AM 26 | */ 27 | public interface MultiInterestUserProcessor extends UserProcessor { 28 | 29 | /** 30 | * A list of the class names of user request. 31 | * Use String type to avoid classloader problem. 32 | */ 33 | List multiInterest(); 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/rpc/protocol/RpcAsyncContext.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.rpc.protocol; 18 | 19 | import java.util.concurrent.atomic.AtomicBoolean; 20 | 21 | import com.alipay.remoting.AsyncContext; 22 | import com.alipay.remoting.RemotingContext; 23 | 24 | /** 25 | * Async biz context of Rpc. 26 | * 27 | * @author xiaomin.cxm 28 | * @version $Id: RpcAsyncContext.java, v 0.1 May 16, 2016 8:23:07 PM xiaomin.cxm Exp $ 29 | */ 30 | public class RpcAsyncContext implements AsyncContext { 31 | /** remoting context */ 32 | private RemotingContext ctx; 33 | 34 | /** rpc request command */ 35 | private RpcRequestCommand cmd; 36 | 37 | private RpcRequestProcessor processor; 38 | 39 | /** is response sent already */ 40 | private AtomicBoolean isResponseSentAlready = new AtomicBoolean(); 41 | 42 | /** 43 | * Default constructor. 44 | * 45 | * @param ctx remoting context 46 | * @param cmd rpc request command 47 | * @param processor rpc request processor 48 | */ 49 | public RpcAsyncContext(final RemotingContext ctx, final RpcRequestCommand cmd, 50 | final RpcRequestProcessor processor) { 51 | this.ctx = ctx; 52 | this.cmd = cmd; 53 | this.processor = processor; 54 | } 55 | 56 | /** 57 | * @see com.alipay.remoting.AsyncContext#sendResponse(java.lang.Object) 58 | */ 59 | @Override 60 | public void sendResponse(Object responseObject) { 61 | if (isResponseSentAlready.compareAndSet(false, true)) { 62 | processor.sendResponseIfNecessary(this.ctx, cmd.getType(), processor 63 | .getCommandFactory().createResponse(responseObject, this.cmd)); 64 | } else { 65 | throw new IllegalStateException("Should not send rpc response repeatedly!"); 66 | } 67 | } 68 | } -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/rpc/protocol/RpcCommandCode.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.rpc.protocol; 18 | 19 | import com.alipay.remoting.CommandCode; 20 | 21 | /** 22 | * Command code for rpc remoting command. 23 | * 远程命令的命令代码 24 | * @author jiangping 25 | * @version $Id: RpcCommandCode.java, v 0.1 2015-9-21 PM5:05:59 tao Exp $ 26 | */ 27 | public enum RpcCommandCode implements CommandCode { 28 | /** 29 | * (short) 1 代表RPC请求命令 30 | * (short) 2 代表RPC回复命令 31 | */ 32 | 33 | RPC_REQUEST((short) 1), RPC_RESPONSE((short) 2); 34 | 35 | private short value; 36 | 37 | RpcCommandCode(short value) { 38 | this.value = value; 39 | } 40 | 41 | @Override 42 | public short value() { 43 | return this.value; 44 | } 45 | 46 | public static RpcCommandCode valueOf(short value) { 47 | switch (value) { 48 | case 1: 49 | return RPC_REQUEST; 50 | case 2: 51 | return RPC_RESPONSE; 52 | } 53 | throw new IllegalArgumentException("Unknown Rpc command code value: " + value); 54 | } 55 | 56 | } -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/rpc/protocol/RpcDeserializeLevel.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.rpc.protocol; 18 | 19 | /** 20 | * Rpc deserialize level. 21 | * 22 | * @author tsui 23 | * @version $Id: RpcDeserializeLevel.java, v 0.1 2017-04-24 15:12 tsui Exp $ 24 | */ 25 | public class RpcDeserializeLevel { 26 | /** deserialize clazz, header, contents all three parts of rpc command */ 27 | public final static int DESERIALIZE_ALL = 0x02; 28 | /** deserialize both header and clazz parts of rpc command */ 29 | public final static int DESERIALIZE_HEADER = 0x01; 30 | /** deserialize only the clazz part of rpc command */ 31 | public final static int DESERIALIZE_CLAZZ = 0x00; 32 | 33 | /** 34 | * Convert to String. 35 | */ 36 | public static String valueOf(int value) { 37 | switch (value) { 38 | case 0x00: 39 | return "DESERIALIZE_CLAZZ"; 40 | case 0x01: 41 | return "DESERIALIZE_HEADER"; 42 | case 0x02: 43 | return "DESERIALIZE_ALL"; 44 | } 45 | throw new IllegalArgumentException("Unknown deserialize level value ," + value); 46 | } 47 | } -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/rpc/protocol/RpcProtocolDecoder.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.rpc.protocol; 18 | 19 | import com.alipay.remoting.codec.ProtocolCodeBasedDecoder; 20 | 21 | import io.netty.buffer.ByteBuf; 22 | 23 | /** 24 | * Rpc protocol decoder. 25 | * 26 | * @author tsui 27 | * @version $Id: RpcProtocolDecoder.java, v 0.1 2018-03-27 19:28 tsui Exp $ 28 | */ 29 | public class RpcProtocolDecoder extends ProtocolCodeBasedDecoder { 30 | public static final int MIN_PROTOCOL_CODE_WITH_VERSION = 2; 31 | 32 | public RpcProtocolDecoder(int protocolCodeLength) { 33 | super(protocolCodeLength); 34 | } 35 | 36 | @Override 37 | protected byte decodeProtocolVersion(ByteBuf in) { 38 | in.resetReaderIndex(); 39 | if (in.readableBytes() >= protocolCodeLength + DEFAULT_PROTOCOL_VERSION_LENGTH) { 40 | byte rpcProtocolCodeByte = in.readByte(); 41 | if (rpcProtocolCodeByte >= MIN_PROTOCOL_CODE_WITH_VERSION) { 42 | return in.readByte(); 43 | } 44 | } 45 | return DEFAULT_ILLEGAL_PROTOCOL_VERSION_LENGTH; 46 | } 47 | } -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/rpc/protocol/RpcProtocolManager.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.rpc.protocol; 18 | 19 | import com.alipay.remoting.ProtocolManager; 20 | 21 | /** 22 | * Protocol manager. 23 | * 24 | * @author tsui 25 | * @version $Id: RpcProtocols.java, v 0.1 2018-03-27 19:42 tsui Exp $ 26 | */ 27 | public class RpcProtocolManager { 28 | public static final int DEFAULT_PROTOCOL_CODE_LENGTH = 1; 29 | 30 | public static void initProtocols() { 31 | ProtocolManager.registerProtocol(new RpcProtocol(), RpcProtocol.PROTOCOL_CODE); 32 | ProtocolManager.registerProtocol(new RpcProtocolV2(), RpcProtocolV2.PROTOCOL_CODE); 33 | } 34 | } -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/rpc/protocol/SyncMutiInterestUserProcessor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.rpc.protocol; 18 | 19 | import java.util.List; 20 | 21 | import com.alipay.remoting.AsyncContext; 22 | import com.alipay.remoting.BizContext; 23 | 24 | /** 25 | * Extends this to process user defined request in SYNC way.
26 | * If you want process reqeuest in ASYNC way, please extends {@link AsynMultiInterestUserProcessor}. 27 | * 28 | * @author muyun.cyt (muyun.cyt@antfin.com) 2018/7/5 11:19 AM 29 | */ 30 | public abstract class SyncMutiInterestUserProcessor extends 31 | AbstractMultiInterestUserProcessor { 32 | 33 | /** 34 | * @see com.alipay.remoting.rpc.protocol.UserProcessor#handleRequest(com.alipay.remoting.BizContext, java.lang.Object) 35 | */ 36 | @Override 37 | public abstract Object handleRequest(BizContext bizCtx, T request) throws Exception; 38 | 39 | /** 40 | * unsupported here! 41 | * 42 | * @see com.alipay.remoting.rpc.protocol.UserProcessor#handleRequest(com.alipay.remoting.BizContext, com.alipay.remoting.AsyncContext, java.lang.Object) 43 | */ 44 | @Override 45 | public void handleRequest(BizContext bizCtx, AsyncContext asyncCtx, T request) { 46 | throw new UnsupportedOperationException( 47 | "ASYNC handle request is unsupported in SyncMutiInterestUserProcessor!"); 48 | } 49 | 50 | /** 51 | * @see com.alipay.remoting.rpc.protocol.MultiInterestUserProcessor#multiInterest() 52 | */ 53 | @Override 54 | public abstract List multiInterest(); 55 | 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/rpc/protocol/SyncUserProcessor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.rpc.protocol; 18 | 19 | import com.alipay.remoting.AsyncContext; 20 | import com.alipay.remoting.BizContext; 21 | 22 | /** 23 | * Extends this to process user defined request in SYNC way.
24 | * If you want process reqeuest in ASYNC way, please extends {@link AsyncUserProcessor}. 25 | * 26 | * @author xiaomin.cxm 27 | * @version $Id: SyncUserProcessor.java, v 0.1 May 19, 2016 2:47:21 PM xiaomin.cxm Exp $ 28 | */ 29 | public abstract class SyncUserProcessor extends AbstractUserProcessor { 30 | /** 31 | * @see com.alipay.remoting.rpc.protocol.UserProcessor#handleRequest(com.alipay.remoting.BizContext, java.lang.Object) 32 | */ 33 | @Override 34 | public abstract Object handleRequest(BizContext bizCtx, T request) throws Exception; 35 | 36 | /** 37 | * unsupported here! 38 | * 39 | * @see com.alipay.remoting.rpc.protocol.UserProcessor#handleRequest(com.alipay.remoting.BizContext, com.alipay.remoting.AsyncContext, java.lang.Object) 40 | */ 41 | @Override 42 | public void handleRequest(BizContext bizCtx, AsyncContext asyncCtx, T request) { 43 | throw new UnsupportedOperationException( 44 | "ASYNC handle request is unsupported in SyncUserProcessor!"); 45 | } 46 | 47 | /** 48 | * @see com.alipay.remoting.rpc.protocol.UserProcessor#interest() 49 | */ 50 | @Override 51 | public abstract String interest(); 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/serialization/Serializer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.serialization; 18 | 19 | import com.alipay.remoting.exception.CodecException; 20 | 21 | /** 22 | * Serializer for serialize and deserialize. 23 | * 用于序列化和反序列化的程序接口类。 24 | * 25 | * @author jiangping 26 | * @version $Id: Serializer.java, v 0.1 2015-10-4 PM9:37:57 tao Exp $ 27 | */ 28 | public interface Serializer { 29 | /** 30 | * Encode object into bytes. 31 | * 将对象编码为字节。 32 | * @param obj target object 33 | * @return serialized result 34 | */ 35 | byte[] serialize(final Object obj) throws CodecException; 36 | 37 | /** 38 | * Decode bytes into Object. 39 | * 将字节解码为Object。 40 | * @param data serialized data 41 | * @param classOfT class of original data 42 | */ 43 | T deserialize(final byte[] data, String classOfT) throws CodecException; 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/serialization/SerializerManager.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.serialization; 18 | 19 | /** 20 | * Manage all serializers. 21 | * 管理所有序列化程序 22 | * 23 | * Notice: Serializer is different with Codec. 24 | * Serializer is mainly used to deserialize bytes to object, or serialize object to bytes. We can use hessian, json, protocol buff etc. 25 | * Codec mainly used to encode bytes or decode bytes according to the protocol format. We can use {@link com.alipay.remoting.codec.ProtocolCodeBasedEncoder} or {@link io.netty.handler.codec.LengthFieldBasedFrameDecoder} etc. 26 | * 27 | * @author jiangping 28 | * @version $Id: SerializerManager.java, v 0.1 2015-9-28 PM3:55:59 tao Exp $ 29 | */ 30 | public class SerializerManager { 31 | 32 | private static Serializer[] serializers = new Serializer[5]; 33 | /** 34 | * 默认序列化工具 Hessian2 35 | */ 36 | public static final byte Hessian2 = 1; 37 | //public static final byte Json = 2; 38 | 39 | static { 40 | addSerializer(Hessian2, new HessianSerializer()); 41 | } 42 | 43 | public static Serializer getSerializer(int idx) { 44 | return serializers[idx]; 45 | } 46 | 47 | public static void addSerializer(int idx, Serializer serializer) { 48 | if (serializers.length <= idx) { 49 | Serializer[] newSerializers = new Serializer[idx + 5]; 50 | System.arraycopy(serializers, 0, newSerializers, 0, serializers.length); 51 | serializers = newSerializers; 52 | } 53 | serializers[idx] = serializer; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/util/ConcurrentHashSet.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.util; 18 | 19 | import java.util.AbstractSet; 20 | import java.util.Iterator; 21 | import java.util.concurrent.ConcurrentHashMap; 22 | 23 | /** 24 | * Concurrent hash set. 25 | * 26 | * @author yunliang.shi 27 | * @version $Id: ConcurrentHashSet.java, v 0.1 Mar 11, 2016 3:40:41 PM yunliang.shi Exp $ 28 | */ 29 | public class ConcurrentHashSet extends AbstractSet { 30 | private ConcurrentHashMap map; 31 | 32 | /** 33 | * constructor 34 | */ 35 | public ConcurrentHashSet() { 36 | super(); 37 | map = new ConcurrentHashMap(); 38 | } 39 | 40 | /** 41 | * return the size of the map 42 | * @see java.util.AbstractCollection#size() 43 | */ 44 | @Override 45 | public int size() { 46 | return map.size(); 47 | } 48 | 49 | /** 50 | * 51 | * @see java.util.AbstractCollection#contains(java.lang.Object) 52 | */ 53 | @Override 54 | public boolean contains(Object o) { 55 | return map.containsKey(o); 56 | } 57 | 58 | /** 59 | * 60 | * @see java.util.AbstractCollection#iterator() 61 | */ 62 | @Override 63 | public Iterator iterator() { 64 | return map.keySet().iterator(); 65 | } 66 | 67 | /** 68 | * add an obj to set, if exist, return false, else return true 69 | * @see java.util.AbstractCollection#add(java.lang.Object) 70 | */ 71 | @Override 72 | public boolean add(E o) { 73 | return map.putIfAbsent(o, Boolean.TRUE) == null; 74 | } 75 | 76 | /** 77 | * 78 | * @see java.util.AbstractCollection#remove(java.lang.Object) 79 | */ 80 | @Override 81 | public boolean remove(Object o) { 82 | return map.remove(o) != null; 83 | } 84 | 85 | /** 86 | * clear the set 87 | * @see java.util.AbstractCollection#clear() 88 | */ 89 | @Override 90 | public void clear() { 91 | map.clear(); 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/util/ConnectionUtil.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.util; 18 | 19 | import com.alipay.remoting.Connection; 20 | import com.alipay.remoting.InvokeFuture; 21 | 22 | import io.netty.channel.Channel; 23 | import io.netty.util.Attribute; 24 | 25 | /** 26 | * connection util 27 | * 28 | * @author yunliang.shi 29 | * @version $Id: ConnectionUtil.java, v 0.1 Mar 10, 2016 11:36:40 AM yunliang.shi Exp $ 30 | */ 31 | public class ConnectionUtil { 32 | 33 | public static Connection getConnectionFromChannel(Channel channel) { 34 | if (channel == null) { 35 | return null; 36 | } 37 | 38 | Attribute connAttr = channel.attr(Connection.CONNECTION); 39 | if (connAttr != null) { 40 | Connection connection = connAttr.get(); 41 | return connection; 42 | } 43 | return null; 44 | } 45 | 46 | public static void addIdPoolKeyMapping(Integer id, String group, Channel channel) { 47 | Connection connection = getConnectionFromChannel(channel); 48 | if (connection != null) { 49 | connection.addIdPoolKeyMapping(id, group); 50 | } 51 | } 52 | 53 | public static String removeIdPoolKeyMapping(Integer id, Channel channel) { 54 | Connection connection = getConnectionFromChannel(channel); 55 | if (connection != null) { 56 | return connection.removeIdPoolKeyMapping(id); 57 | } 58 | 59 | return null; 60 | } 61 | 62 | public static void addIdGroupCallbackMapping(Integer id, InvokeFuture callback, Channel channel) { 63 | Connection connection = getConnectionFromChannel(channel); 64 | if (connection != null) { 65 | connection.addInvokeFuture(callback); 66 | } 67 | } 68 | 69 | public static InvokeFuture removeIdGroupCallbackMapping(Integer id, Channel channel) { 70 | Connection connection = getConnectionFromChannel(channel); 71 | if (connection != null) { 72 | return connection.removeInvokeFuture(id); 73 | } 74 | return null; 75 | } 76 | 77 | public static InvokeFuture getGroupRequestCallBack(Integer id, Channel channel) { 78 | Connection connection = getConnectionFromChannel(channel); 79 | if (connection != null) { 80 | return connection.getInvokeFuture(id); 81 | } 82 | 83 | return null; 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/util/CrcUtil.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.util; 18 | 19 | import java.util.zip.CRC32; 20 | 21 | /** 22 | * CRC32 utility. 23 | * @author jiangping 24 | * @version $Id: CrcUtil2, v 0.1 2017-06-05 11:29 Timo Exp $ 25 | */ 26 | public class CrcUtil { 27 | 28 | private static final ThreadLocal CRC_32_THREAD_LOCAL = new ThreadLocal() { 29 | @Override 30 | protected CRC32 initialValue() { 31 | return new CRC32(); 32 | } 33 | }; 34 | 35 | /** 36 | * Compute CRC32 code for byte[]. 37 | * 38 | * @param array 39 | * @return 40 | */ 41 | public static final int crc32(byte[] array) { 42 | if (array != null) { 43 | return crc32(array, 0, array.length); 44 | } 45 | 46 | return 0; 47 | } 48 | 49 | /** 50 | * Compute CRC32 code for byte[]. 51 | * 52 | * @param array 53 | * @param offset 54 | * @param length 55 | * @return 56 | */ 57 | public static final int crc32(byte[] array, int offset, int length) { 58 | CRC32 crc32 = CRC_32_THREAD_LOCAL.get(); 59 | crc32.update(array, offset, length); 60 | int ret = (int) crc32.getValue(); 61 | crc32.reset(); 62 | return ret; 63 | } 64 | 65 | } 66 | -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/util/FutureTaskNotRunYetException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.util; 18 | 19 | /** 20 | * Exception to represent the run method of a future task has not been called. 21 | * 22 | * @author tsui 23 | * @version $Id: FutureTaskNotRunYetException.java, v 0.1 2017-07-31 16:29 tsui Exp $ 24 | */ 25 | public class FutureTaskNotRunYetException extends Exception { 26 | /** For serialization */ 27 | private static final long serialVersionUID = 2929126204324060632L; 28 | 29 | /** 30 | * Constructor. 31 | */ 32 | public FutureTaskNotRunYetException() { 33 | } 34 | 35 | /** 36 | * Constructor. 37 | */ 38 | public FutureTaskNotRunYetException(String message) { 39 | super(message); 40 | } 41 | 42 | /** 43 | * Constructor. 44 | */ 45 | public FutureTaskNotRunYetException(String message, Throwable cause) { 46 | super(message, cause); 47 | } 48 | } -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/util/FutureTaskUtil.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.util; 18 | 19 | import java.util.concurrent.ExecutionException; 20 | 21 | import org.slf4j.Logger; 22 | 23 | /** 24 | * Utils for future task 25 | * 26 | * @author tsui 27 | * @version $Id: FutureTaskUtil.java, v 0.1 2017-07-24 17:07 tsui Exp $ 28 | */ 29 | public class FutureTaskUtil { 30 | /** 31 | * get the result of a future task 32 | * 33 | * Notice: the run method of this task should have been called at first. 34 | * 35 | * @param task 36 | * @param 37 | * @return 38 | */ 39 | public static T getFutureTaskResult(RunStateRecordedFutureTask task, Logger logger) { 40 | T t = null; 41 | if (null != task) { 42 | try { 43 | t = task.getAfterRun(); 44 | } catch (InterruptedException e) { 45 | logger.error("Future task interrupted!", e); 46 | } catch (ExecutionException e) { 47 | logger.error("Future task execute failed!", e); 48 | } catch (FutureTaskNotRunYetException e) { 49 | logger.error("Future task has not run yet!", e); 50 | } 51 | } 52 | return t; 53 | } 54 | 55 | /** 56 | * launder the throwable 57 | * 58 | * @param t 59 | */ 60 | public static void launderThrowable(Throwable t) { 61 | if (t instanceof RuntimeException) { 62 | throw (RuntimeException) t; 63 | } else if (t instanceof Error) { 64 | throw (Error) t; 65 | } else { 66 | throw new IllegalStateException("Not unchecked!", t); 67 | } 68 | } 69 | } -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/util/IDGenerator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.util; 18 | 19 | import java.util.concurrent.atomic.AtomicInteger; 20 | 21 | /** 22 | * IDGenerator is used for generating request id in integer form. 23 | * 以整形格式生成请求id 24 | * @author jiangping 25 | * @version $Id: IDGenerator.java, v 0.1 2015-9-23 PM5:28:58 tao Exp $ 26 | */ 27 | public class IDGenerator { 28 | private static final AtomicInteger id = new AtomicInteger(0); 29 | 30 | /** 31 | * generate the next id 32 | * 生成下一个id 33 | * @return 34 | */ 35 | public static int nextId() { 36 | return id.incrementAndGet(); 37 | } 38 | 39 | /** 40 | * 重置id 41 | */ 42 | public static void resetId() { 43 | id.set(0); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/util/RunStateRecordedFutureTask.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.util; 18 | 19 | import java.util.concurrent.Callable; 20 | import java.util.concurrent.ExecutionException; 21 | import java.util.concurrent.FutureTask; 22 | import java.util.concurrent.atomic.AtomicBoolean; 23 | 24 | /** 25 | * A customized FutureTask which can record whether the run method has been called. 26 | * @author tsui 27 | * @version $Id: RunStateRecordedFutureTask.java, v 0.1 2017-07-31 16:28 tsui Exp $ 28 | */ 29 | public class RunStateRecordedFutureTask extends FutureTask { 30 | private AtomicBoolean hasRun = new AtomicBoolean(); 31 | 32 | public RunStateRecordedFutureTask(Callable callable) { 33 | super(callable); 34 | } 35 | 36 | @Override 37 | public void run() { 38 | this.hasRun.set(true); 39 | super.run(); 40 | } 41 | 42 | public V getAfterRun() throws InterruptedException, ExecutionException, 43 | FutureTaskNotRunYetException { 44 | if (!hasRun.get()) { 45 | throw new FutureTaskNotRunYetException(); 46 | } 47 | return super.get(); 48 | } 49 | } -------------------------------------------------------------------------------- /src/main/java/com/alipay/remoting/util/TraceLogUtil.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.util; 18 | 19 | import org.slf4j.Logger; 20 | 21 | import com.alipay.remoting.InvokeContext; 22 | 23 | /**
 24 | * Trace log util 25 | * 26 | * @author tsui
 27 | * @version $Id: TraceLogUtil.java, v 0.1 2016-08-02 17:31 tsui Exp $ 28 | */ 29 | public class TraceLogUtil { 30 | /** 31 | * print trace log 32 | * @param traceId 33 | * @param invokeContext 34 | */ 35 | public static void printConnectionTraceLog(Logger logger, String traceId, 36 | InvokeContext invokeContext) { 37 | String sourceIp = invokeContext.get(InvokeContext.CLIENT_LOCAL_IP); 38 | Integer sourcePort = invokeContext.get(InvokeContext.CLIENT_LOCAL_PORT); 39 | String targetIp = invokeContext.get(InvokeContext.CLIENT_REMOTE_IP); 40 | Integer targetPort = invokeContext.get(InvokeContext.CLIENT_REMOTE_PORT); 41 | StringBuilder logMsg = new StringBuilder(); 42 | logMsg.append(traceId).append(","); 43 | logMsg.append(sourceIp).append(","); 44 | logMsg.append(sourcePort).append(","); 45 | logMsg.append(targetIp).append(","); 46 | logMsg.append(targetPort); 47 | if (logger.isInfoEnabled()) { 48 | logger.info(logMsg.toString()); 49 | } 50 | } 51 | } -------------------------------------------------------------------------------- /src/test/java/com/alipay/remoting/ProcessorManagerTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting; 18 | 19 | import org.junit.Assert; 20 | import org.junit.Test; 21 | 22 | import com.alipay.remoting.rpc.protocol.RpcCommandCode; 23 | import com.alipay.remoting.rpc.protocol.RpcRequestProcessor; 24 | 25 | /** 26 | * test processor manager 27 | * 28 | * @author tsui 29 | * @version $Id: ProcessorManagerTest.java, v 0.1 2018-07-06 12:19 tsui Exp $$ 30 | */ 31 | public class ProcessorManagerTest { 32 | 33 | /** 34 | * test it should be override if register twice for the same command code 35 | */ 36 | @Test 37 | public void testRegisterProcessor() { 38 | ProcessorManager processorManager = new ProcessorManager(); 39 | CommandCode cmd1 = RpcCommandCode.RPC_REQUEST; 40 | CommandCode cmd2 = RpcCommandCode.RPC_REQUEST; 41 | RpcRequestProcessor rpcRequestProcessor1 = new RpcRequestProcessor(); 42 | RpcRequestProcessor rpcRequestProcessor2 = new RpcRequestProcessor(); 43 | processorManager.registerProcessor(cmd1, rpcRequestProcessor1); 44 | processorManager.registerProcessor(cmd2, rpcRequestProcessor2); 45 | Assert.assertEquals(processorManager.getProcessor(cmd1), rpcRequestProcessor2); 46 | Assert.assertEquals(processorManager.getProcessor(cmd2), rpcRequestProcessor2); 47 | } 48 | } -------------------------------------------------------------------------------- /src/test/java/com/alipay/remoting/RemotingServerTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting; 18 | 19 | import static org.mockito.Mockito.when; 20 | 21 | import org.junit.Assert; 22 | import org.junit.Test; 23 | import org.mockito.Mockito; 24 | 25 | import com.alipay.remoting.rpc.RpcServer; 26 | 27 | /** 28 | * test {@link AbstractRemotingServer} apis 29 | * 30 | * @author tsui 31 | * @version $Id: RemotingServerTest.java, v 0.1 May 16, 2018 10:00:48 AM tsui Exp $ 32 | */ 33 | public class RemotingServerTest { 34 | @Test 35 | public void testStartRepeatedly() { 36 | RpcServer rpcServer = new RpcServer(1111); 37 | rpcServer.start(); 38 | 39 | try { 40 | rpcServer.start(); 41 | Assert.fail("Should not reach here!"); 42 | } catch (Exception e) { 43 | // expect IllegalStateException 44 | } 45 | rpcServer.stop(); 46 | } 47 | 48 | @Test 49 | public void testStartFailed() throws InterruptedException { 50 | AbstractRemotingServer remotingServer = Mockito.mock(AbstractRemotingServer.class); 51 | when(remotingServer.doStart()).thenThrow(new RuntimeException("start error")); 52 | 53 | Assert.assertFalse(remotingServer.start()); 54 | } 55 | 56 | @Test 57 | public void testStopRepeatedly() { 58 | RpcServer rpcServer = new RpcServer(1111); 59 | try { 60 | rpcServer.start(); 61 | } catch (Exception e) { 62 | Assert.fail("Should not reach here!"); 63 | e.printStackTrace(); 64 | } 65 | rpcServer.stop(); 66 | try { 67 | rpcServer.stop(); 68 | Assert.fail("Should not reach here!"); 69 | } catch (Exception e) { 70 | // expect IllegalStateException 71 | } 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/test/java/com/alipay/remoting/demo/RpcServerDemoByMain.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.demo; 18 | 19 | import org.slf4j.Logger; 20 | import org.slf4j.LoggerFactory; 21 | 22 | import com.alipay.remoting.ConnectionEventType; 23 | import com.alipay.remoting.rpc.common.BoltServer; 24 | import com.alipay.remoting.rpc.common.CONNECTEventProcessor; 25 | import com.alipay.remoting.rpc.common.DISCONNECTEventProcessor; 26 | import com.alipay.remoting.rpc.common.SimpleServerUserProcessor; 27 | 28 | /** 29 | * a demo for rpc server, you can just run the main method to start a server 30 | * 31 | * @author tsui 32 | * @version $Id: RpcServerDemoByMain.java, v 0.1 2018-04-10 10:37 tsui Exp $ 33 | */ 34 | public class RpcServerDemoByMain { 35 | static Logger logger = LoggerFactory 36 | .getLogger(BasicUsageDemoByJunit.class); 37 | 38 | BoltServer server; 39 | 40 | int port = 8999; 41 | 42 | SimpleServerUserProcessor serverUserProcessor = new SimpleServerUserProcessor(); 43 | CONNECTEventProcessor serverConnectProcessor = new CONNECTEventProcessor(); 44 | DISCONNECTEventProcessor serverDisConnectProcessor = new DISCONNECTEventProcessor(); 45 | 46 | public RpcServerDemoByMain() { 47 | // 1. create a Rpc server with port assigned 48 | server = new BoltServer(port); 49 | // 2. add processor for connect and close event if you need 50 | server.addConnectionEventProcessor(ConnectionEventType.CONNECT, serverConnectProcessor); 51 | server.addConnectionEventProcessor(ConnectionEventType.CLOSE, serverDisConnectProcessor); 52 | // 3. register user processor for client request 53 | server.registerUserProcessor(serverUserProcessor); 54 | // 4. server start 55 | if (server.start()) { 56 | System.out.println("server start ok!"); 57 | } else { 58 | System.out.println("server start failed!"); 59 | } 60 | // server.getRpcServer().stop(); 61 | } 62 | 63 | public static void main(String[] args) { 64 | new RpcServerDemoByMain(); 65 | } 66 | } -------------------------------------------------------------------------------- /src/test/java/com/alipay/remoting/rpc/RpcConfigManagerTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.rpc; 18 | 19 | import org.junit.After; 20 | import org.junit.AfterClass; 21 | import org.junit.Assert; 22 | import org.junit.Before; 23 | import org.junit.BeforeClass; 24 | import org.junit.Test; 25 | 26 | public class RpcConfigManagerTest { 27 | @BeforeClass 28 | public static void initClass() { 29 | } 30 | 31 | @Before 32 | public void init() { 33 | } 34 | 35 | @After 36 | public void stop() { 37 | } 38 | 39 | @AfterClass 40 | public static void afterClass() { 41 | } 42 | 43 | @Test 44 | public void testSystemSettings() { 45 | Assert.assertTrue(RpcConfigManager.dispatch_msg_list_in_default_executor()); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/test/java/com/alipay/remoting/rpc/RpcServerTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.rpc; 18 | 19 | import org.junit.After; 20 | import org.junit.Assert; 21 | import org.junit.Before; 22 | import org.junit.Test; 23 | import org.slf4j.Logger; 24 | import org.slf4j.LoggerFactory; 25 | 26 | /** 27 | * test rpc server and stop logic 28 | * 29 | * @author tsui 
 30 | * @version $Id: RpcServerTest.java, v 0.1 2018-05-29 15:27 tsui Exp $$
 31 | */ 32 | public class RpcServerTest { 33 | static Logger logger = LoggerFactory.getLogger(RpcServerTest.class); 34 | 35 | @Before 36 | public void init() { 37 | } 38 | 39 | @After 40 | public void stop() { 41 | } 42 | 43 | @Test 44 | public void doTestStartAndStop() { 45 | doTestStartAndStop(true); 46 | doTestStartAndStop(false); 47 | } 48 | 49 | private void doTestStartAndStop(boolean syncStop) { 50 | // 1. start a rpc server successfully 51 | RpcServer rpcServer1 = new RpcServer(1111, false, syncStop); 52 | try { 53 | rpcServer1.start(); 54 | } catch (Exception e) { 55 | logger.warn("start fail"); 56 | Assert.fail("Should not reach here"); 57 | } 58 | 59 | logger.warn("start success"); 60 | // 2. start a rpc server with the same port number failed 61 | RpcServer rpcServer2 = new RpcServer(1111, false, syncStop); 62 | try { 63 | rpcServer2.start(); 64 | Assert.fail("Should not reach here"); 65 | logger.warn("start success"); 66 | } catch (Exception e) { 67 | logger.warn("start fail"); 68 | } 69 | 70 | // 3. stop the first rpc server successfully 71 | try { 72 | rpcServer1.stop(); 73 | } catch (IllegalStateException e) { 74 | Assert.fail("Should not reach here"); 75 | } 76 | 77 | // 4. stop the second rpc server failed, for if start failed, stop method will be called automatically 78 | try { 79 | rpcServer2.stop(); 80 | Assert.fail("Should not reach here"); 81 | } catch (IllegalStateException e) { 82 | // expect 83 | } 84 | } 85 | } -------------------------------------------------------------------------------- /src/test/java/com/alipay/remoting/rpc/addressargs/RpcAddressParser_SOFTREF_Test.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.rpc.addressargs; 18 | 19 | import org.junit.Assert; 20 | 21 | import com.alipay.remoting.Url; 22 | import com.alipay.remoting.exception.RemotingException; 23 | import com.alipay.remoting.rpc.RpcAddressParser; 24 | 25 | /** 26 | * rpc address parser 27 | * test soft reference 28 | * 29 | * @author xiaomin.cxm 30 | * @version $Id: RpcAddressParser_SOFTREF_Test.java, v 0.1 Apr 6, 2016 10:45:13 AM xiaomin.cxm Exp $ 31 | */ 32 | public class RpcAddressParser_SOFTREF_Test { 33 | 34 | // @Test 35 | public void testParserNonProtocol() throws RemotingException { 36 | String url = "127.0.0.1:1111?_TIMEOUT=3000&_SERIALIZETYPE=hessian2"; 37 | RpcAddressParser parser = new RpcAddressParser(); 38 | int MAX = 1000000; 39 | 40 | printMemory(); 41 | long start1 = System.currentTimeMillis(); 42 | for (int i = 0; i < MAX; ++i) { 43 | Url btUrl = parser.parse(url); 44 | Assert.assertEquals(btUrl.getUniqueKey(), "127.0.0.1:1111"); 45 | } 46 | long end1 = System.currentTimeMillis(); 47 | long time1 = end1 - start1; 48 | System.out.println("time1:" + time1); 49 | printMemory(); 50 | } 51 | 52 | private void printMemory() { 53 | int mb = 1024 * 1024; 54 | Runtime rt = Runtime.getRuntime(); 55 | long total = rt.totalMemory(); 56 | long max = rt.maxMemory(); 57 | long free = rt.freeMemory(); 58 | System.out.print("total[" + total / mb + "mb] "); 59 | System.out.print("max[" + max / mb + "mb] "); 60 | System.out.println("free[" + free / mb + "mb]"); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/test/java/com/alipay/remoting/rpc/common/BoltServer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.rpc.common; 18 | 19 | import com.alipay.remoting.ConnectionEventProcessor; 20 | import com.alipay.remoting.ConnectionEventType; 21 | import com.alipay.remoting.rpc.RpcServer; 22 | import com.alipay.remoting.rpc.protocol.UserProcessor; 23 | 24 | /** 25 | * Demo for bolt server 26 | * 27 | * @author xiaomin.cxm 28 | * @version $Id: BoltServer.java, v 0.1 Apr 6, 2016 3:33:51 PM xiaomin.cxm Exp $ 29 | */ 30 | public class BoltServer { 31 | /** port */ 32 | private int port; 33 | 34 | /** rpc server */ 35 | private RpcServer server; 36 | 37 | // ~~~ constructors 38 | public BoltServer(int port) { 39 | this.port = port; 40 | this.server = new RpcServer(this.port); 41 | } 42 | 43 | public BoltServer(int port, boolean manageFeatureEnabled) { 44 | this.port = port; 45 | this.server = new RpcServer(this.port, manageFeatureEnabled); 46 | } 47 | 48 | public BoltServer(int port, boolean manageFeatureEnabled, boolean syncStop) { 49 | this.port = port; 50 | this.server = new RpcServer(this.port, manageFeatureEnabled, syncStop); 51 | } 52 | 53 | public boolean start() { 54 | this.server.start(); 55 | return true; 56 | } 57 | 58 | public void stop() { 59 | this.server.stop(); 60 | } 61 | 62 | public RpcServer getRpcServer() { 63 | return this.server; 64 | } 65 | 66 | public void registerUserProcessor(UserProcessor processor) { 67 | this.server.registerUserProcessor(processor); 68 | } 69 | 70 | public void addConnectionEventProcessor(ConnectionEventType type, 71 | ConnectionEventProcessor processor) { 72 | this.server.addConnectionEventProcessor(type, processor); 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/test/java/com/alipay/remoting/rpc/common/DISCONNECTEventProcessor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.rpc.common; 18 | 19 | import java.util.concurrent.atomic.AtomicBoolean; 20 | import java.util.concurrent.atomic.AtomicInteger; 21 | 22 | import org.junit.Assert; 23 | 24 | import com.alipay.remoting.Connection; 25 | import com.alipay.remoting.ConnectionEventProcessor; 26 | 27 | /** 28 | * ConnectionEventProcessor for ConnectionEventType.CLOSE 29 | * 30 | * @author xiaomin.cxm 31 | * @version $Id: DISCONNECTEventProcessor.java, v 0.1 Apr 8, 2016 10:58:48 AM xiaomin.cxm Exp $ 32 | */ 33 | public class DISCONNECTEventProcessor implements ConnectionEventProcessor { 34 | 35 | private AtomicBoolean dicConnected = new AtomicBoolean(); 36 | private AtomicInteger disConnectTimes = new AtomicInteger(); 37 | 38 | @Override 39 | public void onEvent(String remoteAddr, Connection conn) { 40 | Assert.assertNotNull(conn); 41 | dicConnected.set(true); 42 | disConnectTimes.incrementAndGet(); 43 | } 44 | 45 | public boolean isDisConnected() { 46 | return this.dicConnected.get(); 47 | } 48 | 49 | public int getDisConnectTimes() { 50 | return this.disConnectTimes.get(); 51 | } 52 | 53 | public void reset() { 54 | this.disConnectTimes.set(0); 55 | this.dicConnected.set(false); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/test/java/com/alipay/remoting/rpc/common/PortScan.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.rpc.common; 18 | 19 | import java.io.IOException; 20 | import java.net.InetSocketAddress; 21 | import java.net.ServerSocket; 22 | import java.net.Socket; 23 | 24 | import org.slf4j.Logger; 25 | import org.slf4j.LoggerFactory; 26 | 27 | public class PortScan { 28 | private static final Logger logger = LoggerFactory.getLogger(PortScan.class); 29 | 30 | static public int select() { 31 | int port = -1; 32 | ServerSocket ss = null; 33 | try { 34 | ss = new ServerSocket(); 35 | ss.bind(null); 36 | port = ss.getLocalPort(); 37 | } catch (IOException ioe) { 38 | ioe.printStackTrace(); 39 | } finally { 40 | try { 41 | ss.close(); 42 | logger.warn("Server socket close status: {}", ss.isClosed()); 43 | } catch (IOException e) { 44 | } 45 | } 46 | return port; 47 | } 48 | 49 | public static void main(String[] args) throws Exception { 50 | int port = PortScan.select(); 51 | ServerSocket ss = new ServerSocket(); 52 | ss.bind(new InetSocketAddress(port)); 53 | logger.warn("listening on port:{}", port); 54 | 55 | Thread.sleep(100); 56 | Socket s = new Socket("localhost", port); 57 | System.out.println(s.isConnected()); 58 | System.out.println("local port: " + s.getLocalPort()); 59 | System.out.println("remote port: " + s.getPort()); 60 | Object lock = new Object(); 61 | 62 | synchronized (lock) { 63 | lock.wait(); 64 | } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/test/java/com/alipay/remoting/rpc/heartbeat/CustomHeartBeatProcessor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.rpc.heartbeat; 18 | 19 | import java.util.Date; 20 | import java.util.concurrent.atomic.AtomicInteger; 21 | 22 | import org.slf4j.Logger; 23 | import org.slf4j.LoggerFactory; 24 | 25 | import com.alipay.remoting.AbstractRemotingProcessor; 26 | import com.alipay.remoting.RemotingCommand; 27 | import com.alipay.remoting.RemotingContext; 28 | 29 | /** 30 | * CustomHeartBeatProcessor 31 | * 32 | * @author xiaomin.cxm 33 | * @version $Id: CustomHeartBeatProcessor.java, v 0.1 Apr 12, 2016 12:05:19 PM xiaomin.cxm Exp $ 34 | */ 35 | public class CustomHeartBeatProcessor extends AbstractRemotingProcessor { 36 | static Logger logger = LoggerFactory.getLogger(CustomHeartBeatProcessor.class); 37 | 38 | private AtomicInteger heartBeatTimes = new AtomicInteger(); 39 | 40 | public int getHeartBeatTimes() { 41 | return heartBeatTimes.get(); 42 | } 43 | 44 | public void reset() { 45 | this.heartBeatTimes.set(0); 46 | } 47 | 48 | @Override 49 | public void doProcess(RemotingContext ctx, RemotingCommand msg) throws Exception { 50 | heartBeatTimes.incrementAndGet(); 51 | java.text.DateFormat format1 = new java.text.SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); 52 | logger.warn("heart beat received:" + format1.format(new Date())); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/test/java/com/alipay/remoting/rpc/userprocessor/executorselector/DefaultExecutorSelector.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.rpc.userprocessor.executorselector; 18 | 19 | import java.util.concurrent.ArrayBlockingQueue; 20 | import java.util.concurrent.Executor; 21 | import java.util.concurrent.ThreadPoolExecutor; 22 | import java.util.concurrent.TimeUnit; 23 | 24 | import org.junit.Assert; 25 | 26 | import com.alipay.remoting.NamedThreadFactory; 27 | import com.alipay.remoting.rpc.protocol.UserProcessor; 28 | import com.alipay.remoting.util.StringUtils; 29 | 30 | /** 31 | * Default Executor Selector 32 | * 33 | * @author tsui 34 | * @version $Id: DefaultExecutorSelector.java, v 0.1 2017-04-24 15:51 tsui Exp $ 35 | */ 36 | public class DefaultExecutorSelector implements UserProcessor.ExecutorSelector { 37 | public static final String EXECUTOR0 = "executor0"; 38 | public static final String EXECUTOR1 = "executor1"; 39 | private String chooseExecutorStr; 40 | /** executor */ 41 | private ThreadPoolExecutor executor0; 42 | private ThreadPoolExecutor executor1; 43 | 44 | public DefaultExecutorSelector(String chooseExecutorStr) { 45 | this.chooseExecutorStr = chooseExecutorStr; 46 | this.executor0 = new ThreadPoolExecutor(1, 3, 60, TimeUnit.SECONDS, 47 | new ArrayBlockingQueue(4), new NamedThreadFactory("Rpc-specific0-executor")); 48 | this.executor1 = new ThreadPoolExecutor(1, 3, 60, TimeUnit.SECONDS, 49 | new ArrayBlockingQueue(4), new NamedThreadFactory("Rpc-specific1-executor")); 50 | } 51 | 52 | @Override 53 | public Executor select(String requestClass, Object requestHeader) { 54 | Assert.assertNotNull(requestClass); 55 | Assert.assertNotNull(requestHeader); 56 | if (StringUtils.equals(chooseExecutorStr, (String) requestHeader)) { 57 | return executor1; 58 | } else { 59 | return executor0; 60 | } 61 | } 62 | } -------------------------------------------------------------------------------- /src/test/java/com/alipay/remoting/rpc/userprocessor/multiinterestprocessor/MultiInterestBaseRequestBody.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.rpc.userprocessor.multiinterestprocessor; 18 | 19 | import java.io.Serializable; 20 | 21 | /** 22 | * @antuor muyun.cyt (muyun.cyt@antfin.com) 2018/7/5 11:20 AM 23 | */ 24 | public interface MultiInterestBaseRequestBody extends Serializable { 25 | /** 26 | * Getter method for property id. 27 | * 28 | * @return property value of id 29 | */ 30 | int getId(); 31 | 32 | /** 33 | * Setter method for property id. 34 | * 35 | * @param id value to be assigned to property id 36 | */ 37 | void setId(int id); 38 | 39 | /** 40 | * Getter method for property msg. 41 | * 42 | * @return property value of msg 43 | */ 44 | String getMsg(); 45 | 46 | /** 47 | * Setter method for property msg. 48 | * 49 | * @param msg value to be assigned to property msg 50 | */ 51 | void setMsg(String msg); 52 | } 53 | -------------------------------------------------------------------------------- /src/test/java/com/alipay/remoting/util/ThreadTestUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package com.alipay.remoting.util; 18 | 19 | /**
 20 | * utils of thread operations 21 | * 22 | * @author tsui 
 23 | * @version $Id: ThreadTestUtils.java, v 0.1 2018-05-29 15:29 tsui Exp $$
 24 | */ 25 | public class ThreadTestUtils { 26 | public static void sleep(long duration) { 27 | try { 28 | Thread.sleep(duration); 29 | } catch (InterruptedException e) { 30 | //ignore 31 | } 32 | } 33 | } -------------------------------------------------------------------------------- /src/test/resources/log4j2.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | --------------------------------------------------------------------------------