├── .gitignore ├── LICENSE.md ├── README.md ├── pom.xml ├── rpc_client ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── github │ │ └── rockeyhoo │ │ └── rpc │ │ └── client │ │ ├── RpcClient.java │ │ ├── RpcProxy.java │ │ ├── RpcRequest.java │ │ ├── RpcResponse.java │ │ └── ServiceDiscovery.java │ └── resources │ ├── client-config.properties │ └── spring-client.xml ├── rpc_common ├── pom.xml └── src │ └── main │ └── java │ └── com │ └── github │ └── rockeyhoo │ └── rpc │ └── common │ ├── Constant.java │ ├── RpcDecoder.java │ ├── RpcEncoder.java │ └── SerializationUtil.java ├── rpc_service ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── github │ │ └── roockey │ │ └── rpc │ │ └── service │ │ ├── core │ │ ├── RpcBootstrap.java │ │ ├── RpcHandler.java │ │ ├── RpcServer.java │ │ ├── RpcService.java │ │ └── ServiceRegistry.java │ │ └── modules │ │ └── simple │ │ ├── HelloService.java │ │ └── impl │ │ └── HelloServiceImpl.java │ └── resources │ ├── server-config.properties │ └── spring-server.xml └── rpc_simple ├── pom.xml └── src └── test └── java └── com └── github └── rockeyhoo └── rpc └── simple └── HelloServiceTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | # IntelliJ project files 2 | .idea/ 3 | *.iml 4 | target/ 5 | .DS_Store 6 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | {description} 294 | Copyright (C) {year} {fullname} 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | {signature of Ty Coon}, 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # messenger 2 | 3 | Spring + Netty + Protostuff + ZooKeeper 实现了一个轻量级 RPC 框架,使用 Spring 提供依赖注入与参数配置,使用 Netty 实现 NIO 方式的数据传输,使用 Protostuff 实现对象序列化,使用 ZooKeeper 实现服务注册与发现。使用该框架,可将服务部署到分布式环境中的任意节点上,客户端通过远程接口来调用服务端的具体实现,让服务端与客户端的开发完全分离,为实现大规模分布式应用提供了基础支持 4 | 5 | 6 | jdk 1.7 + -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | com.github.rockeyhoo 5 | rpc 6 | pom 7 | 0.0.1-SNAPSHOT 8 | messenger 9 | https://github.com/RockeyHoo/messenger 10 | 11 | 12 | rpc_client 13 | rpc_service 14 | rpc_common 15 | rpc_simple 16 | 17 | 18 | 19 | UTF-8 20 | 4.11 21 | 1.7.7 22 | 3.2.12.RELEASE 23 | 4.0.24.Final 24 | 1.0.8 25 | 3.4.6 26 | 2.1 27 | 3.1 28 | 8.1.15.v20140411 29 | 16.0.1 30 | 4.0 31 | 32 | 33 | 34 | 35 | 36 | 37 | junit 38 | junit 39 | ${junit.version} 40 | test 41 | 42 | 43 | 44 | 45 | org.slf4j 46 | slf4j-log4j12 47 | ${slf4j.version} 48 | 49 | 50 | 51 | 52 | org.springframework 53 | spring-context 54 | ${spring.version} 55 | 56 | 57 | org.springframework 58 | spring-test 59 | ${spring.version} 60 | test 61 | 62 | 63 | 64 | 65 | io.netty 66 | netty-all 67 | ${netty.version} 68 | 69 | 70 | 71 | 72 | com.dyuproject.protostuff 73 | protostuff-core 74 | ${protostuff.version} 75 | 76 | 77 | com.dyuproject.protostuff 78 | protostuff-runtime 79 | ${protostuff.version} 80 | 81 | 82 | 83 | 84 | org.apache.zookeeper 85 | zookeeper 86 | ${zookeeper.version} 87 | 88 | 89 | 90 | 91 | org.apache.commons 92 | commons-collections4 93 | ${commons-collections4.version} 94 | 95 | 96 | 97 | 98 | org.objenesis 99 | objenesis 100 | ${objenesis.version} 101 | 102 | 103 | 104 | 105 | cglib 106 | cglib 107 | ${cglib.version} 108 | 109 | 110 | 111 | 112 | com.google.guava 113 | guava 114 | ${guava.version} 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | org.apache.maven.plugins 129 | maven-compiler-plugin 130 | 3.1 131 | 132 | 1.7 133 | 1.7 134 | ${project.build.sourceEncoding} 135 | 136 | 137 | 138 | 139 | 140 | org.apache.maven.plugins 141 | maven-release-plugin 142 | 2.4.2 143 | 144 | 145 | 146 | 147 | org.mortbay.jetty 148 | jetty-maven-plugin 149 | ${jetty.version} 150 | 151 | 152 | 153 | 154 | 155 | -------------------------------------------------------------------------------- /rpc_client/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | rpc 7 | com.github.rockeyhoo 8 | 0.0.1-SNAPSHOT 9 | 10 | 4.0.0 11 | rpc-client 12 | 13 | 14 | 15 | com.github.rockeyhoo 16 | rpc-common 17 | 0.0.1-SNAPSHOT 18 | 19 | 20 | 21 | org.slf4j 22 | slf4j-log4j12 23 | 24 | 25 | 26 | 27 | org.springframework 28 | spring-context 29 | 30 | 31 | 32 | io.netty 33 | netty-all 34 | 35 | 36 | 37 | 38 | com.dyuproject.protostuff 39 | protostuff-core 40 | 41 | 42 | com.dyuproject.protostuff 43 | protostuff-runtime 44 | 45 | 46 | 47 | 48 | org.apache.zookeeper 49 | zookeeper 50 | 51 | 52 | 53 | 54 | org.apache.commons 55 | commons-collections4 56 | 57 | 58 | 59 | 60 | org.objenesis 61 | objenesis 62 | 63 | 64 | 65 | 66 | cglib 67 | cglib 68 | 69 | 70 | 71 | 72 | 73 | 74 | org.apache.maven.plugins 75 | maven-compiler-plugin 76 | 77 | 78 | 79 | org.apache.maven.plugins 80 | maven-release-plugin 81 | 82 | 83 | 84 | -------------------------------------------------------------------------------- /rpc_client/src/main/java/com/github/rockeyhoo/rpc/client/RpcClient.java: -------------------------------------------------------------------------------- 1 | package com.github.rockeyhoo.rpc.client; 2 | 3 | import io.netty.bootstrap.Bootstrap; 4 | import io.netty.channel.ChannelFuture; 5 | import io.netty.channel.ChannelHandlerContext; 6 | import io.netty.channel.ChannelInitializer; 7 | import io.netty.channel.ChannelOption; 8 | import io.netty.channel.EventLoopGroup; 9 | import io.netty.channel.SimpleChannelInboundHandler; 10 | import io.netty.channel.nio.NioEventLoopGroup; 11 | import io.netty.channel.socket.SocketChannel; 12 | import io.netty.channel.socket.nio.NioSocketChannel; 13 | 14 | import org.slf4j.Logger; 15 | import org.slf4j.LoggerFactory; 16 | import com.github.rockeyhoo.rpc.common.RpcDecoder; 17 | import com.github.rockeyhoo.rpc.common.RpcEncoder; 18 | 19 | 20 | public class RpcClient extends SimpleChannelInboundHandler { 21 | 22 | private static final Logger LOGGER = LoggerFactory.getLogger(RpcClient.class); 23 | 24 | private String host; 25 | private int port; 26 | 27 | private RpcResponse response; 28 | 29 | private final Object obj = new Object(); 30 | 31 | public RpcClient(String host, int port) { 32 | this.host = host; 33 | this.port = port; 34 | } 35 | 36 | @Override 37 | public void channelRead0(ChannelHandlerContext ctx, RpcResponse response) throws Exception { 38 | this.response = response; 39 | synchronized (obj) { 40 | obj.notifyAll(); // 收到响应,唤醒线程 41 | } 42 | } 43 | 44 | @Override 45 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { 46 | LOGGER.error("client caught exception", cause); 47 | ctx.close(); 48 | } 49 | 50 | public RpcResponse send(RpcRequest request) throws Exception { 51 | EventLoopGroup group = new NioEventLoopGroup(); 52 | try { 53 | Bootstrap bootstrap = new Bootstrap(); 54 | bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer() { 55 | @Override 56 | public void initChannel(SocketChannel channel) throws Exception { 57 | channel.pipeline().addLast(new RpcEncoder(RpcRequest.class)) // 将 RPC 请求进行编码(为了发送请求) 58 | .addLast(new RpcDecoder(RpcResponse.class)) // 将 RPC 响应进行解码(为了处理响应) 59 | .addLast(RpcClient.this); // 使用 RpcClient 发送 RPC 请求 60 | } 61 | }).option(ChannelOption.SO_KEEPALIVE, true); 62 | 63 | ChannelFuture future = bootstrap.connect(host, port).sync(); 64 | future.channel().writeAndFlush(request).sync(); 65 | 66 | synchronized (obj) { 67 | obj.wait(); // 未收到响应,使线程等待 68 | } 69 | 70 | if (response != null) { 71 | future.channel().closeFuture().sync(); 72 | } 73 | return response; 74 | } finally { 75 | group.shutdownGracefully(); 76 | } 77 | } 78 | } -------------------------------------------------------------------------------- /rpc_client/src/main/java/com/github/rockeyhoo/rpc/client/RpcProxy.java: -------------------------------------------------------------------------------- 1 | package com.github.rockeyhoo.rpc.client; 2 | 3 | import java.lang.reflect.Method; 4 | import java.util.UUID; 5 | 6 | import net.sf.cglib.proxy.InvocationHandler; 7 | import net.sf.cglib.proxy.Proxy; 8 | 9 | public class RpcProxy { 10 | private String serverAddress; 11 | private ServiceDiscovery serviceDiscovery; 12 | 13 | public RpcProxy(String serverAddress) { 14 | this.serverAddress = serverAddress; 15 | } 16 | 17 | public RpcProxy(ServiceDiscovery serviceDiscovery) { 18 | this.serviceDiscovery = serviceDiscovery; 19 | } 20 | 21 | @SuppressWarnings("unchecked") 22 | public T create(Class interfaceClass) { 23 | return (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class[]{interfaceClass}, 24 | new InvocationHandler() { 25 | @Override 26 | public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 27 | RpcRequest request = new RpcRequest(); // 创建并初始化 RPC 请求 28 | request.setRequestId(UUID.randomUUID().toString()); 29 | request.setClassName(method.getDeclaringClass().getName()); 30 | request.setMethodName(method.getName()); 31 | request.setParameterTypes(method.getParameterTypes()); 32 | request.setParameters(args); 33 | 34 | if (serviceDiscovery != null) { 35 | serverAddress = serviceDiscovery.discover(); // 发现服务 36 | } 37 | String[] array = serverAddress.split(":"); 38 | String host = array[0]; 39 | int port = Integer.parseInt(array[1]); 40 | 41 | RpcClient client = new RpcClient(host, port); // 初始化 RPC 客户端 42 | RpcResponse response = client.send(request); // 通过 RPC客户端发送RPC请求并获取RPC响应 43 | if (response.isError()) { 44 | throw response.getError(); 45 | } else { 46 | return response.getResult(); 47 | } 48 | } 49 | }); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /rpc_client/src/main/java/com/github/rockeyhoo/rpc/client/RpcRequest.java: -------------------------------------------------------------------------------- 1 | package com.github.rockeyhoo.rpc.client; 2 | 3 | public class RpcRequest { 4 | private String requestId; 5 | private String className; 6 | private String methodName; 7 | private Class[] parameterTypes; 8 | private Object[] parameters; 9 | 10 | public String getRequestId() { 11 | return requestId; 12 | } 13 | 14 | public void setRequestId(String requestId) { 15 | this.requestId = requestId; 16 | } 17 | 18 | public String getClassName() { 19 | return className; 20 | } 21 | 22 | public void setClassName(String className) { 23 | this.className = className; 24 | } 25 | 26 | public String getMethodName() { 27 | return methodName; 28 | } 29 | 30 | public void setMethodName(String methodName) { 31 | this.methodName = methodName; 32 | } 33 | 34 | public Class[] getParameterTypes() { 35 | return parameterTypes; 36 | } 37 | 38 | public void setParameterTypes(Class[] parameterTypes) { 39 | this.parameterTypes = parameterTypes; 40 | } 41 | 42 | public Object[] getParameters() { 43 | return parameters; 44 | } 45 | 46 | public void setParameters(Object[] parameters) { 47 | this.parameters = parameters; 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /rpc_client/src/main/java/com/github/rockeyhoo/rpc/client/RpcResponse.java: -------------------------------------------------------------------------------- 1 | package com.github.rockeyhoo.rpc.client; 2 | 3 | public class RpcResponse { 4 | private String requestId; 5 | private Throwable error; 6 | private Object result; 7 | 8 | public String getRequestId() { 9 | return requestId; 10 | } 11 | 12 | public void setRequestId(String requestId) { 13 | this.requestId = requestId; 14 | } 15 | 16 | public boolean isError(){ 17 | return error == null; 18 | } 19 | 20 | public Throwable getError() { 21 | return error; 22 | } 23 | 24 | public void setError(Throwable error) { 25 | this.error = error; 26 | } 27 | 28 | public Object getResult() { 29 | return result; 30 | } 31 | 32 | public void setResult(Object result) { 33 | this.result = result; 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /rpc_client/src/main/java/com/github/rockeyhoo/rpc/client/ServiceDiscovery.java: -------------------------------------------------------------------------------- 1 | package com.github.rockeyhoo.rpc.client; 2 | 3 | import io.netty.util.internal.ThreadLocalRandom; 4 | 5 | import java.io.IOException; 6 | import java.util.ArrayList; 7 | import java.util.List; 8 | import java.util.concurrent.CountDownLatch; 9 | 10 | import org.apache.zookeeper.KeeperException; 11 | import org.apache.zookeeper.WatchedEvent; 12 | import org.apache.zookeeper.Watcher; 13 | import org.apache.zookeeper.ZooKeeper; 14 | import org.slf4j.Logger; 15 | import org.slf4j.LoggerFactory; 16 | import com.github.rockeyhoo.rpc.common.Constant; 17 | 18 | 19 | public class ServiceDiscovery { 20 | private static final Logger LOGGER = LoggerFactory.getLogger(ServiceDiscovery.class); 21 | 22 | private CountDownLatch latch = new CountDownLatch(1); 23 | 24 | private volatile List dataList = new ArrayList(); 25 | 26 | private String registryAddress; 27 | 28 | public ServiceDiscovery(String registryAddress) { 29 | this.registryAddress = registryAddress; 30 | 31 | ZooKeeper zk = connectServer(); 32 | if (zk != null) { 33 | watchNode(zk); 34 | } 35 | } 36 | 37 | public String discover() { 38 | String data = null; 39 | int size = dataList.size(); 40 | if (size > 0) { 41 | if (size == 1) { 42 | data = dataList.get(0); 43 | LOGGER.debug("using only data: {}", data); 44 | } else { 45 | data = dataList.get(ThreadLocalRandom.current().nextInt(size)); 46 | LOGGER.debug("using random data: {}", data); 47 | } 48 | } 49 | return data; 50 | } 51 | 52 | private ZooKeeper connectServer() { 53 | ZooKeeper zk = null; 54 | try { 55 | zk = new ZooKeeper(registryAddress, Constant.ZK_SESSION_TIMEOUT, new Watcher() { 56 | @Override 57 | public void process(WatchedEvent event) { 58 | if (event.getState() == Event.KeeperState.SyncConnected) { 59 | latch.countDown(); 60 | } 61 | } 62 | }); 63 | latch.await(); 64 | } catch (IOException | InterruptedException e) { 65 | LOGGER.error("", e); 66 | } 67 | return zk; 68 | } 69 | 70 | private void watchNode(final ZooKeeper zk) { 71 | try { 72 | List nodeList = zk.getChildren(Constant.ZK_REGISTRY_PATH, new Watcher() { 73 | @Override 74 | public void process(WatchedEvent event) { 75 | if (event.getType() == Event.EventType.NodeChildrenChanged) { 76 | watchNode(zk); 77 | } 78 | } 79 | }); 80 | List dataList = new ArrayList<>(); 81 | for (String node : nodeList) { 82 | byte[] bytes = zk.getData(Constant.ZK_REGISTRY_PATH + "/" + node, false, null); 83 | dataList.add(new String(bytes)); 84 | } 85 | LOGGER.debug("node data: {}", dataList); 86 | this.dataList = dataList; 87 | } catch (KeeperException | InterruptedException e) { 88 | LOGGER.error("", e); 89 | } 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /rpc_client/src/main/resources/client-config.properties: -------------------------------------------------------------------------------- 1 | # ZooKeeper \u670d\u52a1\u5668 2 | registry.address=127.0.0.1:2181 -------------------------------------------------------------------------------- /rpc_client/src/main/resources/spring-client.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /rpc_common/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | rpc 7 | com.github.rockeyhoo 8 | 0.0.1-SNAPSHOT 9 | 10 | 4.0.0 11 | 12 | 13 | rpc-common 14 | 15 | 16 | 17 | org.slf4j 18 | slf4j-log4j12 19 | 20 | 21 | 22 | io.netty 23 | netty-all 24 | 25 | 26 | 27 | com.dyuproject.protostuff 28 | protostuff-core 29 | 30 | 31 | com.dyuproject.protostuff 32 | protostuff-runtime 33 | 34 | 35 | 36 | org.apache.zookeeper 37 | zookeeper 38 | 39 | 40 | org.objenesis 41 | objenesis 42 | 43 | 44 | 45 | 46 | 47 | 48 | org.apache.maven.plugins 49 | maven-compiler-plugin 50 | 51 | 52 | 53 | org.apache.maven.plugins 54 | maven-release-plugin 55 | 56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /rpc_common/src/main/java/com/github/rockeyhoo/rpc/common/Constant.java: -------------------------------------------------------------------------------- 1 | package com.github.rockeyhoo.rpc.common; 2 | 3 | public interface Constant { 4 | int ZK_SESSION_TIMEOUT = 5000; 5 | 6 | String ZK_REGISTRY_PATH = "/registry"; 7 | String ZK_DATA_PATH = ZK_REGISTRY_PATH + "/data"; 8 | } 9 | -------------------------------------------------------------------------------- /rpc_common/src/main/java/com/github/rockeyhoo/rpc/common/RpcDecoder.java: -------------------------------------------------------------------------------- 1 | package com.github.rockeyhoo.rpc.common; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import io.netty.channel.ChannelHandlerContext; 5 | import io.netty.handler.codec.ByteToMessageDecoder; 6 | import io.netty.handler.codec.MessageToByteEncoder; 7 | 8 | import java.util.List; 9 | 10 | public class RpcDecoder extends ByteToMessageDecoder { 11 | 12 | private Class genericClass; 13 | 14 | public RpcDecoder(Class genericClass) { 15 | this.genericClass = genericClass; 16 | } 17 | 18 | @Override 19 | public final void decode(ChannelHandlerContext ctx, ByteBuf in, List out) throws Exception { 20 | if (in.readableBytes() < 4) { 21 | return; 22 | } 23 | in.markReaderIndex(); 24 | int dataLength = in.readInt(); 25 | if (dataLength < 0) { 26 | ctx.close(); 27 | } 28 | if (in.readableBytes() < dataLength) { 29 | in.resetReaderIndex(); 30 | } 31 | byte[] data = new byte[dataLength]; 32 | in.readBytes(data); 33 | 34 | Object obj = SerializationUtil.deserialize(data, genericClass); 35 | out.add(obj); 36 | } 37 | 38 | public static class RpcEncoder extends MessageToByteEncoder { 39 | 40 | private Class genericClass; 41 | 42 | public RpcEncoder(Class genericClass) { 43 | this.genericClass = genericClass; 44 | } 45 | 46 | @Override 47 | public void encode(ChannelHandlerContext ctx, Object in, ByteBuf out) throws Exception { 48 | if (genericClass.isInstance(in)) { 49 | byte[] data = SerializationUtil.serialize(in); 50 | out.writeInt(data.length); 51 | out.writeBytes(data); 52 | } 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /rpc_common/src/main/java/com/github/rockeyhoo/rpc/common/RpcEncoder.java: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2015 meituan 2 | // All rights reserved 3 | package com.github.rockeyhoo.rpc.common; 4 | 5 | import io.netty.buffer.ByteBuf; 6 | import io.netty.channel.ChannelHandlerContext; 7 | import io.netty.handler.codec.MessageToByteEncoder; 8 | 9 | /** 10 | * Summary: RPC加密 11 | * Author : anduo@qq.com 12 | * Version: 1.0 13 | * Date : 15/4/26 14 | * time : 21:51 15 | */ 16 | public class RpcEncoder extends MessageToByteEncoder { 17 | 18 | private Class genericClass; 19 | 20 | public RpcEncoder(Class genericClass) { 21 | this.genericClass = genericClass; 22 | } 23 | 24 | @Override 25 | public void encode(ChannelHandlerContext ctx, Object in, ByteBuf out) throws Exception { 26 | if (genericClass.isInstance(in)) { 27 | byte[] data = SerializationUtil.serialize(in); 28 | out.writeInt(data.length); 29 | out.writeBytes(data); 30 | } 31 | } 32 | } -------------------------------------------------------------------------------- /rpc_common/src/main/java/com/github/rockeyhoo/rpc/common/SerializationUtil.java: -------------------------------------------------------------------------------- 1 | package com.github.rockeyhoo.rpc.common; 2 | 3 | import java.util.Map; 4 | import java.util.concurrent.ConcurrentHashMap; 5 | 6 | import org.objenesis.Objenesis; 7 | import org.objenesis.ObjenesisStd; 8 | 9 | import com.dyuproject.protostuff.LinkedBuffer; 10 | import com.dyuproject.protostuff.ProtostuffIOUtil; 11 | import com.dyuproject.protostuff.Schema; 12 | import com.dyuproject.protostuff.runtime.RuntimeSchema; 13 | 14 | public class SerializationUtil { 15 | private static Map, Schema> cachedSchema = new ConcurrentHashMap<>(); 16 | 17 | private static Objenesis objenesis = new ObjenesisStd(true); 18 | 19 | private SerializationUtil() { 20 | } 21 | 22 | @SuppressWarnings("unchecked") 23 | private static Schema getSchema(Class cls) { 24 | Schema schema = (Schema) cachedSchema.get(cls); 25 | if (schema == null) { 26 | schema = RuntimeSchema.createFrom(cls); 27 | if (schema != null) { 28 | cachedSchema.put(cls, schema); 29 | } 30 | } 31 | return schema; 32 | } 33 | 34 | @SuppressWarnings("unchecked") 35 | public static byte[] serialize(T obj) { 36 | Class cls = (Class) obj.getClass(); 37 | LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE); 38 | try { 39 | Schema schema = getSchema(cls); 40 | return ProtostuffIOUtil.toByteArray(obj, schema, buffer); 41 | } catch (Exception e) { 42 | throw new IllegalStateException(e.getMessage(), e); 43 | } finally { 44 | buffer.clear(); 45 | } 46 | } 47 | 48 | public static T deserialize(byte[] data, Class cls) { 49 | try { 50 | T message = (T) objenesis.newInstance(cls); 51 | Schema schema = getSchema(cls); 52 | ProtostuffIOUtil.mergeFrom(data, message, schema); 53 | return message; 54 | } catch (Exception e) { 55 | throw new IllegalStateException(e.getMessage(), e); 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /rpc_service/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | rpc 7 | com.github.rockeyhoo 8 | 0.0.1-SNAPSHOT 9 | 10 | 4.0.0 11 | rpc-service 12 | 13 | 14 | 15 | com.github.rockeyhoo 16 | rpc-client 17 | 0.0.1-SNAPSHOT 18 | 19 | 20 | com.github.rockeyhoo 21 | rpc-common 22 | 0.0.1-SNAPSHOT 23 | 24 | 25 | 26 | junit 27 | junit 28 | 29 | 30 | 31 | 32 | org.slf4j 33 | slf4j-log4j12 34 | 35 | 36 | 37 | 38 | org.springframework 39 | spring-context 40 | 41 | 42 | org.springframework 43 | spring-test 44 | 45 | 46 | 47 | 48 | io.netty 49 | netty-all 50 | 51 | 52 | 53 | 54 | com.dyuproject.protostuff 55 | protostuff-core 56 | 57 | 58 | com.dyuproject.protostuff 59 | protostuff-runtime 60 | 61 | 62 | 63 | 64 | org.apache.zookeeper 65 | zookeeper 66 | 67 | 68 | 69 | 70 | org.apache.commons 71 | commons-collections4 72 | 73 | 74 | 75 | 76 | org.objenesis 77 | objenesis 78 | 79 | 80 | 81 | 82 | cglib 83 | cglib 84 | 85 | 86 | 87 | 88 | 89 | 90 | org.apache.maven.plugins 91 | maven-compiler-plugin 92 | 93 | 94 | 95 | org.apache.maven.plugins 96 | maven-release-plugin 97 | 98 | 99 | 100 | -------------------------------------------------------------------------------- /rpc_service/src/main/java/com/github/roockey/rpc/service/core/RpcBootstrap.java: -------------------------------------------------------------------------------- 1 | package com.github.roockey.rpc.service.core; 2 | 3 | import org.springframework.context.support.ClassPathXmlApplicationContext; 4 | 5 | public class RpcBootstrap { 6 | @SuppressWarnings("resource") 7 | public static void main(String[] args) { 8 | new ClassPathXmlApplicationContext("spring-server.xml"); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /rpc_service/src/main/java/com/github/roockey/rpc/service/core/RpcHandler.java: -------------------------------------------------------------------------------- 1 | package com.github.roockey.rpc.service.core; 2 | 3 | import io.netty.channel.ChannelFutureListener; 4 | import io.netty.channel.ChannelHandlerContext; 5 | import io.netty.channel.SimpleChannelInboundHandler; 6 | 7 | import java.util.Map; 8 | 9 | import net.sf.cglib.reflect.FastClass; 10 | import net.sf.cglib.reflect.FastMethod; 11 | 12 | import org.slf4j.Logger; 13 | import org.slf4j.LoggerFactory; 14 | import com.github.rockeyhoo.rpc.client.RpcRequest; 15 | import com.github.rockeyhoo.rpc.client.RpcResponse; 16 | 17 | public class RpcHandler extends SimpleChannelInboundHandler { 18 | 19 | private static final Logger LOGGER = LoggerFactory.getLogger(RpcHandler.class); 20 | 21 | private final Map handlerMap; 22 | 23 | public RpcHandler(Map handlerMap) { 24 | this.handlerMap = handlerMap; 25 | } 26 | 27 | @Override 28 | public void channelRead0(final ChannelHandlerContext ctx, RpcRequest request) throws Exception { 29 | RpcResponse response = new RpcResponse(); 30 | response.setRequestId(request.getRequestId()); 31 | try { 32 | Object result = handle(request); 33 | response.setResult(result); 34 | } catch (Throwable t) { 35 | response.setError(t); 36 | } 37 | ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); 38 | } 39 | 40 | private Object handle(RpcRequest request) throws Throwable { 41 | String className = request.getClassName(); 42 | Object serviceBean = handlerMap.get(className); 43 | 44 | Class serviceClass = serviceBean.getClass(); 45 | String methodName = request.getMethodName(); 46 | Class[] parameterTypes = request.getParameterTypes(); 47 | Object[] parameters = request.getParameters(); 48 | 49 | /* 50 | * Method method = serviceClass.getMethod(methodName, parameterTypes); 51 | * method.setAccessible(true); return method.invoke(serviceBean, 52 | * parameters); 53 | */ 54 | 55 | FastClass serviceFastClass = FastClass.create(serviceClass); 56 | FastMethod serviceFastMethod = serviceFastClass.getMethod(methodName, parameterTypes); 57 | return serviceFastMethod.invoke(serviceBean, parameters); 58 | } 59 | 60 | @Override 61 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { 62 | LOGGER.error("server caught exception", cause); 63 | ctx.close(); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /rpc_service/src/main/java/com/github/roockey/rpc/service/core/RpcServer.java: -------------------------------------------------------------------------------- 1 | package com.github.roockey.rpc.service.core; 2 | 3 | import io.netty.bootstrap.ServerBootstrap; 4 | import io.netty.channel.ChannelFuture; 5 | import io.netty.channel.ChannelInitializer; 6 | import io.netty.channel.ChannelOption; 7 | import io.netty.channel.EventLoopGroup; 8 | import io.netty.channel.nio.NioEventLoopGroup; 9 | import io.netty.channel.socket.SocketChannel; 10 | import io.netty.channel.socket.nio.NioServerSocketChannel; 11 | 12 | import java.util.HashMap; 13 | import java.util.Map; 14 | 15 | import org.apache.commons.collections4.MapUtils; 16 | import org.slf4j.Logger; 17 | import org.slf4j.LoggerFactory; 18 | import org.springframework.beans.BeansException; 19 | import org.springframework.beans.factory.InitializingBean; 20 | import org.springframework.context.ApplicationContext; 21 | import org.springframework.context.ApplicationContextAware; 22 | 23 | import com.github.rockeyhoo.rpc.client.RpcRequest; 24 | import com.github.rockeyhoo.rpc.client.RpcResponse; 25 | import com.github.rockeyhoo.rpc.common.RpcDecoder; 26 | 27 | public class RpcServer implements ApplicationContextAware, InitializingBean { 28 | 29 | private static final Logger LOGGER = LoggerFactory.getLogger(RpcServer.class); 30 | 31 | private String serverAddress; 32 | private ServiceRegistry serviceRegistry; 33 | 34 | private Map handlerMap = new HashMap(); // 存放接口名与服务对象之间的映射关系 35 | 36 | public RpcServer(String serverAddress) { 37 | this.serverAddress = serverAddress; 38 | } 39 | 40 | public RpcServer(String serverAddress, ServiceRegistry serviceRegistry) { 41 | this.serverAddress = serverAddress; 42 | this.serviceRegistry = serviceRegistry; 43 | } 44 | 45 | @Override 46 | public void setApplicationContext(ApplicationContext ctx) throws BeansException { 47 | // 获取所有带有RpcService注解的SpringBean 48 | Map serviceBeanMap = ctx.getBeansWithAnnotation(RpcService.class); 49 | if (MapUtils.isNotEmpty(serviceBeanMap)) { 50 | for (Object serviceBean : serviceBeanMap.values()) { 51 | String interfaceName = serviceBean.getClass().getAnnotation(RpcService.class).value().getName(); 52 | handlerMap.put(interfaceName, serviceBean); 53 | } 54 | } 55 | } 56 | 57 | @Override 58 | public void afterPropertiesSet() throws Exception { 59 | EventLoopGroup bossGroup = new NioEventLoopGroup(); 60 | EventLoopGroup workerGroup = new NioEventLoopGroup(); 61 | try { 62 | ServerBootstrap bootstrap = new ServerBootstrap(); 63 | bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) 64 | .childHandler(new ChannelInitializer() { 65 | @Override 66 | public void initChannel(SocketChannel channel) throws Exception { 67 | channel.pipeline().addLast(new RpcDecoder(RpcRequest.class)) // 将 68 | // RPC 69 | // 请求进行解码(为了处理请求) 70 | .addLast(new RpcDecoder(RpcResponse.class)) // 将 71 | // RPC 72 | // 响应进行编码(为了返回响应) 73 | .addLast(new RpcHandler(handlerMap)); // 处理 74 | // RPC 75 | // 请求 76 | } 77 | }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true); 78 | 79 | String[] array = serverAddress.split(":"); 80 | String host = array[0]; 81 | int port = Integer.parseInt(array[1]); 82 | 83 | ChannelFuture future = bootstrap.bind(host, port).sync(); 84 | LOGGER.debug("server started on port {}", port); 85 | 86 | if (serviceRegistry != null) { 87 | serviceRegistry.register(serverAddress); // 注册服务地址 88 | } 89 | 90 | future.channel().closeFuture().sync(); 91 | } finally { 92 | workerGroup.shutdownGracefully(); 93 | bossGroup.shutdownGracefully(); 94 | } 95 | } 96 | 97 | } 98 | -------------------------------------------------------------------------------- /rpc_service/src/main/java/com/github/roockey/rpc/service/core/RpcService.java: -------------------------------------------------------------------------------- 1 | package com.github.roockey.rpc.service.core; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | import org.springframework.stereotype.Component; 9 | 10 | @Target({ ElementType.TYPE }) 11 | @Retention(RetentionPolicy.RUNTIME) 12 | @Component 13 | // 表明可被 Spring 扫描 14 | public @interface RpcService { 15 | 16 | Class value(); 17 | } 18 | -------------------------------------------------------------------------------- /rpc_service/src/main/java/com/github/roockey/rpc/service/core/ServiceRegistry.java: -------------------------------------------------------------------------------- 1 | package com.github.roockey.rpc.service.core; 2 | 3 | import java.io.IOException; 4 | import java.util.concurrent.CountDownLatch; 5 | 6 | import org.apache.zookeeper.CreateMode; 7 | import org.apache.zookeeper.KeeperException; 8 | import org.apache.zookeeper.WatchedEvent; 9 | import org.apache.zookeeper.Watcher; 10 | import org.apache.zookeeper.ZooDefs; 11 | import org.apache.zookeeper.ZooKeeper; 12 | import org.slf4j.Logger; 13 | import org.slf4j.LoggerFactory; 14 | import com.github.rockeyhoo.rpc.common.Constant; 15 | 16 | 17 | public class ServiceRegistry { 18 | 19 | private static final Logger LOGGER = LoggerFactory.getLogger(ServiceRegistry.class); 20 | 21 | private CountDownLatch latch = new CountDownLatch(1); 22 | 23 | private String registryAddress; 24 | 25 | public ServiceRegistry(String registryAddress) { 26 | this.registryAddress = registryAddress; 27 | } 28 | 29 | public void register(String data) { 30 | if (data != null) { 31 | ZooKeeper zk = connectServer(); 32 | if (zk != null) { 33 | createNode(zk, data); 34 | } 35 | } 36 | } 37 | 38 | private ZooKeeper connectServer() { 39 | ZooKeeper zk = null; 40 | try { 41 | zk = new ZooKeeper(registryAddress, Constant.ZK_SESSION_TIMEOUT, new Watcher() { 42 | 43 | public void process(WatchedEvent event) { 44 | if (event.getState() == Event.KeeperState.SyncConnected) { 45 | latch.countDown(); 46 | } 47 | } 48 | }); 49 | latch.await(); 50 | } catch (IOException | InterruptedException e) { 51 | LOGGER.error("", e); 52 | } 53 | return zk; 54 | } 55 | 56 | private void createNode(ZooKeeper zk, String data) { 57 | try { 58 | byte[] bytes = data.getBytes(); 59 | String path = zk.create(Constant.ZK_DATA_PATH, bytes, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL); 60 | LOGGER.debug("create zookeeper node ({} => {})", path, data); 61 | } catch (KeeperException | InterruptedException e) { 62 | LOGGER.error("", e); 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /rpc_service/src/main/java/com/github/roockey/rpc/service/modules/simple/HelloService.java: -------------------------------------------------------------------------------- 1 | package com.github.roockey.rpc.service.modules.simple; 2 | 3 | public interface HelloService { 4 | 5 | String hello(String name); 6 | } 7 | -------------------------------------------------------------------------------- /rpc_service/src/main/java/com/github/roockey/rpc/service/modules/simple/impl/HelloServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.github.roockey.rpc.service.modules.simple.impl; 2 | 3 | import com.github.roockey.rpc.service.core.RpcService; 4 | import com.github.roockey.rpc.service.modules.simple.HelloService; 5 | 6 | // 指定远程接口 7 | @RpcService(HelloService.class) 8 | public class HelloServiceImpl implements HelloService { 9 | 10 | @Override 11 | public String hello(String name) { 12 | return "Hello! " + name; 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /rpc_service/src/main/resources/server-config.properties: -------------------------------------------------------------------------------- 1 | # ZooKeeper \u670d\u52a1\u5668 2 | registry.address=127.0.0.1:2181 3 | # RPC \u670d\u52a1\u5668 4 | server.address=127.0.0.1:8000 -------------------------------------------------------------------------------- /rpc_service/src/main/resources/spring-server.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /rpc_simple/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | rpc 7 | com.github.rockeyhoo 8 | 0.0.1-SNAPSHOT 9 | 10 | 4.0.0 11 | rpc-simple 12 | 13 | 14 | 15 | com.github.rockeyhoo 16 | rpc-client 17 | 0.0.1-SNAPSHOT 18 | 19 | 20 | 21 | com.github.rockeyhoo 22 | rpc-service 23 | 0.0.1-SNAPSHOT 24 | 25 | 26 | junit 27 | junit 28 | test 29 | 30 | 31 | org.springframework 32 | spring-test 33 | test 34 | 35 | 36 | org.springframework 37 | spring-context 38 | 39 | 40 | 41 | 42 | 43 | 44 | org.apache.maven.plugins 45 | maven-compiler-plugin 46 | 47 | 48 | 49 | org.apache.maven.plugins 50 | maven-release-plugin 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /rpc_simple/src/test/java/com/github/rockeyhoo/rpc/simple/HelloServiceTest.java: -------------------------------------------------------------------------------- 1 | package com.github.rockeyhoo.rpc.simple; 2 | 3 | import com.github.rockeyhoo.rpc.client.RpcProxy; 4 | import com.github.roockey.rpc.service.modules.simple.HelloService; 5 | import org.junit.Assert; 6 | import org.junit.Test; 7 | import org.junit.runner.RunWith; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.test.context.ContextConfiguration; 10 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 11 | 12 | 13 | @RunWith(SpringJUnit4ClassRunner.class) 14 | @ContextConfiguration(locations = "classpath:spring-client.xml") 15 | public class HelloServiceTest { 16 | 17 | @Autowired 18 | private RpcProxy rpcProxy; 19 | 20 | @Test 21 | public void helloTest() { 22 | try { 23 | HelloService helloService = rpcProxy.create(HelloService.class); 24 | String result = helloService.hello("World"); 25 | Assert.assertEquals("Hello! World", result); 26 | } catch (Exception e) { 27 | e.printStackTrace(); 28 | } 29 | } 30 | 31 | } 32 | --------------------------------------------------------------------------------