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