Repository: xincao9/jsonrpc Branch: master Commit: 51e5f954ca31 Files: 53 Total size: 136.4 KB Directory structure: gitextract_u_twoy7l/ ├── .gitignore ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── pom.xml ├── yurpc-core/ │ ├── pom.xml │ └── src/ │ ├── main/ │ │ └── java/ │ │ └── com/ │ │ └── github/ │ │ └── xincao9/ │ │ └── yurpc/ │ │ └── core/ │ │ ├── DiscoveryService.java │ │ ├── YuRPCClient.java │ │ ├── YuRPCServer.java │ │ ├── codec/ │ │ │ ├── StringDecoder.java │ │ │ └── StringEncoder.java │ │ ├── config/ │ │ │ ├── ClientConfig.java │ │ │ └── ServerConfig.java │ │ ├── constant/ │ │ │ ├── ClientConsts.java │ │ │ ├── ResponseCode.java │ │ │ ├── ServerConsts.java │ │ │ └── SystemConsts.java │ │ ├── impl/ │ │ │ ├── ClientHandler.java │ │ │ ├── ClientInvocationHandler.java │ │ │ ├── HeartbeatHandler.java │ │ │ ├── ServerHandler.java │ │ │ ├── YuRPCClientImpl.java │ │ │ └── YuRPCServerImpl.java │ │ ├── protocol/ │ │ │ ├── Endpoint.java │ │ │ ├── Pair.java │ │ │ ├── Request.java │ │ │ └── Response.java │ │ └── util/ │ │ ├── HostUtils.java │ │ └── PropertiesUtils.java │ └── test/ │ ├── java/ │ │ └── com/ │ │ └── github/ │ │ └── xincao9/ │ │ └── yurpc/ │ │ └── YuRPCServerTest.java │ └── resources/ │ └── config.properties ├── yurpc-sample/ │ ├── dependency-reduced-pom.xml │ ├── pom.xml │ └── src/ │ └── main/ │ ├── java/ │ │ └── com/ │ │ └── github/ │ │ └── xincao9/ │ │ └── yurpc/ │ │ └── sample/ │ │ ├── Say.java │ │ ├── SayService.java │ │ ├── consumer/ │ │ │ ├── ApplicationConsumer.java │ │ │ ├── Benchmark.java │ │ │ ├── Consumer.java │ │ │ └── SayMethod.java │ │ └── provider/ │ │ ├── ApplicationProvider.java │ │ ├── Provider.java │ │ └── SayServiceImpl.java │ └── resources/ │ ├── application.yml │ └── config.properties └── yurpc-spring-boot-starter/ ├── pom.xml └── src/ └── main/ └── java/ └── com/ └── github/ └── xincao9/ └── yurpc/ └── spring/ └── boot/ └── starter/ ├── ConfigConsts.java ├── EnableYuRPC.java ├── YUConsumer.java ├── YUProvider.java ├── YuRPCAutoConfiguration.java ├── YuRPCBeanPostProcessor.java ├── YuRPCImportBeanDefinitionRegistrar.java └── ZKDiscoveryServiceImpl.java ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ HELP.md target/ !.mvn/wrapper/maven-wrapper.jar !**/src/main/** !**/src/test/** ### STS ### .apt_generated .classpath .factorypath .project .settings .springBeans .sts4-cache ### IntelliJ IDEA ### .idea *.iws *.iml *.ipr ### NetBeans ### /nbproject/private/ /nbbuild/ /dist/ /nbdist/ /.nb-gradle/ build/ ### VS Code ### .vscode/ ================================================ FILE: CONTRIBUTING.md ================================================ Primary developer xincao9@gmail.com ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: README.md ================================================ ## yurpc ### 高性能RPC框架 #### yurpc 基于java的高性能开源RPC框架,使用方式上类似dubbo,提倡面向接口编程,如果您熟悉dubbo很容易迁移到yurpc;并享受高性能带来的服务体验。提供springboot高度集成starter包,实现零配置使用 ![logo](https://github.com/xincao9/yurpc/blob/master/architecture.png) #### yurpc 实战 **_maven 依赖_** ``` com.github.xincao9 yurpc-spring-boot-starter 1.2.6 ``` **_实体定义_** ``` public class Say { private Integer id; private String body; public Say(Integer id, String body) { this.id = id; this.body = body; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getBody() { return body; } public void setBody(String body) { this.body = body; } @Override public String toString() { return JSONObject.toJSONString(this, SerializerFeature.DisableCircularReferenceDetect); } } ``` **_服务接口定义_** ``` public interface SayService { Say perform(Say say); } ``` **_提供者实现服务接口_** ``` @YUProvider public class SayServiceImpl implements SayService { @Override public Say perform(Say say) { return say; } } ``` **_服务提供者启动类_** ``` @SpringBootApplication @EnableYuRPC(server = true) public class ApplicationProvider { public static void main(String... args) { SpringApplication.run(ApplicationProvider.class, args); } } ``` **_服务消费者启动类_** ``` @SpringBootApplication @EnableYuRPC(client = true) public class ApplicationConsumer { @YUConsumer private SayService sayService; // 可以在任何spring bean 中注入yurpc服务 public static void main(String... args) { SpringApplication.run(ApplicationConsumer.class, args); } @Bean public CommandLineRunner commandLineRunner() { return (String... args) -> { for (int no = 0; no < 100; no++) { String value = RandomStringUtils.randomAscii(128); Say say = new Say(no, value); System.out.println(sayService.perform(say)); // 远程调用yurpc服务 } }; } } ``` **_application.properties_** ``` ## 服务发现注册或订阅的zk地址,暂时只支持zookeeper的注册中心 yurpc.discovery.zookeeper=localhost:2181 ## 消费者配置 yurpc.client.connectionTimeoutMS=5000 // 服务连接超时时间 yurpc.client.invokeTimeoutMS=1000 // 服务调用超时时间 ## 提供者配置 yurpc.server.port=12306 // 服务监听端口 ``` **_温馨提示_** * 欢迎查看示例 [examples](https://github.com/xincao9/yurpc/tree/master/yurpc-sample) * yurpc 本身并不是必须和springboot一起使用,在示例中可以查看 * 单独使用的话,配置文件名为 config.properties,在示例中可以查看 * @EnableYuRPC(server = true, client = true) 意味着服务角色同为消费端和提供者使用 #### 联系方式 * [https://github.com/xincao9/yurpc/issues](https://github.com/xincao9/yurpc/issues) * [https://issues.sonatype.org/browse/OSSRH-47112](https://issues.sonatype.org/browse/OSSRH-47112) * xincao9@gmail.com ================================================ FILE: pom.xml ================================================ 4.0.0 com.github.xincao9 yurpc yurpc 1.2.6 pom high-performance RPC framework. UTF-8 1.8 1.8 com.github.xincao9 yurpc-core ${project.version} com.github.xincao9 yurpc-spring-boot-starter ${project.version} yurpc-core yurpc-spring-boot-starter yurpc-sample https://github.com/xincao9/yurpc xincao9@gmail.com xin.cao owner https://github.com/xincao9 xincao9 https://github.com/xincao9/ Personal https://github.com/xincao9 Github Issues https://github.com/xincao9/yurpc/issues The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt repo master git@github.com:xincao9/yurpc.git scm:git:git@github.com:xincao9/yurpc.git scm:git:git@github.com:xincao9/yurpc.git sonatype-oss https://oss.sonatype.org/service/local/staging/deploy/maven2 sonatype-oss https://oss.sonatype.org/content/repositories/snapshots release org.sonatype.plugins nexus-staging-maven-plugin 1.6.8 true sonatype-oss https://oss.sonatype.org/ true org.apache.maven.plugins maven-gpg-plugin 1.6 sign-artifacts verify sign org.apache.maven.plugins maven-source-plugin 3.0.1 package jar-no-fork org.apache.maven.plugins maven-javadoc-plugin 3.1.0 package jar ================================================ FILE: yurpc-core/pom.xml ================================================ 4.0.0 com.github.xincao9 yurpc 1.2.6 yurpc-core jar yurpc-core high-performance RPC framework. UTF-8 1.8 1.8 4.1.50.Final 1.2.71 1.7.25 3.7 1.11 4.13.1 1.23 io.netty netty-all ${netty.version} com.alibaba fastjson ${fastjson.version} org.slf4j jcl-over-slf4j ${slf4j.version} org.slf4j jul-to-slf4j ${slf4j.version} org.slf4j log4j-over-slf4j ${slf4j.version} org.slf4j slf4j-api ${slf4j.version} org.apache.commons commons-lang3 ${commons-lang3.version} commons-codec commons-codec ${commons-codec.version} junit junit ${junit.version} org.openjdk.jmh jmh-core ${jmh.version} org.openjdk.jmh jmh-generator-annprocess ${jmh.version} io.netty netty-all com.alibaba fastjson org.slf4j jcl-over-slf4j org.slf4j jul-to-slf4j org.slf4j log4j-over-slf4j org.slf4j slf4j-api org.apache.commons commons-lang3 commons-codec commons-codec junit junit test org.openjdk.jmh jmh-core test org.openjdk.jmh jmh-generator-annprocess test ================================================ FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/DiscoveryService.java ================================================ /* * Copyright 2020 xincao9@gmail.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.xincao9.yurpc.core; import com.github.xincao9.yurpc.core.protocol.Endpoint; import java.util.List; /** * 服务注册与发现组件 * * @author xincao9@gmail.com */ public interface DiscoveryService { /** * 注册 * * @param endpoint 服务信息 */ void register (Endpoint endpoint); /** * 获取注册表 * * @param service 服务名字(接口名) * @return 节点列表 */ List query (String service); /** * 续约 * * @param instanceId 当前实例的id */ void renew (String instanceId); /** * 取消 * * @param instanceId 当前实例的id */ void cancel (String instanceId); } ================================================ FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/YuRPCClient.java ================================================ /* * Copyright 2020 xincao9@gmail.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.xincao9.yurpc.core; import com.github.xincao9.yurpc.core.config.ClientConfig; import com.github.xincao9.yurpc.core.impl.YuRPCClientImpl; import com.github.xincao9.yurpc.core.protocol.Request; import com.github.xincao9.yurpc.core.protocol.Response; import java.util.Map; /** * 客户端 * * @author xincao9@gmail.com */ public interface YuRPCClient { /** * 调用方法 * * @param 类型 * @param request 请求 * @return 调用结果 * @throws Throwable 异常 */ Response invoke(Request request) throws Throwable; /** * 启动 * * @throws java.lang.Throwable 异常 */ void start() throws Throwable; /** * 关闭 * * @throws java.lang.Throwable 异常 */ void shutdown() throws Throwable; /** * 获得客户端 * * @param filename 配置文件 * @param discoveryService 服务组件 * @return 客户端 */ static YuRPCClient defaultYuRPCClient(String filename, DiscoveryService discoveryService) { ClientConfig.init(filename); return new YuRPCClientImpl(discoveryService); } /** * 获得客户端 * * @return 客户端 */ static YuRPCClient defaultYuRPCClient() { return YuRPCClient.defaultYuRPCClient("", null); } /** * 获得客户端 * * @param discoveryService 服务组件 * @return 客户端 */ static YuRPCClient defaultYuRPCClient(DiscoveryService discoveryService) { return YuRPCClient.defaultYuRPCClient("", discoveryService); } /** * 获得请求对象容器 * * @return 请求对象容器 */ Map getRequests(); /** * 获得接口的代理 * * @param 类型 * @param clazz 接口 * @return 代理对象 */ T proxy(Class clazz); /** * 修改器 * * @param discoveryService 服务发现和注册组件 */ void setDiscoveryService(DiscoveryService discoveryService); } ================================================ FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/YuRPCServer.java ================================================ /* * Copyright 2020 xincao9@gmail.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.xincao9.yurpc.core; import com.github.xincao9.yurpc.core.impl.YuRPCServerImpl; import com.github.xincao9.yurpc.core.config.ServerConfig; /** * 服务组件 * * @author xincao9@gmail.com */ public interface YuRPCServer { /** * 启动 * * @throws java.lang.Throwable */ void start() throws Throwable; /** * 关闭 * * @throws java.lang.Throwable */ void shutdown() throws Throwable; /** * 获得服务端 * * @param filename 配置文件名 * @param discovery 服务发现组件 * @return 服务端 */ static YuRPCServer defaultYuRPCServer(String filename, DiscoveryService discovery) throws RuntimeException { ServerConfig.init(filename); return new YuRPCServerImpl(discovery); } /** * 获得服务端 * * @return 服务端 */ static YuRPCServer defaultYuRPCServer() { return YuRPCServer.defaultYuRPCServer("", null); } /** * 获得服务端 * * @param port 端口 * @param discoveryService 服务发现组件 * @return */ static YuRPCServer defaultYuRPCServer(Integer port, DiscoveryService discoveryService) { ServerConfig.port = port; return new YuRPCServerImpl(port, discoveryService); } /** * 获得服务端 * * @param filename 配置文件名 * @return 服务端 */ static YuRPCServer defaultYuRPCServer(String filename) { return YuRPCServer.defaultYuRPCServer(filename, null); } /** * 获得服务端 * * @param discovery 服务发现组件 * @return 服务端 */ static YuRPCServer defaultYuRPCServer(DiscoveryService discovery) { return YuRPCServer.defaultYuRPCServer("", discovery); } /** * 服务注册 * * @param 组建类型 * @param obj 服务组件 */ void register(T obj); /** * 获取组建 * * @param name 组建类型名 * @return 服务组件 */ Object getBean(String name); /** * 修改器 * * @param discoveryService 服务发现和注册组件 */ void setDiscoveryService(DiscoveryService discoveryService); } ================================================ FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/codec/StringDecoder.java ================================================ /* * Copyright 2020 xincao9@gmail.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.xincao9.yurpc.core.codec; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.ByteToMessageDecoder; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.List; /** * 消息解码 * * @author xincao9@gmail.com */ public class StringDecoder extends ByteToMessageDecoder { /** * 解码 * * @param chc * @param byteBuf * @param list * @throws Exception */ @Override protected void decode(ChannelHandlerContext chc, ByteBuf byteBuf, List list) throws Exception { try { do { int readerIndex = byteBuf.readerIndex(); int readableBytesSize = byteBuf.readableBytes(); if (readableBytesSize < 4) { byteBuf.readerIndex(readerIndex); break; } int size = byteBuf.readInt(); if (readableBytesSize - 4 < size) { byteBuf.readerIndex(readerIndex); break; } byteBuf.readerIndex(readerIndex); ByteBuffer byteBuffer = ByteBuffer.allocate(4 + size); byteBuf.readBytes(byteBuffer); byte[] data = byteBuffer.array(); byte[] body = Arrays.copyOfRange(data, 4, data.length); list.add(new String(body, "UTF-8")); } while (byteBuf.isReadable()); } finally { if (byteBuf.isReadable()) { byteBuf.discardReadBytes(); } } } } ================================================ FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/codec/StringEncoder.java ================================================ /* * Copyright 2020 xincao9@gmail.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.xincao9.yurpc.core.codec; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.MessageToByteEncoder; import java.util.Objects; import org.apache.commons.lang3.StringUtils; /** * 消息编码 * * @author xincao9@gmail.com */ public class StringEncoder extends MessageToByteEncoder { /** * 编码 * * @param chc * @param object * @param byteBuf * @throws Exception */ @Override protected void encode(ChannelHandlerContext chc, Object object, ByteBuf byteBuf) throws Exception { Objects.requireNonNull(object); if (!(object instanceof String)) { return; } String str = (String) object; if (StringUtils.isBlank(str)) { return; } byte[] data = str.getBytes("UTF-8"); byteBuf.writeInt(data.length); byteBuf.writeBytes(data); } } ================================================ FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/config/ClientConfig.java ================================================ /* * Copyright 2020 xincao9@gmail.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.xincao9.yurpc.core.config; import com.github.xincao9.yurpc.core.protocol.Pair; import com.github.xincao9.yurpc.core.constant.ClientConsts; import com.github.xincao9.yurpc.core.constant.SystemConsts; import com.github.xincao9.yurpc.core.util.PropertiesUtils; import java.util.ArrayList; import java.util.List; import java.util.Properties; /** * 客户端配置 * * @author xincao9@gmail.com */ public class ClientConfig { public static List> serverList = new ArrayList(1); public static Integer connectionTimeoutMS; public static Integer invokeTimeoutMS; /** * 初始化客户端配置 * * @param filename 配置文件名 */ public static void init(String filename) { Properties pros = PropertiesUtils.read(filename, SystemConsts.DEFAULT_CONFIG_FILENAME); init(pros); } /** * 初始化客户端配置 * * @param pros 属性文件 */ public static void init(Properties pros) { String serverListStr = pros.getProperty(ClientConsts.SERVER_LIST, ClientConsts.DEFAULT_SERVER_LIST); String[] servers = serverListStr.split(","); for (String server : servers) { serverList.add(new Pair(server.split(":")[0], Integer.valueOf(server.split(":")[1]))); } connectionTimeoutMS = Integer.valueOf(pros.getProperty(ClientConsts.CONNECTION_TIMEOUT_MS, ClientConsts.DEFAULT_CONNECTION_TIMEOUT_MS)); invokeTimeoutMS = Integer.valueOf(pros.getProperty(ClientConsts.INVOKE_TIMEOUT_MS, ClientConsts.DEFAULT_INVOKE_TIMEOUT_MS)); } } ================================================ FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/config/ServerConfig.java ================================================ /* * Copyright 2020 xincao9@gmail.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.xincao9.yurpc.core.config; import com.github.xincao9.yurpc.core.constant.ServerConsts; import com.github.xincao9.yurpc.core.constant.SystemConsts; import com.github.xincao9.yurpc.core.util.PropertiesUtils; import java.util.Properties; /** * 服务配置类 * * @author xincao9@gmail.com */ public class ServerConfig { public static Integer port; public static Integer ioThreadBoss = ServerConsts.DEFAULT_IO_THREAD_BOSS; public static Integer ioThreadWorker = ServerConsts.DEFAULT_IO_THREAD_WORKER; /** * 初始化服务组件配置 * * @param filename 配置文件名 */ public static void init(String filename) { Properties pros = PropertiesUtils.read(filename, SystemConsts.DEFAULT_CONFIG_FILENAME); init(pros); } /** * 初始化服务组件配置 * * @param pros 属性文件 */ public static void init(Properties pros) { port = Integer.valueOf(pros.getProperty(ServerConsts.PORT, ServerConsts.DEFAULT_PORT)); if (port <= 0 || port > 65535) { port = Integer.valueOf(ServerConsts.DEFAULT_PORT); } } } ================================================ FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/constant/ClientConsts.java ================================================ /* * Copyright 2020 xincao9@gmail.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.xincao9.yurpc.core.constant; /** * 客户端常量 * * @author xincao9@gmail.com */ public class ClientConsts { public static final String SERVER_LIST = "yurpc.client.serverList"; public static final String DEFAULT_SERVER_LIST = "127.0.0.1:12306"; public static final String CONNECTION_TIMEOUT_MS = "yurpc.client.connectionTimeoutMS"; public static final String DEFAULT_CONNECTION_TIMEOUT_MS = "5000"; public static final String INVOKE_TIMEOUT_MS = "yurpc.client.invokeTimeoutMS"; public static final String DEFAULT_INVOKE_TIMEOUT_MS = "1000"; } ================================================ FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/constant/ResponseCode.java ================================================ /* * Copyright 2020 xincao9@gmail.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.xincao9.yurpc.core.constant; /** * 响应码 * * @author xincao9@gmail.com */ public class ResponseCode { public static final Integer OK = 0; public static final String OK_MSG = "OK"; public static final Integer INVOKE_TIMEOUT = 1; public static final String INVOKE_TIMEOUT_MSG = "INVOKE TIMEOUT"; public static final Integer CONNECTION_FAILURE = 2; public static final String CONNECTION_FAILURE_MSG = "CONNECTION FAILURE"; public static final Integer SERVER_ERROR = 3; public static final String SERVER_ERROR_MSG = "SERVER ERROR"; public static final Integer PARAMETER_ERROR = 4; public static final String PARAMETER_ERROR_MSG = "PARAMETER ERROR"; public static final Integer NOT_FOUND_COMPONENT = 5; public static final String NOT_FOUND_COMPONENT_MSG = "COMPONENT CLASS: %s NOT FOUND"; public static final Integer NOT_FOUND_METHOD = 6; public static final String NOT_FOUND_METHOD_MSG = "CLASS: %s METHOD: %s NOT FOUND!"; } ================================================ FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/constant/ServerConsts.java ================================================ /* * Copyright 2020 xincao9@gmail.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.xincao9.yurpc.core.constant; /** * 服务端常量 * * @author xincao9@gmail.com */ public class ServerConsts { public static final String PORT = "yurpc.server.port"; public static final String DEFAULT_PORT = "12306"; public static final Integer DEFAULT_IO_THREAD_BOSS = 1; public static final Integer DEFAULT_IO_THREAD_WORKER = Runtime.getRuntime().availableProcessors(); } ================================================ FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/constant/SystemConsts.java ================================================ /* * Copyright 2020 xincao9@gmail.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.xincao9.yurpc.core.constant; /** * * @author xincao9@gmail.com */ public class SystemConsts { public static final String DEFAULT_CONFIG_FILENAME = "/config.properties"; } ================================================ FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/impl/ClientHandler.java ================================================ /* * Copyright 2020 xincao9@gmail.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.xincao9.yurpc.core.impl; import com.github.xincao9.yurpc.core.YuRPCClient; import com.github.xincao9.yurpc.core.protocol.Request; import com.alibaba.fastjson.JSONObject; import com.github.xincao9.yurpc.core.protocol.Response; import io.netty.channel.ChannelHandler.Sharable; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 客户端输入流处理器 * * @author xincao9@gmail.com */ @Sharable public class ClientHandler extends SimpleChannelInboundHandler { private static final Logger LOGGER = LoggerFactory.getLogger(ClientHandler.class); private YuRPCClient yuRPCClient; /** * 读取输入流处理 * * @param ctx channel上下文 * @param msg 消息 * @throws Exception 异常 */ @Override protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { Response response = JSONObject.parseObject(msg, Response.class); LOGGER.debug("msg = {}", msg); long responseId = response.getId(); Map requests = yuRPCClient.getRequests(); if (requests.containsKey(responseId)) { Request request = requests.get(responseId); requests.remove(responseId); request.putResponse(response); } } /** * 修改器 * * @param yuRPCClient 客户端 */ public void setYuRPCClient(YuRPCClient yuRPCClient) { this.yuRPCClient = yuRPCClient; } } ================================================ FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/impl/ClientInvocationHandler.java ================================================ /* * Copyright 2020 xincao9@gmail.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.xincao9.yurpc.core.impl; import com.github.xincao9.yurpc.core.YuRPCClient; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.serializer.SerializerFeature; import com.github.xincao9.yurpc.core.protocol.Request; import com.github.xincao9.yurpc.core.protocol.Response; import com.github.xincao9.yurpc.core.constant.ResponseCode; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.lang.reflect.Type; import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 客户端调用代理 * * @author xincao9@gmail.com */ public class ClientInvocationHandler implements InvocationHandler { private static final Logger LOGGER = LoggerFactory.getLogger(ClientInvocationHandler.class); private YuRPCClient yuRPCClient; private final Map proxies = new ConcurrentHashMap(); /** * 代理方法调用 * * @param proxy 代理对象 * @param method 调用的方法 * @param args 调用方法的参数 * @return 调用方法的结果 * @throws Throwable 异常 */ @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { StringBuilder sb = new StringBuilder(); sb.append(method.getDeclaringClass().getTypeName()).append('.'); sb.append(method.getName()); Type returnType = method.getReturnType(); Request request; String[] paramTypes = null; Class[] clazzParamTypes = method.getParameterTypes(); if (clazzParamTypes != null && clazzParamTypes.length > 0) { paramTypes = new String[clazzParamTypes.length]; for (int i = 0; i < clazzParamTypes.length; i++) { paramTypes[i] = clazzParamTypes[i].getTypeName(); } } if ("void".equalsIgnoreCase(returnType.getTypeName())) { request = Request.createRequest(Boolean.FALSE, sb.toString(), args); } else { request = Request.createRequest(Boolean.TRUE, sb.toString(), args); } request.setParamTypes(paramTypes); long startTime = System.currentTimeMillis(); Response response = yuRPCClient.invoke(request); if (response == null) { return null; } LOGGER.debug("requestId = {}, invoke costTime = {}", request.getId(), System.currentTimeMillis() - startTime); LOGGER.debug("requestId = {}, c to s costTime = {} ms, s to c costTime {} ms", request.getId(), response.getCreateTime() - request.getCreateTime(), System.currentTimeMillis() - response.getCreateTime()); if (Objects.equals(response.getCode(), ResponseCode.OK) && !"void".equalsIgnoreCase(returnType.getTypeName())) { if (response.getData() == null) { return null; } Class clazz = Class.forName(returnType.getTypeName()); return JSON.parseObject(JSONObject.toJSONString(response.getData(), SerializerFeature.DisableCircularReferenceDetect), clazz); } if (!Objects.equals(response.getCode(), ResponseCode.OK)) { LOGGER.error("request = {}, code = {}, msg = {}", request, response.getCode(), response.getMsg()); throw new RuntimeException(response.getMsg()); } return null; } /** * 获得接口代理对象 * * @param 接口类型 * @param clazz 接口 * @return 接口的代理类 */ public T proxy(Class clazz) { if (!clazz.isInterface()) { LOGGER.error("{} is not interface", clazz.getCanonicalName()); return null; } if (proxies.containsKey(clazz)) { return (T) proxies.get(clazz); } Object proxy = Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz}, this); proxies.put(clazz, proxy); return (T) proxy; } /** * 修改器 * * @param yuRPCClient 客户端 */ public void setYuRPCClient(YuRPCClient yuRPCClient) { this.yuRPCClient = yuRPCClient; } } ================================================ FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/impl/HeartbeatHandler.java ================================================ /* * Copyright 2020 xincao9@gmail.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.xincao9.yurpc.core.impl; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandler.Sharable; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.handler.timeout.IdleStateEvent; import io.netty.util.CharsetUtil; /** * 心跳处理器 * * @author xincao9@gmail.com */ @Sharable public class HeartbeatHandler extends ChannelInboundHandlerAdapter { private static final ByteBuf HEARTBEAT_SEQUENCE = Unpooled.unreleasableBuffer(Unpooled.copiedBuffer("HEARTBEAT", CharsetUtil.UTF_8)); /** * 事件触发 * * @param ctx 上下文 * @param evt 事件对象 * @throws Exception 异常 */ @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof IdleStateEvent) { ctx.writeAndFlush(HEARTBEAT_SEQUENCE.duplicate()).addListener(ChannelFutureListener.CLOSE_ON_FAILURE); } else { super.userEventTriggered(ctx, evt); } } } ================================================ FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/impl/ServerHandler.java ================================================ /* * Copyright 2020 xincao9@gmail.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.xincao9.yurpc.core.impl; import com.github.xincao9.yurpc.core.YuRPCServer; import com.alibaba.fastjson.JSONObject; import com.github.xincao9.yurpc.core.protocol.Request; import com.github.xincao9.yurpc.core.protocol.Response; import com.github.xincao9.yurpc.core.constant.ResponseCode; import io.netty.channel.ChannelHandler.Sharable; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import java.lang.reflect.Method; import java.util.Map; import java.util.concurrent.*; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 服务输入流处理 * * @author xincao9@gmail.com */ @Sharable public class ServerHandler extends SimpleChannelInboundHandler { private static final Logger LOGGER = LoggerFactory.getLogger(ServerHandler.class); private YuRPCServer yuRPCServer; private final ThreadPoolExecutor processor; private final Map nameClass = new ConcurrentHashMap(); public ServerHandler() { processor = new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors(), 256, 60L, TimeUnit.SECONDS, new SynchronousQueue<>(), new ThreadPoolExecutor.CallerRunsPolicy()); } private void submit(Boolean requestType, Method method, Long rid, Object component, Object[] params, ChannelHandlerContext ctx) { processor.submit(() -> { exec(requestType, method, rid, component, params, ctx); }); } private void exec(Boolean requestType, Method method, Long rid, Object component, Object[] params, ChannelHandlerContext ctx) { try { Response response; if (requestType) { response = Response.createResponse(rid, method.invoke(component, params)); } else { method.invoke(component, params); response = Response.createResponse(rid, null); } ctx.channel().writeAndFlush(response.toString()); } catch (Throwable e) { LOGGER.error(e.getMessage()); exception(ctx, rid, ResponseCode.SERVER_ERROR, e.getMessage()); } } /** * 处理请求 * * @param ctx 上下文 * @param str 消息体 * @throws Exception 异常 */ @Override protected void channelRead0(ChannelHandlerContext ctx, String str) throws Exception { Request request = JSONObject.parseObject(str, Request.class); if (request.getEventType()) { return; } long rid = request.getId(); try { String name = request.getMethod(); if (StringUtils.isBlank(name)) { exception(ctx, rid, ResponseCode.PARAMETER_ERROR, ResponseCode.PARAMETER_ERROR_MSG); return; } String classname = StringUtils.substringBeforeLast(name, "."); String methodname = StringUtils.substringAfterLast(name, "."); Object component = yuRPCServer.getBean(classname); if (component == null) { exception(ctx, rid, ResponseCode.NOT_FOUND_COMPONENT, String.format(ResponseCode.NOT_FOUND_COMPONENT_MSG, classname)); return; } String[] paramTypes = request.getParamTypes(); Class clazz = getClass(classname); Method method; Object[] params = null; if (paramTypes == null || paramTypes.length <= 0) { method = clazz.getMethod(methodname); } else { Class[] clazzes = new Class[paramTypes.length]; params = new Object[paramTypes.length]; for (int i = 0; i < paramTypes.length; i++) { clazzes[i] = getClass(paramTypes[i]); if (request.getParams() != null && request.getParams()[i] != null) { params[i] = JSONObject.parseObject(JSONObject.toJSONString(request.getParams()[i]), clazzes[i]); } } method = clazz.getMethod(methodname, clazzes); } if (method == null) { exception(ctx, rid, ResponseCode.NOT_FOUND_METHOD, String.format(ResponseCode.NOT_FOUND_METHOD_MSG, classname, methodname)); return; } submit(request.getRequestType(), method, rid, component, params, ctx); } catch (Throwable e) { LOGGER.error(e.getMessage()); exception(ctx, rid, ResponseCode.SERVER_ERROR, e.getMessage()); } } /** * @param classname * @return * @throws ClassNotFoundException */ private Class getClass(String classname) throws ClassNotFoundException { if (!nameClass.containsKey(classname)) { nameClass.put(classname, Class.forName(classname)); } return nameClass.get(classname); } /** * @param ctx * @param id * @param responseCode * @param msg */ private void exception(ChannelHandlerContext ctx, Long id, Integer responseCode, String msg) { ctx.channel().writeAndFlush(Response.createResponse(id, responseCode, msg).toString()); } /** * 修改器 * * @param yuRPCServer 服务组件 */ public void setYuRPCServer(YuRPCServer yuRPCServer) { this.yuRPCServer = yuRPCServer; } } ================================================ FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/impl/YuRPCClientImpl.java ================================================ /* * Copyright 2020 xincao9@gmail.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.xincao9.yurpc.core.impl; import com.github.xincao9.yurpc.core.YuRPCClient; import com.github.xincao9.yurpc.core.config.ClientConfig; import com.github.xincao9.yurpc.core.protocol.Request; import com.github.xincao9.yurpc.core.protocol.Response; import com.github.xincao9.yurpc.core.codec.StringDecoder; import com.github.xincao9.yurpc.core.codec.StringEncoder; import com.github.xincao9.yurpc.core.constant.ResponseCode; import com.github.xincao9.yurpc.core.protocol.Endpoint; import com.github.xincao9.yurpc.core.DiscoveryService; import io.netty.bootstrap.Bootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.ChannelPipeline; import io.netty.channel.EventLoopGroup; import io.netty.channel.epoll.Epoll; import io.netty.channel.epoll.EpollEventLoopGroup; import io.netty.channel.epoll.EpollSocketChannel; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.timeout.IdleStateHandler; import io.netty.util.concurrent.Future; import java.net.InetSocketAddress; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import org.apache.commons.lang3.RandomUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 客户端 * * @author xincao9@gmail.com */ public class YuRPCClientImpl implements YuRPCClient { private static final Logger LOGGER = LoggerFactory.getLogger(YuRPCClientImpl.class); private final Map requests = new ConcurrentHashMap(); private final Bootstrap bootstrap = new Bootstrap(); private final Map addressChannel = new HashMap(); private EventLoopGroup workerGroup; private ClientInvocationHandler clientInvocationHandler; private DiscoveryService discoveryService; /** * 构造器 * */ public YuRPCClientImpl() { this(null); } /** * 构造器 * * @param discoveryService 服务组件 */ public YuRPCClientImpl(DiscoveryService discoveryService) { this.discoveryService = discoveryService; } /** * 启动 * * @throws java.lang.Throwable 异常 */ @Override public void start() throws Throwable { this.workerGroup = Epoll.isAvailable() ? new EpollEventLoopGroup(Runtime.getRuntime().availableProcessors()) : new NioEventLoopGroup(Runtime.getRuntime().availableProcessors()); ClientHandler clientHandler = new ClientHandler(); clientHandler.setYuRPCClient(this); this.bootstrap.group(this.workerGroup).channel(Epoll.isAvailable() ? EpollSocketChannel.class : NioSocketChannel.class) .option(ChannelOption.TCP_NODELAY, true) .option(ChannelOption.SO_KEEPALIVE, false) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, ClientConfig.connectionTimeoutMS) .option(ChannelOption.SO_SNDBUF, 65535) .option(ChannelOption.SO_RCVBUF, 65535) .handler(new ChannelInitializer() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast( new StringEncoder(), new StringDecoder(), clientHandler, new IdleStateHandler(0, 0, 60, TimeUnit.SECONDS), new HeartbeatHandler() ); } }); clientInvocationHandler = new ClientInvocationHandler(); clientInvocationHandler.setYuRPCClient(this); } /** * 关闭 * * @throws java.lang.Throwable 异常 */ @Override public void shutdown() throws Throwable { this.addressChannel.entrySet().forEach((entry) -> { String address = entry.getKey(); Channel channel = entry.getValue(); if (channel != null) { channel.close().addListener((Future future) -> { LOGGER.warn("close the connection to the yurpc service address = {}, cause = {}", address, future.cause()); }); } }); if (this.workerGroup != null) { try { this.workerGroup.shutdownGracefully().sync(); } catch (InterruptedException ex) { LOGGER.error(ex.getMessage()); } } } /** * 调用方法 * * @param 类型 * @param request 请求 * @return 调用结果 * @throws Throwable 异常 */ @Override public Response invoke(Request request) throws Throwable { Objects.requireNonNull(request); if (discoveryService != null && !request.isDirect()) { List nodes = discoveryService.query(StringUtils.substringBeforeLast(request.getMethod(), ".")); if (nodes != null && !nodes.isEmpty()) { Endpoint node = nodes.get(RandomUtils.nextInt(0, nodes.size())); request.setHost(node.getHost()); request.setPort(node.getPort()); } } Channel channel = getChannel(request.getHost(), request.getPort()); if (channel == null) { return Response.createResponse(request.getId(), ResponseCode.CONNECTION_FAILURE, ResponseCode.CONNECTION_FAILURE_MSG); } this.requests.put(request.getId(), request); channel.writeAndFlush(request.toString()).addListener((ChannelFutureListener) (ChannelFuture f) -> { if (f.isSuccess()) { request.setSendOk(Boolean.TRUE); return; } request.setSendOk(Boolean.FALSE); this.requests.remove(request.getId()); request.putResponse(null); LOGGER.error("yurpc.invoke() request = {} failure exception = {}", request, f.cause()); }); try { return request.waitResponse(ClientConfig.invokeTimeoutMS, TimeUnit.MILLISECONDS); } catch (Throwable e) { LOGGER.error(e.getMessage()); } this.requests.remove(request.getId()); request.putResponse(null); LOGGER.error("yurpc.invoke() request = {} timeout (wait time > {} ms)", request, ClientConfig.invokeTimeoutMS); return Response.createResponse(request.getId(), ResponseCode.INVOKE_TIMEOUT, ResponseCode.INVOKE_TIMEOUT_MSG); } /** * 获取通道 * * @param host 主机 * @param port 端口 * @return 通道 */ private Channel getChannel(String host, int port) { String address = String.format("%s:%d", host, port); if (!this.addressChannel.containsKey(address)) { synchronized (this) { if (!this.addressChannel.containsKey(address)) { ChannelFuture channelFuture = this.bootstrap.connect(new InetSocketAddress(host, port)); if (channelFuture.awaitUninterruptibly(ClientConfig.connectionTimeoutMS)) { if (channelFuture.channel().isActive()) { YuRPCClientImpl.this.addressChannel.put(address, channelFuture.channel()); } } } } } Channel channel = this.addressChannel.get(address); if (channel == null) { LOGGER.error("getChannel() host = {} port = {} channel is null", host, port); return null; } if (!channel.isActive()) { this.addressChannel.remove(address); LOGGER.error("getChannel() host = {} port = {} channel is inactive", host, port); return null; } return channel; } /** * 获得请求对象容器 * * @return 请求对象容器 */ @Override public Map getRequests() { return this.requests; } /** * 获得接口的代理 * * @param 类型 * @param clazz 接口 * @return 代理对象 */ @Override public T proxy(Class clazz) { return this.clientInvocationHandler.proxy(clazz); } /** * 修改器 * * @param discoveryService 服务发现和注册组件 */ @Override public void setDiscoveryService(DiscoveryService discoveryService) { this.discoveryService = discoveryService; } } ================================================ FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/impl/YuRPCServerImpl.java ================================================ /* * Copyright 2020 xincao9@gmail.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.xincao9.yurpc.core.impl; import com.github.xincao9.yurpc.core.YuRPCServer; import com.github.xincao9.yurpc.core.codec.StringDecoder; import com.github.xincao9.yurpc.core.codec.StringEncoder; import com.github.xincao9.yurpc.core.config.ServerConfig; import com.github.xincao9.yurpc.core.DiscoveryService; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.epoll.Epoll; import io.netty.channel.epoll.EpollEventLoopGroup; import io.netty.channel.epoll.EpollServerSocketChannel; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.timeout.IdleStateHandler; import io.netty.util.concurrent.Future; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.xincao9.yurpc.core.protocol.Endpoint; /** * 服务组件 * * @author xincao9@gmail.com */ public class YuRPCServerImpl implements YuRPCServer { private static final Logger LOGGER = LoggerFactory.getLogger(YuRPCServerImpl.class); private final Integer port; private EventLoopGroup bossGroup; private EventLoopGroup workerGroup; private final Integer boss; private final Integer worker; private DiscoveryService discoveryService; /** * 构造器 */ public YuRPCServerImpl() { this(null); } /** * 构造器 * * @param port 端口 * @param discoveryService 服务组件 */ public YuRPCServerImpl(Integer port, DiscoveryService discoveryService) { this.port = port; this.boss = ServerConfig.ioThreadBoss; this.worker = ServerConfig.ioThreadWorker; this.discoveryService = discoveryService; } /** * 构造器 * * @param discoveryService 服务组件 */ public YuRPCServerImpl(DiscoveryService discoveryService) { this.port = ServerConfig.port; this.boss = ServerConfig.ioThreadBoss; this.worker = ServerConfig.ioThreadWorker; this.discoveryService = discoveryService; } /** * 启动 * * @throws Throwable */ @Override public void start() throws Throwable { this.workerGroup = Epoll.isAvailable() ? new EpollEventLoopGroup(this.worker) : new NioEventLoopGroup(this.worker); ServerBootstrap bootstrap = new ServerBootstrap(); ServerHandler serverHandler = new ServerHandler(); serverHandler.setYuRPCServer(this); if (this.boss == 0) { bootstrap.group(this.workerGroup); } else { this.bossGroup = Epoll.isAvailable() ? new EpollEventLoopGroup(this.boss) : new NioEventLoopGroup(this.boss); bootstrap.group(this.bossGroup, this.workerGroup); } bootstrap.channel(Epoll.isAvailable() ? EpollServerSocketChannel.class : NioServerSocketChannel.class) .childHandler(new ChannelInitializer() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast( new StringEncoder(), new StringDecoder(), serverHandler, new IdleStateHandler(0, 0, 60, TimeUnit.SECONDS), new HeartbeatHandler() ); } }) .childOption(ChannelOption.SO_KEEPALIVE, false) .childOption(ChannelOption.TCP_NODELAY, true); ChannelFuture f = bootstrap.bind("0.0.0.0", port).addListener((Future future) -> { LOGGER.warn("start the yurpc service port = {}, cause = {}", this.port, future.cause()); }); f.channel().closeFuture().addListener((Future future) -> { LOGGER.warn("turn off yurpc service port = {}, cause = {}", this.port, future.cause()); }); } /** * 关闭 * * @throws Throwable */ @Override public void shutdown() throws Throwable { if (this.workerGroup != null) { this.workerGroup.shutdownGracefully(); } if (this.bossGroup != null) { this.bossGroup.shutdownGracefully(); } } private final Map componentes = new HashMap(); /** * 服务注册 * * @param 组建类型 * @param obj 服务组件 */ @Override public void register(T obj) { Objects.requireNonNull(obj); Class[] clazzes = obj.getClass().getInterfaces(); if (clazzes == null || clazzes.length <= 0) { LOGGER.error("class = {} invalid format", obj.getClass().getCanonicalName()); return; } for (Class clazz : clazzes) { componentes.put(clazz.getTypeName(), obj); if (discoveryService != null) { discoveryService.register(Endpoint.create(clazz.getTypeName())); } } } /** * 获取组建 * * @param name 组建类型名 * @return 服务组件 */ @Override public Object getBean(String name) { return componentes.get(name); } /** * 修改器 * * @param discoveryService 服务发现和注册组件 */ @Override public void setDiscoveryService(DiscoveryService discoveryService) { this.discoveryService = discoveryService; } } ================================================ FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/protocol/Endpoint.java ================================================ /* * Copyright 2020 xincao9@gmail.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.xincao9.yurpc.core.protocol; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.serializer.SerializerFeature; import com.github.xincao9.yurpc.core.config.ServerConfig; import com.github.xincao9.yurpc.core.util.HostUtils; import java.util.Date; import java.util.UUID; /** * 端点 * * @author xincao9@gmail.com */ public class Endpoint { private String instanceId; private String host; private Integer port; private String name; private Date createTime; /** * 创建端点 * * @param name 服务名字 * @return 端点 */ public static Endpoint create (String name) { Endpoint node = new Endpoint(); node.setInstanceId(UUID.randomUUID().toString()); node.setHost(HostUtils.getLocalAddress()); node.setPort(ServerConfig.port); node.setName(name); node.setCreateTime(new Date()); return node; } public String getInstanceId() { return instanceId; } public void setInstanceId(String instanceId) { this.instanceId = instanceId; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public Integer getPort() { return port; } public void setPort(Integer port) { this.port = port; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } @Override public String toString () { return JSONObject.toJSONString(this, SerializerFeature.DisableCircularReferenceDetect); } } ================================================ FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/protocol/Pair.java ================================================ /* * Copyright 2020 xincao9@gmail.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.xincao9.yurpc.core.protocol; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.serializer.SerializerFeature; /** * 一对 * * @author xincao9@gmail.com * @param 类型1 * @param 类型2 */ public class Pair { private T1 o1; // 对象1 private T2 o2; // 对象2 public Pair() { } public Pair(T1 o1, T2 o2) { this.o1 = o1; this.o2 = o2; } public T1 getO1() { return o1; } public void setO1(T1 o1) { this.o1 = o1; } public T2 getO2() { return o2; } public void setO2(T2 o2) { this.o2 = o2; } @Override public String toString() { return JSONObject.toJSONString(this, SerializerFeature.DisableCircularReferenceDetect); } } ================================================ FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/protocol/Request.java ================================================ /* * Copyright 2020 xincao9@gmail.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.xincao9.yurpc.core.protocol; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.serializer.SerializerFeature; import com.github.xincao9.yurpc.core.config.ClientConfig; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import org.apache.commons.lang3.RandomUtils; /** * 请求体 * * @author xincao9@gmail.com */ public class Request { private Boolean requestType; // request with/without return value private Boolean eventType; // whether the request is an event message private Long id; // request id private Object[] params; private String[] paramTypes; private static final AtomicLong COUNTER = new AtomicLong(0); private String method; private Long createTime; private String host; private int port; private final CountDownLatch countDownLatch = new CountDownLatch(1); private Response response; private Boolean sendOk; private Boolean direct = Boolean.FALSE; /** * 创建请求体 * * @param requestType * @param method * @param params * @return */ public static Request createRequest(Boolean requestType, String method, Object... params) { Request request = new Request(); request.setRequestType(requestType); request.setEventType(false); request.setId(COUNTER.getAndIncrement()); request.setMethod(method); request.setParams(params); request.setCreateTime(System.currentTimeMillis()); Pair pair = ClientConfig.serverList.get(RandomUtils.nextInt(0, ClientConfig.serverList.size())); request.setHost(pair.getO1()); request.setPort(pair.getO2()); return request; } /** * 创建事件 * * @param method * @return */ public static Request createEvent(String method) { Request request = new Request(); request.setRequestType(false); request.setEventType(true); request.setId(COUNTER.getAndIncrement()); request.setMethod(method); request.setCreateTime(System.currentTimeMillis()); Pair pair = ClientConfig.serverList.get(RandomUtils.nextInt(0, ClientConfig.serverList.size())); request.setHost(pair.getO1()); request.setPort(pair.getO2()); return request; } /** * 等待响应 * * @param * @param timeout * @param timeUnit * @return * @throws InterruptedException */ public Response waitResponse(int timeout, TimeUnit timeUnit) throws InterruptedException { this.countDownLatch.await(timeout, timeUnit); return response; } /** * 设置返回值 * * @param response */ public void putResponse(Response response) { this.response = response; this.countDownLatch.countDown(); } public Boolean getRequestType() { return requestType; } public void setRequestType(Boolean requestType) { this.requestType = requestType; } public Boolean getEventType() { return eventType; } public void setEventType(Boolean eventType) { this.eventType = eventType; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Object[] getParams() { return params; } public void setParams(Object[] params) { this.params = params; } public String[] getParamTypes() { return paramTypes; } public void setParamTypes(String[] paramTypes) { this.paramTypes = paramTypes; } public String getMethod() { return method; } public void setMethod(String method) { this.method = method; } public Long getCreateTime() { return createTime; } public void setCreateTime(Long createTime) { this.createTime = createTime; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } public Object getResponse() { return response; } public void setResponse(Response response) { this.response = response; } public Boolean getSendOk() { return sendOk; } public void setSendOk(Boolean sendOk) { this.sendOk = sendOk; } public Boolean isDirect () { return getDirect(); } public Boolean getDirect() { return direct; } public void setDirect(Boolean direct) { this.direct = direct; } @Override public String toString() { return JSONObject.toJSONString(this, SerializerFeature.DisableCircularReferenceDetect); } } ================================================ FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/protocol/Response.java ================================================ /* * Copyright 2020 xincao9@gmail.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.xincao9.yurpc.core.protocol; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.serializer.SerializerFeature; import com.github.xincao9.yurpc.core.constant.ResponseCode; /** * 响应体 * * @author xincao9@gmail.com * @param */ public class Response { private Long id; // response id private Integer code = ResponseCode.OK; // response code private T data; private String msg = ResponseCode.OK_MSG; private final Long createTime = System.currentTimeMillis(); public static Response createResponse(Long id, T data) { Response response = new Response(); response.setId(id); response.setData(data); return response; } public static Response createResponse(Long id, Integer code, String msg) { Response response = new Response(); response.setId(id); response.setCode(code); response.setMsg(msg); return response; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public T getData() { return data; } public void setData(T data) { this.data = data; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public Long getCreateTime() { return createTime; } @Override public String toString() { return JSONObject.toJSONString(this, SerializerFeature.DisableCircularReferenceDetect); } } ================================================ FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/util/HostUtils.java ================================================ /* * Copyright 2020 xincao9@gmail.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.xincao9.yurpc.core.util; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.UnknownHostException; import java.util.Enumeration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 主机工具 * * @author xincao9@gmail.com */ public class HostUtils { private static final Logger LOGGER = LoggerFactory.getLogger(HostUtils.class); /** * 获得本机IP地址 * * @return 本机IP */ public static String getLocalAddress() { try { InetAddress candidateAddress = null; // 遍历所有的网络接口 Enumeration interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface face = (NetworkInterface) interfaces.nextElement(); // 在所有的接口下再遍历IP Enumeration inetAddrs = face.getInetAddresses(); while (inetAddrs.hasMoreElements()) { InetAddress inetAddr = (InetAddress) inetAddrs.nextElement(); if (!inetAddr.isLoopbackAddress()) { // 排除loopback类型地址 if (inetAddr.isSiteLocalAddress()) { // 如果是site-local地址,就是它了 return inetAddr.getHostAddress(); } else if (candidateAddress == null) { // site-local类型的地址未被发现,先记录候选地址 candidateAddress = inetAddr; } } } } if (candidateAddress != null) { return candidateAddress.getHostAddress(); } InetAddress jdkSuppliedAddress = InetAddress.getLocalHost(); // 如果没有发现 non-loopback地址.只能用最次选的方案 return jdkSuppliedAddress.getHostAddress(); } catch (SocketException | UnknownHostException e) { LOGGER.error(e.getMessage()); } return null; } } ================================================ FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/util/PropertiesUtils.java ================================================ /* * Copyright 2020 xincao9@gmail.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.xincao9.yurpc.core.util; import java.io.IOException; import java.util.Properties; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 属性工具类 * * @author xincao9@gmail.com */ public class PropertiesUtils { private static final Logger LOGGER = LoggerFactory.getLogger(PropertiesUtils.class); /** * 读取属性文件 * * @param filename * @param defaultFilename * @return */ public static Properties read(String filename, String defaultFilename) { if (StringUtils.isBlank(filename)) { LOGGER.warn("filename is empty"); filename = defaultFilename; } try { Properties pros = new Properties(); pros.load(PropertiesUtils.class.getResourceAsStream(filename)); return pros; } catch (IOException e) { LOGGER.warn(e.getMessage()); } return new Properties(); } } ================================================ FILE: yurpc-core/src/test/java/com/github/xincao9/yurpc/YuRPCServerTest.java ================================================ /* * Copyright 2020 xincao9@gmail.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.xincao9.yurpc; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.serializer.SerializerFeature; import com.github.xincao9.yurpc.core.YuRPCClient; import com.github.xincao9.yurpc.core.YuRPCServer; import org.apache.commons.lang3.RandomStringUtils; import org.junit.Test; import org.openjdk.jmh.annotations.*; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; /** * 服务组件测试 * * @author xincao9@gmail.com */ @BenchmarkMode(Mode.Throughput) @Warmup(iterations = 5) @Measurement(iterations = 5, time = 5, timeUnit = TimeUnit.SECONDS) @OutputTimeUnit(TimeUnit.SECONDS) @State(Scope.Benchmark) public class YuRPCServerTest { private YuRPCServer yuRPCServer; private YuRPCClient yuRPCClient; private SayService sayService; private AtomicInteger no = new AtomicInteger(0); /** * 启动服务组件 * * @throws Throwable */ @Setup public void setUp() throws Throwable { yuRPCServer = YuRPCServer.defaultYuRPCServer(); yuRPCServer.register(new SayServiceImpl()); yuRPCServer.start(); yuRPCClient = YuRPCClient.defaultYuRPCClient(); yuRPCClient.start(); sayService = yuRPCClient.proxy(SayService.class); } /** * 关闭服务组件 * * @throws Throwable */ @TearDown public void tearDown() throws Throwable { yuRPCServer.shutdown(); yuRPCClient.shutdown(); } @Benchmark public void perform() { String value = RandomStringUtils.randomAscii(128); Say say = new Say(no.incrementAndGet(), value); System.out.println(sayService.perform(say)); } /** * 客户端发送请求给服务端 * * @throws Throwable */ @Test public void testMethod() throws Throwable { Options opt = new OptionsBuilder() .include(getClass().getSimpleName()) .forks(1) .build(); new Runner(opt).run(); } public static class Say { private Integer id; private String body; public Say(Integer id, String body) { this.id = id; this.body = body; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getBody() { return body; } public void setBody(String body) { this.body = body; } @Override public String toString() { return JSONObject.toJSONString(this, SerializerFeature.DisableCircularReferenceDetect); } } public interface SayService { Say perform(Say say); } public static class SayServiceImpl implements SayService { @Override public Say perform(Say say) { return say; } } } ================================================ FILE: yurpc-core/src/test/resources/config.properties ================================================ yurpc.client.serverList=localhost:12306 yurpc.client.connectionTimeoutMS=5000 yurpc.client.invokeTimeoutMS=1000 yurpc.server.port=12306 ================================================ FILE: yurpc-sample/dependency-reduced-pom.xml ================================================ yurpc com.github.xincao9 1.2.6 4.0.0 yurpc-sample maven-shade-plugin 3.2.1 package shade com.github.xincao9.yurpc.sample.provider.Provider org.springframework.boot spring-boot-dependencies ${spring-boot.version} pom import 2.1.3.RELEASE ================================================ FILE: yurpc-sample/pom.xml ================================================ 4.0.0 com.github.xincao9 yurpc 1.2.6 yurpc-sample jar 2.1.3.RELEASE org.springframework.boot spring-boot-dependencies ${spring-boot.version} pom import org.springframework.boot spring-boot-starter com.github.xincao9 yurpc-spring-boot-starter com.github.xincao9 ptk-core 1.0 org.apache.maven.plugins maven-shade-plugin 3.2.1 package shade com.github.xincao9.yurpc.sample.provider.Provider ================================================ FILE: yurpc-sample/src/main/java/com/github/xincao9/yurpc/sample/Say.java ================================================ /* * Copyright 2020 xincao9@gmail.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.xincao9.yurpc.sample; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.serializer.SerializerFeature; /** * 招呼 * * @author xincao9@gmail.com */ public class Say { private Integer id; private String body; public Say(Integer id, String body) { this.id = id; this.body = body; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getBody() { return body; } public void setBody(String body) { this.body = body; } @Override public String toString() { return JSONObject.toJSONString(this, SerializerFeature.DisableCircularReferenceDetect); } } ================================================ FILE: yurpc-sample/src/main/java/com/github/xincao9/yurpc/sample/SayService.java ================================================ /* * Copyright 2020 xincao9@gmail.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.xincao9.yurpc.sample; /** * 招呼服务 * * @author xincao9@gmail.com */ public interface SayService { /** * 执行 * * @param say 招呼 * @return 招呼 */ Say perform(Say say); } ================================================ FILE: yurpc-sample/src/main/java/com/github/xincao9/yurpc/sample/consumer/ApplicationConsumer.java ================================================ /* * Copyright 2020 xincao9@gmail.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.xincao9.yurpc.sample.consumer; import com.github.xincao9.yurpc.sample.Say; import com.github.xincao9.yurpc.sample.SayService; import com.github.xincao9.yurpc.spring.boot.starter.EnableYuRPC; import com.github.xincao9.yurpc.spring.boot.starter.YUConsumer; import org.apache.commons.lang3.RandomStringUtils; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; /** * 服务消费者 * * @author xincao9@gmail.com */ @SpringBootApplication @EnableYuRPC(client = true) public class ApplicationConsumer { @YUConsumer private SayService sayService; /** * 入口方法 * * @param args 参数 */ public static void main(String... args) { SpringApplication.run(ApplicationConsumer.class, args); } /** * 启动时钩子 * * @return */ @Bean public CommandLineRunner commandLineRunner() { return (String... args) -> { for (int no = 0; no < 100; no++) { String value = RandomStringUtils.randomAscii(128); Say say = new Say(no, value); System.out.println(sayService.perform(say)); } }; } } ================================================ FILE: yurpc-sample/src/main/java/com/github/xincao9/yurpc/sample/consumer/Benchmark.java ================================================ /* * Copyright 2020 xincao9@gmail.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.xincao9.yurpc.sample.consumer; import com.github.xincao9.ptk.core.PTKCore; import com.github.xincao9.ptk.core.source.SequenceSource; /** * java -cp target/yurpc-sample-1.2.5.jar com.github.xincao9.yurpc.sample.consumer.Benchmark -m say -t -1 -c 16 */ public class Benchmark { public static void main(String... args) throws Throwable { PTKCore.bootstrap(new SequenceSource(1000000), args); } } ================================================ FILE: yurpc-sample/src/main/java/com/github/xincao9/yurpc/sample/consumer/Consumer.java ================================================ /* * Copyright 2020 xincao9@gmail.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.xincao9.yurpc.sample.consumer; import com.github.xincao9.yurpc.core.YuRPCClient; import com.github.xincao9.yurpc.sample.Say; import com.github.xincao9.yurpc.sample.SayService; import org.apache.commons.lang3.RandomStringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 服务消费者 * * @author xincao9@gmail.com */ public class Consumer { private static final Logger LOGGER = LoggerFactory.getLogger(Consumer.class); /** * 入口方法 * * @param args 参数 * @throws Throwable 异常 */ public static void main(String... args) throws Throwable { YuRPCClient yuRPCClient = YuRPCClient.defaultYuRPCClient(); yuRPCClient.start(); SayService sayService = yuRPCClient.proxy(SayService.class); for (int no = 0; no < 100; no++) { String value = RandomStringUtils.randomAscii(128); Say say = new Say(no, value); System.out.println(sayService.perform(say)); } Runtime.getRuntime().addShutdownHook(new Thread(() -> { try { yuRPCClient.shutdown(); } catch (Throwable ex) { LOGGER.error(ex.getMessage()); } })); } } ================================================ FILE: yurpc-sample/src/main/java/com/github/xincao9/yurpc/sample/consumer/SayMethod.java ================================================ /* * Copyright 2020 xincao9@gmail.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.xincao9.yurpc.sample.consumer; import com.github.xincao9.ptk.core.Method; import com.github.xincao9.ptk.core.annotation.Test; import com.github.xincao9.yurpc.core.YuRPCClient; import com.github.xincao9.yurpc.sample.Say; import com.github.xincao9.yurpc.sample.SayService; import org.apache.commons.lang3.RandomStringUtils; @Test(name="say") public class SayMethod extends Method { private SayService sayService; public SayMethod () { YuRPCClient yuRPCClient = YuRPCClient.defaultYuRPCClient(); try { yuRPCClient.start(); } catch(Throwable e) { throw new RuntimeException(e); } sayService = yuRPCClient.proxy(SayService.class); } @Override public void exec(Object params) throws Exception { Integer id = (Integer) params; String value = RandomStringUtils.randomAscii(128); Say say = new Say(id, value); sayService.perform(say); } } ================================================ FILE: yurpc-sample/src/main/java/com/github/xincao9/yurpc/sample/provider/ApplicationProvider.java ================================================ /* * Copyright 2020 xincao9@gmail.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.xincao9.yurpc.sample.provider; import com.github.xincao9.yurpc.spring.boot.starter.EnableYuRPC; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * 服务提供者 * * @author xincao9@gmail.com */ @SpringBootApplication @EnableYuRPC(server = true) public class ApplicationProvider { /** * 入口方法 * * @param args 参数 */ public static void main(String... args) { SpringApplication.run(ApplicationProvider.class, args); } } ================================================ FILE: yurpc-sample/src/main/java/com/github/xincao9/yurpc/sample/provider/Provider.java ================================================ /* * Copyright 2020 xincao9@gmail.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.xincao9.yurpc.sample.provider; import com.github.xincao9.yurpc.core.YuRPCServer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 服务提供者 * java -jar target/yurpc-sample-1.2.5.jar * * @author xincao9@gmail.com */ public class Provider { private static final Logger LOGGER = LoggerFactory.getLogger(Provider.class); /** * 入口方法 * * @param args 参数 * @throws java.lang.Throwable */ public static void main(String... args) throws Throwable { YuRPCServer yuRPCServer = YuRPCServer.defaultYuRPCServer(); yuRPCServer.register(new SayServiceImpl()); yuRPCServer.start(); Runtime.getRuntime().addShutdownHook(new Thread(() -> { try { yuRPCServer.shutdown(); } catch (Throwable ex) { LOGGER.error(ex.getMessage()); } })); } } ================================================ FILE: yurpc-sample/src/main/java/com/github/xincao9/yurpc/sample/provider/SayServiceImpl.java ================================================ /* * Copyright 2020 xincao9@gmail.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.xincao9.yurpc.sample.provider; import com.github.xincao9.yurpc.sample.Say; import com.github.xincao9.yurpc.sample.SayService; import com.github.xincao9.yurpc.spring.boot.starter.YUProvider; /** * 招呼服务实现 * * @author xincao9@gmail.com */ @YUProvider public class SayServiceImpl implements SayService { /** * 执行 * * @param say 招呼 * @return 招呼 */ @Override public Say perform(Say say) { return say; } } ================================================ FILE: yurpc-sample/src/main/resources/application.yml ================================================ yurpc: discovery: zookeeper: localhost:2181 client: serverList: localhost:12306 connectionTimeoutMS: 5000 invokeTimeoutMS: 1000 server: port: 12306 ================================================ FILE: yurpc-sample/src/main/resources/config.properties ================================================ yurpc.client.serverList=localhost:12306 yurpc.client.connectionTimeoutMS=5000 yurpc.client.invokeTimeoutMS=1000 yurpc.server.port=12306 ================================================ FILE: yurpc-spring-boot-starter/pom.xml ================================================ 4.0.0 com.github.xincao9 yurpc 1.2.6 yurpc-spring-boot-starter yurpc-spring-boot-starter jar 2.1.3.RELEASE 4.2.0 3.5.6 29.0-jre org.springframework.boot spring-boot-autoconfigure ${spring-boot.version} org.apache.curator curator-recipes ${curator.version} log4j log4j org.apache.curator curator-framework ${curator.version} log4j log4j org.apache.curator curator-client ${curator.version} log4j log4j org.apache.zookeeper zookeeper ${zookeeper.version} log4j log4j io.netty netty org.slf4j slf4j-log4j12 com.google.guava guava ${guava.version} com.github.xincao9 yurpc-core org.springframework.boot spring-boot-autoconfigure org.apache.curator curator-recipes org.apache.curator curator-framework org.apache.curator curator-client org.apache.zookeeper zookeeper com.google.guava guava ================================================ FILE: yurpc-spring-boot-starter/src/main/java/com/github/xincao9/yurpc/spring/boot/starter/ConfigConsts.java ================================================ /* * Copyright 2020 xincao9@gmail.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.xincao9.yurpc.spring.boot.starter; /** * @author xincao9@gmail.com */ public class ConfigConsts { public static final String DISCOVERY_ZOOKEEPER = "yurpc.discovery.zookeeper"; } ================================================ FILE: yurpc-spring-boot-starter/src/main/java/com/github/xincao9/yurpc/spring/boot/starter/EnableYuRPC.java ================================================ /* * Copyright 2020 xincao9@gmail.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.xincao9.yurpc.spring.boot.starter; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.context.annotation.Import; /** * 启动注解 * * @author xincao9@gmail.com */ @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Import({YuRPCImportBeanDefinitionRegistrar.class}) public @interface EnableYuRPC { /** * 服务角色 * * @return */ boolean server() default false; /** * 客户端角色 * * @return */ boolean client() default false; } ================================================ FILE: yurpc-spring-boot-starter/src/main/java/com/github/xincao9/yurpc/spring/boot/starter/YUConsumer.java ================================================ /* * Copyright 2020 xincao9@gmail.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.xincao9.yurpc.spring.boot.starter; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @author xincao9@gmail.com */ @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface YUConsumer { } ================================================ FILE: yurpc-spring-boot-starter/src/main/java/com/github/xincao9/yurpc/spring/boot/starter/YUProvider.java ================================================ /* * Copyright 2020 xincao9@gmail.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.xincao9.yurpc.spring.boot.starter; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.core.annotation.AliasFor; import org.springframework.stereotype.Component; /** * YuRPC 服务注解 * * @author xincao9@gmail.com */ @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Component public @interface YUProvider { @AliasFor(annotation = Component.class) String value() default ""; } ================================================ FILE: yurpc-spring-boot-starter/src/main/java/com/github/xincao9/yurpc/spring/boot/starter/YuRPCAutoConfiguration.java ================================================ /* * Copyright 2020 xincao9@gmail.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.xincao9.yurpc.spring.boot.starter; import com.github.xincao9.yurpc.core.DiscoveryService; import com.github.xincao9.yurpc.core.config.ClientConfig; import com.github.xincao9.yurpc.core.YuRPCClient; import com.github.xincao9.yurpc.core.impl.YuRPCClientImpl; import com.github.xincao9.yurpc.core.constant.ClientConsts; import com.github.xincao9.yurpc.core.constant.ServerConsts; import com.github.xincao9.yurpc.core.YuRPCServer; import com.github.xincao9.yurpc.core.impl.YuRPCServerImpl; import com.github.xincao9.yurpc.core.config.ServerConfig; import java.util.Properties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.context.EnvironmentAware; import org.springframework.core.env.Environment; /** * 自动配置类 * * @author xincao9@gmail.com */ public class YuRPCAutoConfiguration implements EnvironmentAware, InitializingBean, DisposableBean, BeanFactoryPostProcessor { private static final Logger LOGGER = LoggerFactory.getLogger(YuRPCAutoConfiguration.class); private Environment environment; private Boolean server; private Boolean client; private YuRPCClient yuRPCClient; private YuRPCServer yuRPCServer; private DiscoveryService discoveryService; private YuRPCBeanPostProcessor yuRPCBeanPostProcessor; /** * 修改器 * * @param environment 环境 */ @Override public void setEnvironment(Environment environment) { this.environment = environment; } /** * 自动扫描,注册服务组件 * * @return 注册服务组件 * @throws java.lang.Throwable 异常 */ public YuRPCBeanPostProcessor yuRPCBeanPostProcessor(YuRPCClient yuRPCClient, YuRPCServer yuRPCServer) throws Throwable { if (server || client) { yuRPCBeanPostProcessor = new YuRPCBeanPostProcessor(yuRPCClient, yuRPCServer); return yuRPCBeanPostProcessor; } return null; } /** * 释放资源 * * @throws Exception 异常 */ @Override public void destroy() throws Exception { if (yuRPCClient != null) { try { yuRPCClient.shutdown(); } catch (Throwable e) { LOGGER.error(e.getMessage()); } } if (yuRPCServer != null) { try { yuRPCServer.shutdown(); } catch (Throwable e) { LOGGER.error(e.getMessage()); } } } /** * 服务端角色 * * @param server 状态 */ public void setServer(Boolean server) { this.server = server; } /** * 客户端角色 * * @param client 状态 */ public void setClient(Boolean client) { this.client = client; } /** * 服务发现注册组件 * * @return 服务发现注册组件 * @throws java.lang.Throwable 异常 */ public DiscoveryService discoveryService() throws Throwable { if ((client || server) && environment.containsProperty(ConfigConsts.DISCOVERY_ZOOKEEPER)) { discoveryService = new ZKDiscoveryServiceImpl(environment.getProperty(ConfigConsts.DISCOVERY_ZOOKEEPER)); return discoveryService; } return null; } /** * 服务端 * * @param discoveryService 服务发现注册组件 * @return 服务端 * @throws java.lang.Throwable 异常 */ public YuRPCServer yuRPCServer(DiscoveryService discoveryService) throws Throwable { if (server) { Properties pros = new Properties(); if (environment.containsProperty(ServerConsts.PORT)) { pros.setProperty(ServerConsts.PORT, environment.getProperty(ServerConsts.PORT)); } ServerConfig.init(pros); yuRPCServer = new YuRPCServerImpl(); yuRPCServer.setDiscoveryService(discoveryService); yuRPCServer.start(); return yuRPCServer; } return null; } /** * 客户端 * * @param discoveryService 服务发现注册组件 * @return 客户端 * @throws java.lang.Throwable 异常 */ public YuRPCClient yuRPCClient(DiscoveryService discoveryService) throws Throwable { if (client) { Properties pros = new Properties(); if (environment.containsProperty(ClientConsts.SERVER_LIST)) { pros.setProperty(ClientConsts.SERVER_LIST, environment.getProperty(ClientConsts.SERVER_LIST)); } if (environment.containsProperty(ClientConsts.CONNECTION_TIMEOUT_MS)) { pros.setProperty(ClientConsts.CONNECTION_TIMEOUT_MS, environment.getProperty(ClientConsts.CONNECTION_TIMEOUT_MS)); } if (environment.containsProperty(ClientConsts.INVOKE_TIMEOUT_MS)) { pros.setProperty(ClientConsts.INVOKE_TIMEOUT_MS, environment.getProperty(ClientConsts.INVOKE_TIMEOUT_MS)); } ClientConfig.init(pros); yuRPCClient = new YuRPCClientImpl(); yuRPCClient.setDiscoveryService(discoveryService); yuRPCClient.start(); return yuRPCClient; } return null; } /** * 后置处理组件工厂 * * @param beanFactory 容器上下文 * @throws BeansException 组件异常 */ @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { if (server || client) { try { beanFactory.addBeanPostProcessor(yuRPCBeanPostProcessor); } catch (Throwable e) { throw new BeansException(e.getMessage()) { }; } } } @Override public void afterPropertiesSet() throws Exception { try { discoveryService(); yuRPCClient(discoveryService); yuRPCServer(discoveryService); yuRPCBeanPostProcessor(yuRPCClient, yuRPCServer); } catch (Throwable e) { throw new Exception(e.getCause()); } } } ================================================ FILE: yurpc-spring-boot-starter/src/main/java/com/github/xincao9/yurpc/spring/boot/starter/YuRPCBeanPostProcessor.java ================================================ /* * Copyright 2020 xincao9@gmail.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.xincao9.yurpc.spring.boot.starter; import com.github.xincao9.yurpc.core.YuRPCClient; import com.github.xincao9.yurpc.core.YuRPCServer; import java.lang.reflect.Field; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.util.ClassUtils; /** * 自动扫描,注册服务组件 * * @author xincao9@gmail.com */ public class YuRPCBeanPostProcessor implements BeanPostProcessor { private static final Logger LOGGER = LoggerFactory.getLogger(YuRPCBeanPostProcessor.class); private final YuRPCServer yuRPCServer; private final YuRPCClient yuRPCClient; public YuRPCBeanPostProcessor(YuRPCClient yuRPCClient, YuRPCServer yuRPCServer) { this.yuRPCClient = yuRPCClient; this.yuRPCServer = yuRPCServer; } /** * 初始化前执行 * * @param bean 实例 * @param beanName 名字 * @return * @throws BeansException 异常 */ @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (this.yuRPCServer != null && bean != null && bean.getClass().isAnnotationPresent(YUProvider.class)) { this.yuRPCServer.register(bean); LOGGER.info("register yurpc service = {}", beanName); } if (this.yuRPCClient != null && bean != null) { // Class clazz = AopUtils.getTargetClass(bean); // AOP代理的目标类 https://github.com/spring-projects/spring-framework/issues/20132 Class clazz = ClassUtils.getUserClass(bean); // the original class for CGLIB-generated classes, consider ClassUtils.getUserClass Field[] fields = clazz.getDeclaredFields(); if (fields != null && fields.length > 0) { for (Field field : fields) { if (field.isAnnotationPresent(YUConsumer.class)) { Object obj = this.yuRPCClient.proxy(field.getType()); try { field.setAccessible(true); field.set(bean, obj); } catch (IllegalArgumentException | IllegalAccessException ex) { LOGGER.error(ex.getMessage()); throw new BeansException(ex.getMessage()) { }; } LOGGER.info("service reference beanName = {}, field = {}", beanName, field.getName()); } } } } return BeanPostProcessor.super.postProcessBeforeInitialization(bean, beanName); } /** * 初始化后执行 * * @param bean 实例 * @param beanName 名字 * @return * @throws BeansException 异常 */ @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName); } } ================================================ FILE: yurpc-spring-boot-starter/src/main/java/com/github/xincao9/yurpc/spring/boot/starter/YuRPCImportBeanDefinitionRegistrar.java ================================================ /* * Copyright 2020 xincao9@gmail.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.xincao9.yurpc.spring.boot.starter; import java.util.Map; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.context.annotation.ImportBeanDefinitionRegistrar; import org.springframework.core.type.AnnotationMetadata; /** * 导入注解属性且初始化自动配置类 * * @author xincao9@gmail.com */ public class YuRPCImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar { /** * 注册组件 * * @param am 注解元信息 * @param bdr 组件注册器 */ @Override public void registerBeanDefinitions(AnnotationMetadata am, BeanDefinitionRegistry bdr) { Map attributes = am.getAnnotationAttributes(EnableYuRPC.class.getName()); BeanDefinitionBuilder bdb = BeanDefinitionBuilder.rootBeanDefinition(YuRPCAutoConfiguration.class); if (attributes != null && attributes.containsKey("server")) { bdb.addPropertyValue("server", (Boolean) attributes.get("server")); } if (attributes != null && attributes.containsKey("client")) { bdb.addPropertyValue("client", (Boolean) attributes.get("client")); } bdr.registerBeanDefinition(YuRPCAutoConfiguration.class.getName(), bdb.getBeanDefinition()); } } ================================================ FILE: yurpc-spring-boot-starter/src/main/java/com/github/xincao9/yurpc/spring/boot/starter/ZKDiscoveryServiceImpl.java ================================================ /* * Copyright 2020 xincao9@gmail.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.xincao9.yurpc.spring.boot.starter; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.serializer.SerializerFeature; import com.github.xincao9.yurpc.core.DiscoveryService; import com.github.xincao9.yurpc.core.protocol.Endpoint; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.apache.curator.RetryPolicy; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.recipes.cache.TreeCache; import org.apache.curator.framework.recipes.cache.TreeCacheEvent; import org.apache.curator.framework.recipes.cache.TreeCacheListener; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.framework.state.ConnectionStateListener; import org.apache.curator.retry.ExponentialBackoffRetry; import org.apache.zookeeper.CreateMode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 服务注册与发现组件 * * @author xincao9@gmail.com */ public final class ZKDiscoveryServiceImpl implements DiscoveryService { private static final Logger LOGGER = LoggerFactory.getLogger(ZKDiscoveryServiceImpl.class); private CuratorFramework client; private static final String YURPC_ROOT = "/yurpc"; private static final String YURPC_SERVICE_PATTERN = "/yurpc/%s"; private static final String YURPC_INSTANCE_PATTERN = "/yurpc/%s/%s"; private final Map> services = new ConcurrentHashMap(); private final ExecutorService watcherExecutorService = Executors.newFixedThreadPool(1); private final Map pathValue = new ConcurrentHashMap(); /** * 构造器 */ public ZKDiscoveryServiceImpl() { } /** * 构造器 * * @param zookeeper zookeeper地址,(格式host1:port1,host2:port2,...) * @throws java.lang.Throwable 异常 */ public ZKDiscoveryServiceImpl(String zookeeper) throws Throwable { init(zookeeper); } /** * 初始化方法,(仅在使用无参构造器时使用) * * @param zookeeper * @throws java.lang.Throwable 异常 */ public void init(String zookeeper) throws Throwable { RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3); this.client = CuratorFrameworkFactory.newClient(zookeeper, retryPolicy); this.client.start(); this.client.getConnectionStateListenable().addListener((ConnectionStateListener) (CuratorFramework cf, ConnectionState cs) -> { if (cs == ConnectionState.RECONNECTED) { if (pathValue != null && !pathValue.isEmpty()) { pathValue.entrySet().forEach((entry) -> { String path = entry.getKey(); byte[] value = entry.getValue(); try { cf.create().withMode(CreateMode.EPHEMERAL).forPath(path, value); } catch (Exception ex) { LOGGER.error(ex.getMessage()); } }); } } }, watcherExecutorService); } /** * 监控服务 * * @param service 服务名字(接口名) */ private void watcher(String service) { try { TreeCache treeCache = TreeCache.newBuilder(this.client, String.format(YURPC_SERVICE_PATTERN, service)).setExecutor(this.watcherExecutorService).build(); treeCache.getListenable().addListener((TreeCacheListener) (CuratorFramework cf, TreeCacheEvent tce) -> { TreeCacheEvent.Type type = tce.getType(); if (type == TreeCacheEvent.Type.NODE_ADDED || type == TreeCacheEvent.Type.NODE_REMOVED || type == TreeCacheEvent.Type.NODE_UPDATED) { LOGGER.warn("service = {}, event = {} refresh", service, type); try { this.services.put(service, queryZookeeper(service)); } catch (Throwable e) { LOGGER.error(e.getMessage()); } } }); treeCache.start(); } catch (Exception e) { LOGGER.error(e.getMessage()); } } /** * 注册 * * @param endpoint 服务信息 */ @Override public void register(Endpoint endpoint) { try { if (this.client.checkExists().forPath(YURPC_ROOT) == null) { this.client.create().withMode(CreateMode.PERSISTENT).forPath(YURPC_ROOT); } if (this.client.checkExists().forPath(String.format(YURPC_SERVICE_PATTERN, endpoint.getName())) == null) { this.client.create().withMode(CreateMode.PERSISTENT).forPath(String.format(YURPC_SERVICE_PATTERN, endpoint.getName())); } String path = String.format(YURPC_INSTANCE_PATTERN, endpoint.getName(), endpoint.getInstanceId()); byte[] value = JSONObject.toJSONBytes(endpoint, SerializerFeature.DisableCircularReferenceDetect); this.client.create() .withMode(CreateMode.EPHEMERAL) .forPath(path, value); this.pathValue.put(path, value); } catch (Exception e) { LOGGER.error(e.getMessage()); } } /** * 获取注册表 * * @param service 服务名字(接口名) * @return 节点列表 */ @Override public List query(String service) { if (!this.services.containsKey(service)) { synchronized (this) { if (!this.services.containsKey(service)) { try { this.services.put(service, queryZookeeper(service)); watcher(service); } catch (Throwable e) { LOGGER.error(e.getMessage()); } } } } return this.services.get(service); } /** * 获取注册表 * * @param service 服务名字(接口名) * @return 节点列表 * @throws Throwable 异常 */ private List queryZookeeper(String service) throws Throwable { List paths = this.client.getChildren().forPath(String.format(YURPC_SERVICE_PATTERN, service)); if (paths == null || paths.isEmpty()) { return Collections.EMPTY_LIST; } List endpoints = new ArrayList(); for (String path : paths) { byte[] data = this.client.getData().forPath(String.format(YURPC_INSTANCE_PATTERN, service, path)); if (data != null && data.length > 0) { endpoints.add(JSONObject.parseObject(data, Endpoint.class)); } } return endpoints; } /** * 续约 * * @param instanceId 当前实例的id */ @Override public void renew(String instanceId) { } /** * 取消 * * @param instanceId 当前实例的id */ @Override public void cancel(String instanceId) { } }