Repository: xincao9/jsonrpc
Branch: master
Commit: 51e5f954ca31
Files: 53
Total size: 136.4 KB
Directory structure:
gitextract_u_twoy7l/
├── .gitignore
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── pom.xml
├── yurpc-core/
│ ├── pom.xml
│ └── src/
│ ├── main/
│ │ └── java/
│ │ └── com/
│ │ └── github/
│ │ └── xincao9/
│ │ └── yurpc/
│ │ └── core/
│ │ ├── DiscoveryService.java
│ │ ├── YuRPCClient.java
│ │ ├── YuRPCServer.java
│ │ ├── codec/
│ │ │ ├── StringDecoder.java
│ │ │ └── StringEncoder.java
│ │ ├── config/
│ │ │ ├── ClientConfig.java
│ │ │ └── ServerConfig.java
│ │ ├── constant/
│ │ │ ├── ClientConsts.java
│ │ │ ├── ResponseCode.java
│ │ │ ├── ServerConsts.java
│ │ │ └── SystemConsts.java
│ │ ├── impl/
│ │ │ ├── ClientHandler.java
│ │ │ ├── ClientInvocationHandler.java
│ │ │ ├── HeartbeatHandler.java
│ │ │ ├── ServerHandler.java
│ │ │ ├── YuRPCClientImpl.java
│ │ │ └── YuRPCServerImpl.java
│ │ ├── protocol/
│ │ │ ├── Endpoint.java
│ │ │ ├── Pair.java
│ │ │ ├── Request.java
│ │ │ └── Response.java
│ │ └── util/
│ │ ├── HostUtils.java
│ │ └── PropertiesUtils.java
│ └── test/
│ ├── java/
│ │ └── com/
│ │ └── github/
│ │ └── xincao9/
│ │ └── yurpc/
│ │ └── YuRPCServerTest.java
│ └── resources/
│ └── config.properties
├── yurpc-sample/
│ ├── dependency-reduced-pom.xml
│ ├── pom.xml
│ └── src/
│ └── main/
│ ├── java/
│ │ └── com/
│ │ └── github/
│ │ └── xincao9/
│ │ └── yurpc/
│ │ └── sample/
│ │ ├── Say.java
│ │ ├── SayService.java
│ │ ├── consumer/
│ │ │ ├── ApplicationConsumer.java
│ │ │ ├── Benchmark.java
│ │ │ ├── Consumer.java
│ │ │ └── SayMethod.java
│ │ └── provider/
│ │ ├── ApplicationProvider.java
│ │ ├── Provider.java
│ │ └── SayServiceImpl.java
│ └── resources/
│ ├── application.yml
│ └── config.properties
└── yurpc-spring-boot-starter/
├── pom.xml
└── src/
└── main/
└── java/
└── com/
└── github/
└── xincao9/
└── yurpc/
└── spring/
└── boot/
└── starter/
├── ConfigConsts.java
├── EnableYuRPC.java
├── YUConsumer.java
├── YUProvider.java
├── YuRPCAutoConfiguration.java
├── YuRPCBeanPostProcessor.java
├── YuRPCImportBeanDefinitionRegistrar.java
└── ZKDiscoveryServiceImpl.java
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**
!**/src/test/**
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
### VS Code ###
.vscode/
================================================
FILE: CONTRIBUTING.md
================================================
Primary developer xincao9@gmail.com
================================================
FILE: LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: README.md
================================================
## yurpc
### 高性能RPC框架
#### yurpc 基于java的高性能开源RPC框架,使用方式上类似dubbo,提倡面向接口编程,如果您熟悉dubbo很容易迁移到yurpc;并享受高性能带来的服务体验。提供springboot高度集成starter包,实现零配置使用

#### yurpc 实战
**_maven 依赖_**
```
<dependency>
<groupId>com.github.xincao9</groupId>
<artifactId>yurpc-spring-boot-starter</artifactId>
<version>1.2.6</version>
</dependency>
```
**_实体定义_**
```
public class Say {
private Integer id;
private String body;
public Say(Integer id, String body) {
this.id = id;
this.body = body;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
@Override
public String toString() {
return JSONObject.toJSONString(this, SerializerFeature.DisableCircularReferenceDetect);
}
}
```
**_服务接口定义_**
```
public interface SayService {
Say perform(Say say);
}
```
**_提供者实现服务接口_**
```
@YUProvider
public class SayServiceImpl implements SayService {
@Override
public Say perform(Say say) {
return say;
}
}
```
**_服务提供者启动类_**
```
@SpringBootApplication
@EnableYuRPC(server = true)
public class ApplicationProvider {
public static void main(String... args) {
SpringApplication.run(ApplicationProvider.class, args);
}
}
```
**_服务消费者启动类_**
```
@SpringBootApplication
@EnableYuRPC(client = true)
public class ApplicationConsumer {
@YUConsumer
private SayService sayService; // 可以在任何spring bean 中注入yurpc服务
public static void main(String... args) {
SpringApplication.run(ApplicationConsumer.class, args);
}
@Bean
public CommandLineRunner commandLineRunner() {
return (String... args) -> {
for (int no = 0; no < 100; no++) {
String value = RandomStringUtils.randomAscii(128);
Say say = new Say(no, value);
System.out.println(sayService.perform(say)); // 远程调用yurpc服务
}
};
}
}
```
**_application.properties_**
```
## 服务发现注册或订阅的zk地址,暂时只支持zookeeper的注册中心
yurpc.discovery.zookeeper=localhost:2181
## 消费者配置
yurpc.client.connectionTimeoutMS=5000 // 服务连接超时时间
yurpc.client.invokeTimeoutMS=1000 // 服务调用超时时间
## 提供者配置
yurpc.server.port=12306 // 服务监听端口
```
**_温馨提示_**
* 欢迎查看示例 [examples](https://github.com/xincao9/yurpc/tree/master/yurpc-sample)
* yurpc 本身并不是必须和springboot一起使用,在示例中可以查看
* 单独使用的话,配置文件名为 config.properties,在示例中可以查看
* @EnableYuRPC(server = true, client = true) 意味着服务角色同为消费端和提供者使用
#### 联系方式
* [https://github.com/xincao9/yurpc/issues](https://github.com/xincao9/yurpc/issues)
* [https://issues.sonatype.org/browse/OSSRH-47112](https://issues.sonatype.org/browse/OSSRH-47112)
* xincao9@gmail.com
================================================
FILE: pom.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<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">
<modelVersion>4.0.0</modelVersion>
<groupId>com.github.xincao9</groupId>
<artifactId>yurpc</artifactId>
<name>yurpc</name>
<version>1.2.6</version>
<packaging>pom</packaging>
<description>high-performance RPC framework.</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.github.xincao9</groupId>
<artifactId>yurpc-core</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.github.xincao9</groupId>
<artifactId>yurpc-spring-boot-starter</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<modules>
<module>yurpc-core</module>
<module>yurpc-spring-boot-starter</module>
<module>yurpc-sample</module>
</modules>
<url>https://github.com/xincao9/yurpc</url>
<developers>
<developer>
<email>xincao9@gmail.com</email>
<name>xin.cao</name>
<roles>
<role>owner</role>
</roles>
<url>https://github.com/xincao9</url>
<organization>xincao9</organization>
<organizationUrl>https://github.com/xincao9/</organizationUrl>
</developer>
</developers>
<organization>
<name>Personal</name>
<url>https://github.com/xincao9</url>
</organization>
<issueManagement>
<system>Github Issues</system>
<url>https://github.com/xincao9/yurpc/issues</url>
</issueManagement>
<licenses>
<license>
<name>The Apache Software License, Version 2.0</name>
<url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
<distribution>repo</distribution>
</license>
</licenses>
<scm>
<tag>master</tag>
<url>git@github.com:xincao9/yurpc.git</url>
<connection>scm:git:git@github.com:xincao9/yurpc.git</connection>
<developerConnection>scm:git:git@github.com:xincao9/yurpc.git</developerConnection>
</scm>
<distributionManagement>
<repository>
<id>sonatype-oss</id>
<url>https://oss.sonatype.org/service/local/staging/deploy/maven2</url>
</repository>
<snapshotRepository>
<id>sonatype-oss</id>
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
</snapshotRepository>
</distributionManagement>
<profiles>
<profile>
<id>release</id>
<build>
<plugins>
<plugin>
<groupId>org.sonatype.plugins</groupId>
<artifactId>nexus-staging-maven-plugin</artifactId>
<version>1.6.8</version>
<extensions>true</extensions>
<configuration>
<serverId>sonatype-oss</serverId>
<nexusUrl>https://oss.sonatype.org/</nexusUrl>
<autoReleaseAfterClose>true</autoReleaseAfterClose>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
<version>1.6</version>
<executions>
<execution>
<id>sign-artifacts</id>
<phase>verify</phase>
<goals>
<goal>sign</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.0.1</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>jar-no-fork</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>3.1.0</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>
================================================
FILE: yurpc-core/pom.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<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">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.github.xincao9</groupId>
<artifactId>yurpc</artifactId>
<version>1.2.6</version>
</parent>
<artifactId>yurpc-core</artifactId>
<packaging>jar</packaging>
<name>yurpc-core</name>
<description>high-performance RPC framework.</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<netty.version>4.1.50.Final</netty.version>
<fastjson.version>1.2.71</fastjson.version>
<slf4j.version>1.7.25</slf4j.version>
<commons-lang3.version>3.7</commons-lang3.version>
<commons-codec.version>1.11</commons-codec.version>
<junit.version>4.13.1</junit.version>
<jmh.version>1.23</jmh.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>${netty.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jul-to-slf4j</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>${commons-codec.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${jmh.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jul-to-slf4j</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
================================================
FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/DiscoveryService.java
================================================
/*
* Copyright 2020 xincao9@gmail.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.xincao9.yurpc.core;
import com.github.xincao9.yurpc.core.protocol.Endpoint;
import java.util.List;
/**
* 服务注册与发现组件
*
* @author xincao9@gmail.com
*/
public interface DiscoveryService {
/**
* 注册
*
* @param endpoint 服务信息
*/
void register (Endpoint endpoint);
/**
* 获取注册表
*
* @param service 服务名字(接口名)
* @return 节点列表
*/
List<Endpoint> query (String service);
/**
* 续约
*
* @param instanceId 当前实例的id
*/
void renew (String instanceId);
/**
* 取消
*
* @param instanceId 当前实例的id
*/
void cancel (String instanceId);
}
================================================
FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/YuRPCClient.java
================================================
/*
* Copyright 2020 xincao9@gmail.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.xincao9.yurpc.core;
import com.github.xincao9.yurpc.core.config.ClientConfig;
import com.github.xincao9.yurpc.core.impl.YuRPCClientImpl;
import com.github.xincao9.yurpc.core.protocol.Request;
import com.github.xincao9.yurpc.core.protocol.Response;
import java.util.Map;
/**
* 客户端
*
* @author xincao9@gmail.com
*/
public interface YuRPCClient {
/**
* 调用方法
*
* @param <T> 类型
* @param request 请求
* @return 调用结果
* @throws Throwable 异常
*/
<T> Response<T> invoke(Request request) throws Throwable;
/**
* 启动
*
* @throws java.lang.Throwable 异常
*/
void start() throws Throwable;
/**
* 关闭
*
* @throws java.lang.Throwable 异常
*/
void shutdown() throws Throwable;
/**
* 获得客户端
*
* @param filename 配置文件
* @param discoveryService 服务组件
* @return 客户端
*/
static YuRPCClient defaultYuRPCClient(String filename, DiscoveryService discoveryService) {
ClientConfig.init(filename);
return new YuRPCClientImpl(discoveryService);
}
/**
* 获得客户端
*
* @return 客户端
*/
static YuRPCClient defaultYuRPCClient() {
return YuRPCClient.defaultYuRPCClient("", null);
}
/**
* 获得客户端
*
* @param discoveryService 服务组件
* @return 客户端
*/
static YuRPCClient defaultYuRPCClient(DiscoveryService discoveryService) {
return YuRPCClient.defaultYuRPCClient("", discoveryService);
}
/**
* 获得请求对象容器
*
* @return 请求对象容器
*/
Map<Long, Request> getRequests();
/**
* 获得接口的代理
*
* @param <T> 类型
* @param clazz 接口
* @return 代理对象
*/
<T> T proxy(Class<T> clazz);
/**
* 修改器
*
* @param discoveryService 服务发现和注册组件
*/
void setDiscoveryService(DiscoveryService discoveryService);
}
================================================
FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/YuRPCServer.java
================================================
/*
* Copyright 2020 xincao9@gmail.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.xincao9.yurpc.core;
import com.github.xincao9.yurpc.core.impl.YuRPCServerImpl;
import com.github.xincao9.yurpc.core.config.ServerConfig;
/**
* 服务组件
*
* @author xincao9@gmail.com
*/
public interface YuRPCServer {
/**
* 启动
*
* @throws java.lang.Throwable
*/
void start() throws Throwable;
/**
* 关闭
*
* @throws java.lang.Throwable
*/
void shutdown() throws Throwable;
/**
* 获得服务端
*
* @param filename 配置文件名
* @param discovery 服务发现组件
* @return 服务端
*/
static YuRPCServer defaultYuRPCServer(String filename, DiscoveryService discovery) throws RuntimeException {
ServerConfig.init(filename);
return new YuRPCServerImpl(discovery);
}
/**
* 获得服务端
*
* @return 服务端
*/
static YuRPCServer defaultYuRPCServer() {
return YuRPCServer.defaultYuRPCServer("", null);
}
/**
* 获得服务端
*
* @param port 端口
* @param discoveryService 服务发现组件
* @return
*/
static YuRPCServer defaultYuRPCServer(Integer port, DiscoveryService discoveryService) {
ServerConfig.port = port;
return new YuRPCServerImpl(port, discoveryService);
}
/**
* 获得服务端
*
* @param filename 配置文件名
* @return 服务端
*/
static YuRPCServer defaultYuRPCServer(String filename) {
return YuRPCServer.defaultYuRPCServer(filename, null);
}
/**
* 获得服务端
*
* @param discovery 服务发现组件
* @return 服务端
*/
static YuRPCServer defaultYuRPCServer(DiscoveryService discovery) {
return YuRPCServer.defaultYuRPCServer("", discovery);
}
/**
* 服务注册
*
* @param <T> 组建类型
* @param obj 服务组件
*/
<T> void register(T obj);
/**
* 获取组建
*
* @param name 组建类型名
* @return 服务组件
*/
Object getBean(String name);
/**
* 修改器
*
* @param discoveryService 服务发现和注册组件
*/
void setDiscoveryService(DiscoveryService discoveryService);
}
================================================
FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/codec/StringDecoder.java
================================================
/*
* Copyright 2020 xincao9@gmail.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.xincao9.yurpc.core.codec;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.List;
/**
* 消息解码
*
* @author xincao9@gmail.com
*/
public class StringDecoder extends ByteToMessageDecoder {
/**
* 解码
*
* @param chc
* @param byteBuf
* @param list
* @throws Exception
*/
@Override
protected void decode(ChannelHandlerContext chc, ByteBuf byteBuf, List<Object> list) throws Exception {
try {
do {
int readerIndex = byteBuf.readerIndex();
int readableBytesSize = byteBuf.readableBytes();
if (readableBytesSize < 4) {
byteBuf.readerIndex(readerIndex);
break;
}
int size = byteBuf.readInt();
if (readableBytesSize - 4 < size) {
byteBuf.readerIndex(readerIndex);
break;
}
byteBuf.readerIndex(readerIndex);
ByteBuffer byteBuffer = ByteBuffer.allocate(4 + size);
byteBuf.readBytes(byteBuffer);
byte[] data = byteBuffer.array();
byte[] body = Arrays.copyOfRange(data, 4, data.length);
list.add(new String(body, "UTF-8"));
} while (byteBuf.isReadable());
} finally {
if (byteBuf.isReadable()) {
byteBuf.discardReadBytes();
}
}
}
}
================================================
FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/codec/StringEncoder.java
================================================
/*
* Copyright 2020 xincao9@gmail.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.xincao9.yurpc.core.codec;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import java.util.Objects;
import org.apache.commons.lang3.StringUtils;
/**
* 消息编码
*
* @author xincao9@gmail.com
*/
public class StringEncoder extends MessageToByteEncoder<Object> {
/**
* 编码
*
* @param chc
* @param object
* @param byteBuf
* @throws Exception
*/
@Override
protected void encode(ChannelHandlerContext chc, Object object, ByteBuf byteBuf) throws Exception {
Objects.requireNonNull(object);
if (!(object instanceof String)) {
return;
}
String str = (String) object;
if (StringUtils.isBlank(str)) {
return;
}
byte[] data = str.getBytes("UTF-8");
byteBuf.writeInt(data.length);
byteBuf.writeBytes(data);
}
}
================================================
FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/config/ClientConfig.java
================================================
/*
* Copyright 2020 xincao9@gmail.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.xincao9.yurpc.core.config;
import com.github.xincao9.yurpc.core.protocol.Pair;
import com.github.xincao9.yurpc.core.constant.ClientConsts;
import com.github.xincao9.yurpc.core.constant.SystemConsts;
import com.github.xincao9.yurpc.core.util.PropertiesUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
/**
* 客户端配置
*
* @author xincao9@gmail.com
*/
public class ClientConfig {
public static List<Pair<String, Integer>> serverList = new ArrayList(1);
public static Integer connectionTimeoutMS;
public static Integer invokeTimeoutMS;
/**
* 初始化客户端配置
*
* @param filename 配置文件名
*/
public static void init(String filename) {
Properties pros = PropertiesUtils.read(filename, SystemConsts.DEFAULT_CONFIG_FILENAME);
init(pros);
}
/**
* 初始化客户端配置
*
* @param pros 属性文件
*/
public static void init(Properties pros) {
String serverListStr = pros.getProperty(ClientConsts.SERVER_LIST, ClientConsts.DEFAULT_SERVER_LIST);
String[] servers = serverListStr.split(",");
for (String server : servers) {
serverList.add(new Pair(server.split(":")[0], Integer.valueOf(server.split(":")[1])));
}
connectionTimeoutMS = Integer.valueOf(pros.getProperty(ClientConsts.CONNECTION_TIMEOUT_MS, ClientConsts.DEFAULT_CONNECTION_TIMEOUT_MS));
invokeTimeoutMS = Integer.valueOf(pros.getProperty(ClientConsts.INVOKE_TIMEOUT_MS, ClientConsts.DEFAULT_INVOKE_TIMEOUT_MS));
}
}
================================================
FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/config/ServerConfig.java
================================================
/*
* Copyright 2020 xincao9@gmail.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.xincao9.yurpc.core.config;
import com.github.xincao9.yurpc.core.constant.ServerConsts;
import com.github.xincao9.yurpc.core.constant.SystemConsts;
import com.github.xincao9.yurpc.core.util.PropertiesUtils;
import java.util.Properties;
/**
* 服务配置类
*
* @author xincao9@gmail.com
*/
public class ServerConfig {
public static Integer port;
public static Integer ioThreadBoss = ServerConsts.DEFAULT_IO_THREAD_BOSS;
public static Integer ioThreadWorker = ServerConsts.DEFAULT_IO_THREAD_WORKER;
/**
* 初始化服务组件配置
*
* @param filename 配置文件名
*/
public static void init(String filename) {
Properties pros = PropertiesUtils.read(filename, SystemConsts.DEFAULT_CONFIG_FILENAME);
init(pros);
}
/**
* 初始化服务组件配置
*
* @param pros 属性文件
*/
public static void init(Properties pros) {
port = Integer.valueOf(pros.getProperty(ServerConsts.PORT, ServerConsts.DEFAULT_PORT));
if (port <= 0 || port > 65535) {
port = Integer.valueOf(ServerConsts.DEFAULT_PORT);
}
}
}
================================================
FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/constant/ClientConsts.java
================================================
/*
* Copyright 2020 xincao9@gmail.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.xincao9.yurpc.core.constant;
/**
* 客户端常量
*
* @author xincao9@gmail.com
*/
public class ClientConsts {
public static final String SERVER_LIST = "yurpc.client.serverList";
public static final String DEFAULT_SERVER_LIST = "127.0.0.1:12306";
public static final String CONNECTION_TIMEOUT_MS = "yurpc.client.connectionTimeoutMS";
public static final String DEFAULT_CONNECTION_TIMEOUT_MS = "5000";
public static final String INVOKE_TIMEOUT_MS = "yurpc.client.invokeTimeoutMS";
public static final String DEFAULT_INVOKE_TIMEOUT_MS = "1000";
}
================================================
FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/constant/ResponseCode.java
================================================
/*
* Copyright 2020 xincao9@gmail.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.xincao9.yurpc.core.constant;
/**
* 响应码
*
* @author xincao9@gmail.com
*/
public class ResponseCode {
public static final Integer OK = 0;
public static final String OK_MSG = "OK";
public static final Integer INVOKE_TIMEOUT = 1;
public static final String INVOKE_TIMEOUT_MSG = "INVOKE TIMEOUT";
public static final Integer CONNECTION_FAILURE = 2;
public static final String CONNECTION_FAILURE_MSG = "CONNECTION FAILURE";
public static final Integer SERVER_ERROR = 3;
public static final String SERVER_ERROR_MSG = "SERVER ERROR";
public static final Integer PARAMETER_ERROR = 4;
public static final String PARAMETER_ERROR_MSG = "PARAMETER ERROR";
public static final Integer NOT_FOUND_COMPONENT = 5;
public static final String NOT_FOUND_COMPONENT_MSG = "COMPONENT CLASS: %s NOT FOUND";
public static final Integer NOT_FOUND_METHOD = 6;
public static final String NOT_FOUND_METHOD_MSG = "CLASS: %s METHOD: %s NOT FOUND!";
}
================================================
FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/constant/ServerConsts.java
================================================
/*
* Copyright 2020 xincao9@gmail.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.xincao9.yurpc.core.constant;
/**
* 服务端常量
*
* @author xincao9@gmail.com
*/
public class ServerConsts {
public static final String PORT = "yurpc.server.port";
public static final String DEFAULT_PORT = "12306";
public static final Integer DEFAULT_IO_THREAD_BOSS = 1;
public static final Integer DEFAULT_IO_THREAD_WORKER = Runtime.getRuntime().availableProcessors();
}
================================================
FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/constant/SystemConsts.java
================================================
/*
* Copyright 2020 xincao9@gmail.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.xincao9.yurpc.core.constant;
/**
*
* @author xincao9@gmail.com
*/
public class SystemConsts {
public static final String DEFAULT_CONFIG_FILENAME = "/config.properties";
}
================================================
FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/impl/ClientHandler.java
================================================
/*
* Copyright 2020 xincao9@gmail.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.xincao9.yurpc.core.impl;
import com.github.xincao9.yurpc.core.YuRPCClient;
import com.github.xincao9.yurpc.core.protocol.Request;
import com.alibaba.fastjson.JSONObject;
import com.github.xincao9.yurpc.core.protocol.Response;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 客户端输入流处理器
*
* @author xincao9@gmail.com
*/
@Sharable
public class ClientHandler extends SimpleChannelInboundHandler<String> {
private static final Logger LOGGER = LoggerFactory.getLogger(ClientHandler.class);
private YuRPCClient yuRPCClient;
/**
* 读取输入流处理
*
* @param ctx channel上下文
* @param msg 消息
* @throws Exception 异常
*/
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
Response response = JSONObject.parseObject(msg, Response.class);
LOGGER.debug("msg = {}", msg);
long responseId = response.getId();
Map<Long, Request> requests = yuRPCClient.getRequests();
if (requests.containsKey(responseId)) {
Request request = requests.get(responseId);
requests.remove(responseId);
request.putResponse(response);
}
}
/**
* 修改器
*
* @param yuRPCClient 客户端
*/
public void setYuRPCClient(YuRPCClient yuRPCClient) {
this.yuRPCClient = yuRPCClient;
}
}
================================================
FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/impl/ClientInvocationHandler.java
================================================
/*
* Copyright 2020 xincao9@gmail.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.xincao9.yurpc.core.impl;
import com.github.xincao9.yurpc.core.YuRPCClient;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.github.xincao9.yurpc.core.protocol.Request;
import com.github.xincao9.yurpc.core.protocol.Response;
import com.github.xincao9.yurpc.core.constant.ResponseCode;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.Type;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 客户端调用代理
*
* @author xincao9@gmail.com
*/
public class ClientInvocationHandler implements InvocationHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(ClientInvocationHandler.class);
private YuRPCClient yuRPCClient;
private final Map<Class, Object> proxies = new ConcurrentHashMap();
/**
* 代理方法调用
*
* @param proxy 代理对象
* @param method 调用的方法
* @param args 调用方法的参数
* @return 调用方法的结果
* @throws Throwable 异常
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
StringBuilder sb = new StringBuilder();
sb.append(method.getDeclaringClass().getTypeName()).append('.');
sb.append(method.getName());
Type returnType = method.getReturnType();
Request request;
String[] paramTypes = null;
Class<?>[] clazzParamTypes = method.getParameterTypes();
if (clazzParamTypes != null && clazzParamTypes.length > 0) {
paramTypes = new String[clazzParamTypes.length];
for (int i = 0; i < clazzParamTypes.length; i++) {
paramTypes[i] = clazzParamTypes[i].getTypeName();
}
}
if ("void".equalsIgnoreCase(returnType.getTypeName())) {
request = Request.createRequest(Boolean.FALSE, sb.toString(), args);
} else {
request = Request.createRequest(Boolean.TRUE, sb.toString(), args);
}
request.setParamTypes(paramTypes);
long startTime = System.currentTimeMillis();
Response response = yuRPCClient.invoke(request);
if (response == null) {
return null;
}
LOGGER.debug("requestId = {}, invoke costTime = {}", request.getId(), System.currentTimeMillis() - startTime);
LOGGER.debug("requestId = {}, c to s costTime = {} ms, s to c costTime {} ms", request.getId(), response.getCreateTime() - request.getCreateTime(), System.currentTimeMillis() - response.getCreateTime());
if (Objects.equals(response.getCode(), ResponseCode.OK) && !"void".equalsIgnoreCase(returnType.getTypeName())) {
if (response.getData() == null) {
return null;
}
Class clazz = Class.forName(returnType.getTypeName());
return JSON.parseObject(JSONObject.toJSONString(response.getData(), SerializerFeature.DisableCircularReferenceDetect), clazz);
}
if (!Objects.equals(response.getCode(), ResponseCode.OK)) {
LOGGER.error("request = {}, code = {}, msg = {}", request, response.getCode(), response.getMsg());
throw new RuntimeException(response.getMsg());
}
return null;
}
/**
* 获得接口代理对象
*
* @param <T> 接口类型
* @param clazz 接口
* @return 接口的代理类
*/
public <T> T proxy(Class<T> clazz) {
if (!clazz.isInterface()) {
LOGGER.error("{} is not interface", clazz.getCanonicalName());
return null;
}
if (proxies.containsKey(clazz)) {
return (T) proxies.get(clazz);
}
Object proxy = Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz}, this);
proxies.put(clazz, proxy);
return (T) proxy;
}
/**
* 修改器
*
* @param yuRPCClient 客户端
*/
public void setYuRPCClient(YuRPCClient yuRPCClient) {
this.yuRPCClient = yuRPCClient;
}
}
================================================
FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/impl/HeartbeatHandler.java
================================================
/*
* Copyright 2020 xincao9@gmail.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.xincao9.yurpc.core.impl;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.CharsetUtil;
/**
* 心跳处理器
*
* @author xincao9@gmail.com
*/
@Sharable
public class HeartbeatHandler extends ChannelInboundHandlerAdapter {
private static final ByteBuf HEARTBEAT_SEQUENCE = Unpooled.unreleasableBuffer(Unpooled.copiedBuffer("HEARTBEAT", CharsetUtil.UTF_8));
/**
* 事件触发
*
* @param ctx 上下文
* @param evt 事件对象
* @throws Exception 异常
*/
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof IdleStateEvent) {
ctx.writeAndFlush(HEARTBEAT_SEQUENCE.duplicate()).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
} else {
super.userEventTriggered(ctx, evt);
}
}
}
================================================
FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/impl/ServerHandler.java
================================================
/*
* Copyright 2020 xincao9@gmail.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.xincao9.yurpc.core.impl;
import com.github.xincao9.yurpc.core.YuRPCServer;
import com.alibaba.fastjson.JSONObject;
import com.github.xincao9.yurpc.core.protocol.Request;
import com.github.xincao9.yurpc.core.protocol.Response;
import com.github.xincao9.yurpc.core.constant.ResponseCode;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 服务输入流处理
*
* @author xincao9@gmail.com
*/
@Sharable
public class ServerHandler extends SimpleChannelInboundHandler<String> {
private static final Logger LOGGER = LoggerFactory.getLogger(ServerHandler.class);
private YuRPCServer yuRPCServer;
private final ThreadPoolExecutor processor;
private final Map<String, Class> nameClass = new ConcurrentHashMap();
public ServerHandler() {
processor = new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors(),
256,
60L,
TimeUnit.SECONDS,
new SynchronousQueue<>(), new ThreadPoolExecutor.CallerRunsPolicy());
}
private void submit(Boolean requestType, Method method, Long rid, Object component, Object[] params, ChannelHandlerContext ctx) {
processor.submit(() -> {
exec(requestType, method, rid, component, params, ctx);
});
}
private void exec(Boolean requestType, Method method, Long rid, Object component, Object[] params, ChannelHandlerContext ctx) {
try {
Response response;
if (requestType) {
response = Response.createResponse(rid, method.invoke(component, params));
} else {
method.invoke(component, params);
response = Response.createResponse(rid, null);
}
ctx.channel().writeAndFlush(response.toString());
} catch (Throwable e) {
LOGGER.error(e.getMessage());
exception(ctx, rid, ResponseCode.SERVER_ERROR, e.getMessage());
}
}
/**
* 处理请求
*
* @param ctx 上下文
* @param str 消息体
* @throws Exception 异常
*/
@Override
protected void channelRead0(ChannelHandlerContext ctx, String str) throws Exception {
Request request = JSONObject.parseObject(str, Request.class);
if (request.getEventType()) {
return;
}
long rid = request.getId();
try {
String name = request.getMethod();
if (StringUtils.isBlank(name)) {
exception(ctx, rid, ResponseCode.PARAMETER_ERROR, ResponseCode.PARAMETER_ERROR_MSG);
return;
}
String classname = StringUtils.substringBeforeLast(name, ".");
String methodname = StringUtils.substringAfterLast(name, ".");
Object component = yuRPCServer.getBean(classname);
if (component == null) {
exception(ctx, rid, ResponseCode.NOT_FOUND_COMPONENT, String.format(ResponseCode.NOT_FOUND_COMPONENT_MSG, classname));
return;
}
String[] paramTypes = request.getParamTypes();
Class<?> clazz = getClass(classname);
Method method;
Object[] params = null;
if (paramTypes == null || paramTypes.length <= 0) {
method = clazz.getMethod(methodname);
} else {
Class<?>[] clazzes = new Class<?>[paramTypes.length];
params = new Object[paramTypes.length];
for (int i = 0; i < paramTypes.length; i++) {
clazzes[i] = getClass(paramTypes[i]);
if (request.getParams() != null && request.getParams()[i] != null) {
params[i] = JSONObject.parseObject(JSONObject.toJSONString(request.getParams()[i]), clazzes[i]);
}
}
method = clazz.getMethod(methodname, clazzes);
}
if (method == null) {
exception(ctx, rid, ResponseCode.NOT_FOUND_METHOD, String.format(ResponseCode.NOT_FOUND_METHOD_MSG, classname, methodname));
return;
}
submit(request.getRequestType(), method, rid, component, params, ctx);
} catch (Throwable e) {
LOGGER.error(e.getMessage());
exception(ctx, rid, ResponseCode.SERVER_ERROR, e.getMessage());
}
}
/**
* @param classname
* @return
* @throws ClassNotFoundException
*/
private Class getClass(String classname) throws ClassNotFoundException {
if (!nameClass.containsKey(classname)) {
nameClass.put(classname, Class.forName(classname));
}
return nameClass.get(classname);
}
/**
* @param ctx
* @param id
* @param responseCode
* @param msg
*/
private void exception(ChannelHandlerContext ctx, Long id, Integer responseCode, String msg) {
ctx.channel().writeAndFlush(Response.createResponse(id, responseCode, msg).toString());
}
/**
* 修改器
*
* @param yuRPCServer 服务组件
*/
public void setYuRPCServer(YuRPCServer yuRPCServer) {
this.yuRPCServer = yuRPCServer;
}
}
================================================
FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/impl/YuRPCClientImpl.java
================================================
/*
* Copyright 2020 xincao9@gmail.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.xincao9.yurpc.core.impl;
import com.github.xincao9.yurpc.core.YuRPCClient;
import com.github.xincao9.yurpc.core.config.ClientConfig;
import com.github.xincao9.yurpc.core.protocol.Request;
import com.github.xincao9.yurpc.core.protocol.Response;
import com.github.xincao9.yurpc.core.codec.StringDecoder;
import com.github.xincao9.yurpc.core.codec.StringEncoder;
import com.github.xincao9.yurpc.core.constant.ResponseCode;
import com.github.xincao9.yurpc.core.protocol.Endpoint;
import com.github.xincao9.yurpc.core.DiscoveryService;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.epoll.Epoll;
import io.netty.channel.epoll.EpollEventLoopGroup;
import io.netty.channel.epoll.EpollSocketChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.concurrent.Future;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 客户端
*
* @author xincao9@gmail.com
*/
public class YuRPCClientImpl implements YuRPCClient {
private static final Logger LOGGER = LoggerFactory.getLogger(YuRPCClientImpl.class);
private final Map<Long, Request> requests = new ConcurrentHashMap();
private final Bootstrap bootstrap = new Bootstrap();
private final Map<String, Channel> addressChannel = new HashMap();
private EventLoopGroup workerGroup;
private ClientInvocationHandler clientInvocationHandler;
private DiscoveryService discoveryService;
/**
* 构造器
*
*/
public YuRPCClientImpl() {
this(null);
}
/**
* 构造器
*
* @param discoveryService 服务组件
*/
public YuRPCClientImpl(DiscoveryService discoveryService) {
this.discoveryService = discoveryService;
}
/**
* 启动
*
* @throws java.lang.Throwable 异常
*/
@Override
public void start() throws Throwable {
this.workerGroup = Epoll.isAvailable() ? new EpollEventLoopGroup(Runtime.getRuntime().availableProcessors()) : new NioEventLoopGroup(Runtime.getRuntime().availableProcessors());
ClientHandler clientHandler = new ClientHandler();
clientHandler.setYuRPCClient(this);
this.bootstrap.group(this.workerGroup).channel(Epoll.isAvailable() ? EpollSocketChannel.class : NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.option(ChannelOption.SO_KEEPALIVE, false)
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, ClientConfig.connectionTimeoutMS)
.option(ChannelOption.SO_SNDBUF, 65535)
.option(ChannelOption.SO_RCVBUF, 65535)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(
new StringEncoder(),
new StringDecoder(),
clientHandler,
new IdleStateHandler(0, 0, 60, TimeUnit.SECONDS),
new HeartbeatHandler()
);
}
});
clientInvocationHandler = new ClientInvocationHandler();
clientInvocationHandler.setYuRPCClient(this);
}
/**
* 关闭
*
* @throws java.lang.Throwable 异常
*/
@Override
public void shutdown() throws Throwable {
this.addressChannel.entrySet().forEach((entry) -> {
String address = entry.getKey();
Channel channel = entry.getValue();
if (channel != null) {
channel.close().addListener((Future<? super Void> future) -> {
LOGGER.warn("close the connection to the yurpc service address = {}, cause = {}", address, future.cause());
});
}
});
if (this.workerGroup != null) {
try {
this.workerGroup.shutdownGracefully().sync();
} catch (InterruptedException ex) {
LOGGER.error(ex.getMessage());
}
}
}
/**
* 调用方法
*
* @param <T> 类型
* @param request 请求
* @return 调用结果
* @throws Throwable 异常
*/
@Override
public <T> Response<T> invoke(Request request) throws Throwable {
Objects.requireNonNull(request);
if (discoveryService != null && !request.isDirect()) {
List<Endpoint> nodes = discoveryService.query(StringUtils.substringBeforeLast(request.getMethod(), "."));
if (nodes != null && !nodes.isEmpty()) {
Endpoint node = nodes.get(RandomUtils.nextInt(0, nodes.size()));
request.setHost(node.getHost());
request.setPort(node.getPort());
}
}
Channel channel = getChannel(request.getHost(), request.getPort());
if (channel == null) {
return Response.createResponse(request.getId(), ResponseCode.CONNECTION_FAILURE, ResponseCode.CONNECTION_FAILURE_MSG);
}
this.requests.put(request.getId(), request);
channel.writeAndFlush(request.toString()).addListener((ChannelFutureListener) (ChannelFuture f) -> {
if (f.isSuccess()) {
request.setSendOk(Boolean.TRUE);
return;
}
request.setSendOk(Boolean.FALSE);
this.requests.remove(request.getId());
request.putResponse(null);
LOGGER.error("yurpc.invoke() request = {} failure exception = {}", request, f.cause());
});
try {
return request.waitResponse(ClientConfig.invokeTimeoutMS, TimeUnit.MILLISECONDS);
} catch (Throwable e) {
LOGGER.error(e.getMessage());
}
this.requests.remove(request.getId());
request.putResponse(null);
LOGGER.error("yurpc.invoke() request = {} timeout (wait time > {} ms)", request, ClientConfig.invokeTimeoutMS);
return Response.createResponse(request.getId(), ResponseCode.INVOKE_TIMEOUT, ResponseCode.INVOKE_TIMEOUT_MSG);
}
/**
* 获取通道
*
* @param host 主机
* @param port 端口
* @return 通道
*/
private Channel getChannel(String host, int port) {
String address = String.format("%s:%d", host, port);
if (!this.addressChannel.containsKey(address)) {
synchronized (this) {
if (!this.addressChannel.containsKey(address)) {
ChannelFuture channelFuture = this.bootstrap.connect(new InetSocketAddress(host, port));
if (channelFuture.awaitUninterruptibly(ClientConfig.connectionTimeoutMS)) {
if (channelFuture.channel().isActive()) {
YuRPCClientImpl.this.addressChannel.put(address, channelFuture.channel());
}
}
}
}
}
Channel channel = this.addressChannel.get(address);
if (channel == null) {
LOGGER.error("getChannel() host = {} port = {} channel is null", host, port);
return null;
}
if (!channel.isActive()) {
this.addressChannel.remove(address);
LOGGER.error("getChannel() host = {} port = {} channel is inactive", host, port);
return null;
}
return channel;
}
/**
* 获得请求对象容器
*
* @return 请求对象容器
*/
@Override
public Map<Long, Request> getRequests() {
return this.requests;
}
/**
* 获得接口的代理
*
* @param <T> 类型
* @param clazz 接口
* @return 代理对象
*/
@Override
public <T> T proxy(Class<T> clazz) {
return this.clientInvocationHandler.proxy(clazz);
}
/**
* 修改器
*
* @param discoveryService 服务发现和注册组件
*/
@Override
public void setDiscoveryService(DiscoveryService discoveryService) {
this.discoveryService = discoveryService;
}
}
================================================
FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/impl/YuRPCServerImpl.java
================================================
/*
* Copyright 2020 xincao9@gmail.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.xincao9.yurpc.core.impl;
import com.github.xincao9.yurpc.core.YuRPCServer;
import com.github.xincao9.yurpc.core.codec.StringDecoder;
import com.github.xincao9.yurpc.core.codec.StringEncoder;
import com.github.xincao9.yurpc.core.config.ServerConfig;
import com.github.xincao9.yurpc.core.DiscoveryService;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.epoll.Epoll;
import io.netty.channel.epoll.EpollEventLoopGroup;
import io.netty.channel.epoll.EpollServerSocketChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.concurrent.Future;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.xincao9.yurpc.core.protocol.Endpoint;
/**
* 服务组件
*
* @author xincao9@gmail.com
*/
public class YuRPCServerImpl implements YuRPCServer {
private static final Logger LOGGER = LoggerFactory.getLogger(YuRPCServerImpl.class);
private final Integer port;
private EventLoopGroup bossGroup;
private EventLoopGroup workerGroup;
private final Integer boss;
private final Integer worker;
private DiscoveryService discoveryService;
/**
* 构造器
*/
public YuRPCServerImpl() {
this(null);
}
/**
* 构造器
*
* @param port 端口
* @param discoveryService 服务组件
*/
public YuRPCServerImpl(Integer port, DiscoveryService discoveryService) {
this.port = port;
this.boss = ServerConfig.ioThreadBoss;
this.worker = ServerConfig.ioThreadWorker;
this.discoveryService = discoveryService;
}
/**
* 构造器
*
* @param discoveryService 服务组件
*/
public YuRPCServerImpl(DiscoveryService discoveryService) {
this.port = ServerConfig.port;
this.boss = ServerConfig.ioThreadBoss;
this.worker = ServerConfig.ioThreadWorker;
this.discoveryService = discoveryService;
}
/**
* 启动
*
* @throws Throwable
*/
@Override
public void start() throws Throwable {
this.workerGroup = Epoll.isAvailable() ? new EpollEventLoopGroup(this.worker) : new NioEventLoopGroup(this.worker);
ServerBootstrap bootstrap = new ServerBootstrap();
ServerHandler serverHandler = new ServerHandler();
serverHandler.setYuRPCServer(this);
if (this.boss == 0) {
bootstrap.group(this.workerGroup);
} else {
this.bossGroup = Epoll.isAvailable() ? new EpollEventLoopGroup(this.boss) : new NioEventLoopGroup(this.boss);
bootstrap.group(this.bossGroup, this.workerGroup);
}
bootstrap.channel(Epoll.isAvailable() ? EpollServerSocketChannel.class : NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(
new StringEncoder(),
new StringDecoder(),
serverHandler,
new IdleStateHandler(0, 0, 60, TimeUnit.SECONDS),
new HeartbeatHandler()
);
}
})
.childOption(ChannelOption.SO_KEEPALIVE, false)
.childOption(ChannelOption.TCP_NODELAY, true);
ChannelFuture f = bootstrap.bind("0.0.0.0", port).addListener((Future<? super Void> future) -> {
LOGGER.warn("start the yurpc service port = {}, cause = {}", this.port, future.cause());
});
f.channel().closeFuture().addListener((Future<? super Void> future) -> {
LOGGER.warn("turn off yurpc service port = {}, cause = {}", this.port, future.cause());
});
}
/**
* 关闭
*
* @throws Throwable
*/
@Override
public void shutdown() throws Throwable {
if (this.workerGroup != null) {
this.workerGroup.shutdownGracefully();
}
if (this.bossGroup != null) {
this.bossGroup.shutdownGracefully();
}
}
private final Map<String, Object> componentes = new HashMap();
/**
* 服务注册
*
* @param <T> 组建类型
* @param obj 服务组件
*/
@Override
public <T> void register(T obj) {
Objects.requireNonNull(obj);
Class<?>[] clazzes = obj.getClass().getInterfaces();
if (clazzes == null || clazzes.length <= 0) {
LOGGER.error("class = {} invalid format", obj.getClass().getCanonicalName());
return;
}
for (Class clazz : clazzes) {
componentes.put(clazz.getTypeName(), obj);
if (discoveryService != null) {
discoveryService.register(Endpoint.create(clazz.getTypeName()));
}
}
}
/**
* 获取组建
*
* @param name 组建类型名
* @return 服务组件
*/
@Override
public Object getBean(String name) {
return componentes.get(name);
}
/**
* 修改器
*
* @param discoveryService 服务发现和注册组件
*/
@Override
public void setDiscoveryService(DiscoveryService discoveryService) {
this.discoveryService = discoveryService;
}
}
================================================
FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/protocol/Endpoint.java
================================================
/*
* Copyright 2020 xincao9@gmail.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.xincao9.yurpc.core.protocol;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.github.xincao9.yurpc.core.config.ServerConfig;
import com.github.xincao9.yurpc.core.util.HostUtils;
import java.util.Date;
import java.util.UUID;
/**
* 端点
*
* @author xincao9@gmail.com
*/
public class Endpoint {
private String instanceId;
private String host;
private Integer port;
private String name;
private Date createTime;
/**
* 创建端点
*
* @param name 服务名字
* @return 端点
*/
public static Endpoint create (String name) {
Endpoint node = new Endpoint();
node.setInstanceId(UUID.randomUUID().toString());
node.setHost(HostUtils.getLocalAddress());
node.setPort(ServerConfig.port);
node.setName(name);
node.setCreateTime(new Date());
return node;
}
public String getInstanceId() {
return instanceId;
}
public void setInstanceId(String instanceId) {
this.instanceId = instanceId;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@Override
public String toString () {
return JSONObject.toJSONString(this, SerializerFeature.DisableCircularReferenceDetect);
}
}
================================================
FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/protocol/Pair.java
================================================
/*
* Copyright 2020 xincao9@gmail.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.xincao9.yurpc.core.protocol;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
/**
* 一对
*
* @author xincao9@gmail.com
* @param <T1> 类型1
* @param <T2> 类型2
*/
public class Pair<T1, T2> {
private T1 o1; // 对象1
private T2 o2; // 对象2
public Pair() {
}
public Pair(T1 o1, T2 o2) {
this.o1 = o1;
this.o2 = o2;
}
public T1 getO1() {
return o1;
}
public void setO1(T1 o1) {
this.o1 = o1;
}
public T2 getO2() {
return o2;
}
public void setO2(T2 o2) {
this.o2 = o2;
}
@Override
public String toString() {
return JSONObject.toJSONString(this, SerializerFeature.DisableCircularReferenceDetect);
}
}
================================================
FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/protocol/Request.java
================================================
/*
* Copyright 2020 xincao9@gmail.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.xincao9.yurpc.core.protocol;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.github.xincao9.yurpc.core.config.ClientConfig;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.commons.lang3.RandomUtils;
/**
* 请求体
*
* @author xincao9@gmail.com
*/
public class Request {
private Boolean requestType; // request with/without return value
private Boolean eventType; // whether the request is an event message
private Long id; // request id
private Object[] params;
private String[] paramTypes;
private static final AtomicLong COUNTER = new AtomicLong(0);
private String method;
private Long createTime;
private String host;
private int port;
private final CountDownLatch countDownLatch = new CountDownLatch(1);
private Response response;
private Boolean sendOk;
private Boolean direct = Boolean.FALSE;
/**
* 创建请求体
*
* @param requestType
* @param method
* @param params
* @return
*/
public static Request createRequest(Boolean requestType, String method, Object... params) {
Request request = new Request();
request.setRequestType(requestType);
request.setEventType(false);
request.setId(COUNTER.getAndIncrement());
request.setMethod(method);
request.setParams(params);
request.setCreateTime(System.currentTimeMillis());
Pair<String, Integer> pair = ClientConfig.serverList.get(RandomUtils.nextInt(0, ClientConfig.serverList.size()));
request.setHost(pair.getO1());
request.setPort(pair.getO2());
return request;
}
/**
* 创建事件
*
* @param method
* @return
*/
public static Request createEvent(String method) {
Request request = new Request();
request.setRequestType(false);
request.setEventType(true);
request.setId(COUNTER.getAndIncrement());
request.setMethod(method);
request.setCreateTime(System.currentTimeMillis());
Pair<String, Integer> pair = ClientConfig.serverList.get(RandomUtils.nextInt(0, ClientConfig.serverList.size()));
request.setHost(pair.getO1());
request.setPort(pair.getO2());
return request;
}
/**
* 等待响应
*
* @param <T>
* @param timeout
* @param timeUnit
* @return
* @throws InterruptedException
*/
public <T> Response<T> waitResponse(int timeout, TimeUnit timeUnit) throws InterruptedException {
this.countDownLatch.await(timeout, timeUnit);
return response;
}
/**
* 设置返回值
*
* @param response
*/
public void putResponse(Response response) {
this.response = response;
this.countDownLatch.countDown();
}
public Boolean getRequestType() {
return requestType;
}
public void setRequestType(Boolean requestType) {
this.requestType = requestType;
}
public Boolean getEventType() {
return eventType;
}
public void setEventType(Boolean eventType) {
this.eventType = eventType;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Object[] getParams() {
return params;
}
public void setParams(Object[] params) {
this.params = params;
}
public String[] getParamTypes() {
return paramTypes;
}
public void setParamTypes(String[] paramTypes) {
this.paramTypes = paramTypes;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public Long getCreateTime() {
return createTime;
}
public void setCreateTime(Long createTime) {
this.createTime = createTime;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public Object getResponse() {
return response;
}
public void setResponse(Response response) {
this.response = response;
}
public Boolean getSendOk() {
return sendOk;
}
public void setSendOk(Boolean sendOk) {
this.sendOk = sendOk;
}
public Boolean isDirect () {
return getDirect();
}
public Boolean getDirect() {
return direct;
}
public void setDirect(Boolean direct) {
this.direct = direct;
}
@Override
public String toString() {
return JSONObject.toJSONString(this, SerializerFeature.DisableCircularReferenceDetect);
}
}
================================================
FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/protocol/Response.java
================================================
/*
* Copyright 2020 xincao9@gmail.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.xincao9.yurpc.core.protocol;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.github.xincao9.yurpc.core.constant.ResponseCode;
/**
* 响应体
*
* @author xincao9@gmail.com
* @param <T>
*/
public class Response<T> {
private Long id; // response id
private Integer code = ResponseCode.OK; // response code
private T data;
private String msg = ResponseCode.OK_MSG;
private final Long createTime = System.currentTimeMillis();
public static <T> Response<T> createResponse(Long id, T data) {
Response response = new Response();
response.setId(id);
response.setData(data);
return response;
}
public static <T> Response<T> createResponse(Long id, Integer code, String msg) {
Response response = new Response();
response.setId(id);
response.setCode(code);
response.setMsg(msg);
return response;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Long getCreateTime() {
return createTime;
}
@Override
public String toString() {
return JSONObject.toJSONString(this, SerializerFeature.DisableCircularReferenceDetect);
}
}
================================================
FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/util/HostUtils.java
================================================
/*
* Copyright 2020 xincao9@gmail.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.xincao9.yurpc.core.util;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 主机工具
*
* @author xincao9@gmail.com
*/
public class HostUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(HostUtils.class);
/**
* 获得本机IP地址
*
* @return 本机IP
*/
public static String getLocalAddress() {
try {
InetAddress candidateAddress = null; // 遍历所有的网络接口
Enumeration interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface face = (NetworkInterface) interfaces.nextElement(); // 在所有的接口下再遍历IP
Enumeration inetAddrs = face.getInetAddresses();
while (inetAddrs.hasMoreElements()) {
InetAddress inetAddr = (InetAddress) inetAddrs.nextElement();
if (!inetAddr.isLoopbackAddress()) { // 排除loopback类型地址
if (inetAddr.isSiteLocalAddress()) { // 如果是site-local地址,就是它了
return inetAddr.getHostAddress();
} else if (candidateAddress == null) { // site-local类型的地址未被发现,先记录候选地址
candidateAddress = inetAddr;
}
}
}
}
if (candidateAddress != null) {
return candidateAddress.getHostAddress();
}
InetAddress jdkSuppliedAddress = InetAddress.getLocalHost(); // 如果没有发现 non-loopback地址.只能用最次选的方案
return jdkSuppliedAddress.getHostAddress();
} catch (SocketException | UnknownHostException e) {
LOGGER.error(e.getMessage());
}
return null;
}
}
================================================
FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/util/PropertiesUtils.java
================================================
/*
* Copyright 2020 xincao9@gmail.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.xincao9.yurpc.core.util;
import java.io.IOException;
import java.util.Properties;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 属性工具类
*
* @author xincao9@gmail.com
*/
public class PropertiesUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(PropertiesUtils.class);
/**
* 读取属性文件
*
* @param filename
* @param defaultFilename
* @return
*/
public static Properties read(String filename, String defaultFilename) {
if (StringUtils.isBlank(filename)) {
LOGGER.warn("filename is empty");
filename = defaultFilename;
}
try {
Properties pros = new Properties();
pros.load(PropertiesUtils.class.getResourceAsStream(filename));
return pros;
} catch (IOException e) {
LOGGER.warn(e.getMessage());
}
return new Properties();
}
}
================================================
FILE: yurpc-core/src/test/java/com/github/xincao9/yurpc/YuRPCServerTest.java
================================================
/*
* Copyright 2020 xincao9@gmail.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.xincao9.yurpc;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.github.xincao9.yurpc.core.YuRPCClient;
import com.github.xincao9.yurpc.core.YuRPCServer;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.Test;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 服务组件测试
*
* @author xincao9@gmail.com
*/
@BenchmarkMode(Mode.Throughput)
@Warmup(iterations = 5)
@Measurement(iterations = 5, time = 5, timeUnit = TimeUnit.SECONDS)
@OutputTimeUnit(TimeUnit.SECONDS)
@State(Scope.Benchmark)
public class YuRPCServerTest {
private YuRPCServer yuRPCServer;
private YuRPCClient yuRPCClient;
private SayService sayService;
private AtomicInteger no = new AtomicInteger(0);
/**
* 启动服务组件
*
* @throws Throwable
*/
@Setup
public void setUp() throws Throwable {
yuRPCServer = YuRPCServer.defaultYuRPCServer();
yuRPCServer.register(new SayServiceImpl());
yuRPCServer.start();
yuRPCClient = YuRPCClient.defaultYuRPCClient();
yuRPCClient.start();
sayService = yuRPCClient.proxy(SayService.class);
}
/**
* 关闭服务组件
*
* @throws Throwable
*/
@TearDown
public void tearDown() throws Throwable {
yuRPCServer.shutdown();
yuRPCClient.shutdown();
}
@Benchmark
public void perform() {
String value = RandomStringUtils.randomAscii(128);
Say say = new Say(no.incrementAndGet(), value);
System.out.println(sayService.perform(say));
}
/**
* 客户端发送请求给服务端
*
* @throws Throwable
*/
@Test
public void testMethod() throws Throwable {
Options opt = new OptionsBuilder()
.include(getClass().getSimpleName())
.forks(1)
.build();
new Runner(opt).run();
}
public static class Say {
private Integer id;
private String body;
public Say(Integer id, String body) {
this.id = id;
this.body = body;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
@Override
public String toString() {
return JSONObject.toJSONString(this, SerializerFeature.DisableCircularReferenceDetect);
}
}
public interface SayService {
Say perform(Say say);
}
public static class SayServiceImpl implements SayService {
@Override
public Say perform(Say say) {
return say;
}
}
}
================================================
FILE: yurpc-core/src/test/resources/config.properties
================================================
yurpc.client.serverList=localhost:12306
yurpc.client.connectionTimeoutMS=5000
yurpc.client.invokeTimeoutMS=1000
yurpc.server.port=12306
================================================
FILE: yurpc-sample/dependency-reduced-pom.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<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">
<parent>
<artifactId>yurpc</artifactId>
<groupId>com.github.xincao9</groupId>
<version>1.2.6</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>yurpc-sample</artifactId>
<build>
<plugins>
<plugin>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.1</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer>
<mainClass>com.github.xincao9.yurpc.sample.provider.Provider</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<properties>
<spring-boot.version>2.1.3.RELEASE</spring-boot.version>
</properties>
</project>
================================================
FILE: yurpc-sample/pom.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<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">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.github.xincao9</groupId>
<artifactId>yurpc</artifactId>
<version>1.2.6</version>
</parent>
<artifactId>yurpc-sample</artifactId>
<packaging>jar</packaging>
<properties>
<spring-boot.version>2.1.3.RELEASE</spring-boot.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.github.xincao9</groupId>
<artifactId>yurpc-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.github.xincao9</groupId>
<artifactId>ptk-core</artifactId>
<version>1.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.1</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>com.github.xincao9.yurpc.sample.provider.Provider</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
================================================
FILE: yurpc-sample/src/main/java/com/github/xincao9/yurpc/sample/Say.java
================================================
/*
* Copyright 2020 xincao9@gmail.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.xincao9.yurpc.sample;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
/**
* 招呼
*
* @author xincao9@gmail.com
*/
public class Say {
private Integer id;
private String body;
public Say(Integer id, String body) {
this.id = id;
this.body = body;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
@Override
public String toString() {
return JSONObject.toJSONString(this, SerializerFeature.DisableCircularReferenceDetect);
}
}
================================================
FILE: yurpc-sample/src/main/java/com/github/xincao9/yurpc/sample/SayService.java
================================================
/*
* Copyright 2020 xincao9@gmail.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.xincao9.yurpc.sample;
/**
* 招呼服务
*
* @author xincao9@gmail.com
*/
public interface SayService {
/**
* 执行
*
* @param say 招呼
* @return 招呼
*/
Say perform(Say say);
}
================================================
FILE: yurpc-sample/src/main/java/com/github/xincao9/yurpc/sample/consumer/ApplicationConsumer.java
================================================
/*
* Copyright 2020 xincao9@gmail.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.xincao9.yurpc.sample.consumer;
import com.github.xincao9.yurpc.sample.Say;
import com.github.xincao9.yurpc.sample.SayService;
import com.github.xincao9.yurpc.spring.boot.starter.EnableYuRPC;
import com.github.xincao9.yurpc.spring.boot.starter.YUConsumer;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
/**
* 服务消费者
*
* @author xincao9@gmail.com
*/
@SpringBootApplication
@EnableYuRPC(client = true)
public class ApplicationConsumer {
@YUConsumer
private SayService sayService;
/**
* 入口方法
*
* @param args 参数
*/
public static void main(String... args) {
SpringApplication.run(ApplicationConsumer.class, args);
}
/**
* 启动时钩子
*
* @return
*/
@Bean
public CommandLineRunner commandLineRunner() {
return (String... args) -> {
for (int no = 0; no < 100; no++) {
String value = RandomStringUtils.randomAscii(128);
Say say = new Say(no, value);
System.out.println(sayService.perform(say));
}
};
}
}
================================================
FILE: yurpc-sample/src/main/java/com/github/xincao9/yurpc/sample/consumer/Benchmark.java
================================================
/*
* Copyright 2020 xincao9@gmail.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.xincao9.yurpc.sample.consumer;
import com.github.xincao9.ptk.core.PTKCore;
import com.github.xincao9.ptk.core.source.SequenceSource;
/**
* java -cp target/yurpc-sample-1.2.5.jar com.github.xincao9.yurpc.sample.consumer.Benchmark -m say -t -1 -c 16
*/
public class Benchmark {
public static void main(String... args) throws Throwable {
PTKCore.bootstrap(new SequenceSource(1000000), args);
}
}
================================================
FILE: yurpc-sample/src/main/java/com/github/xincao9/yurpc/sample/consumer/Consumer.java
================================================
/*
* Copyright 2020 xincao9@gmail.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.xincao9.yurpc.sample.consumer;
import com.github.xincao9.yurpc.core.YuRPCClient;
import com.github.xincao9.yurpc.sample.Say;
import com.github.xincao9.yurpc.sample.SayService;
import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 服务消费者
*
* @author xincao9@gmail.com
*/
public class Consumer {
private static final Logger LOGGER = LoggerFactory.getLogger(Consumer.class);
/**
* 入口方法
*
* @param args 参数
* @throws Throwable 异常
*/
public static void main(String... args) throws Throwable {
YuRPCClient yuRPCClient = YuRPCClient.defaultYuRPCClient();
yuRPCClient.start();
SayService sayService = yuRPCClient.proxy(SayService.class);
for (int no = 0; no < 100; no++) {
String value = RandomStringUtils.randomAscii(128);
Say say = new Say(no, value);
System.out.println(sayService.perform(say));
}
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
try {
yuRPCClient.shutdown();
} catch (Throwable ex) {
LOGGER.error(ex.getMessage());
}
}));
}
}
================================================
FILE: yurpc-sample/src/main/java/com/github/xincao9/yurpc/sample/consumer/SayMethod.java
================================================
/*
* Copyright 2020 xincao9@gmail.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.xincao9.yurpc.sample.consumer;
import com.github.xincao9.ptk.core.Method;
import com.github.xincao9.ptk.core.annotation.Test;
import com.github.xincao9.yurpc.core.YuRPCClient;
import com.github.xincao9.yurpc.sample.Say;
import com.github.xincao9.yurpc.sample.SayService;
import org.apache.commons.lang3.RandomStringUtils;
@Test(name="say")
public class SayMethod extends Method {
private SayService sayService;
public SayMethod () {
YuRPCClient yuRPCClient = YuRPCClient.defaultYuRPCClient();
try {
yuRPCClient.start();
} catch(Throwable e) {
throw new RuntimeException(e);
}
sayService = yuRPCClient.proxy(SayService.class);
}
@Override
public void exec(Object params) throws Exception {
Integer id = (Integer) params;
String value = RandomStringUtils.randomAscii(128);
Say say = new Say(id, value);
sayService.perform(say);
}
}
================================================
FILE: yurpc-sample/src/main/java/com/github/xincao9/yurpc/sample/provider/ApplicationProvider.java
================================================
/*
* Copyright 2020 xincao9@gmail.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.xincao9.yurpc.sample.provider;
import com.github.xincao9.yurpc.spring.boot.starter.EnableYuRPC;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* 服务提供者
*
* @author xincao9@gmail.com
*/
@SpringBootApplication
@EnableYuRPC(server = true)
public class ApplicationProvider {
/**
* 入口方法
*
* @param args 参数
*/
public static void main(String... args) {
SpringApplication.run(ApplicationProvider.class, args);
}
}
================================================
FILE: yurpc-sample/src/main/java/com/github/xincao9/yurpc/sample/provider/Provider.java
================================================
/*
* Copyright 2020 xincao9@gmail.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.xincao9.yurpc.sample.provider;
import com.github.xincao9.yurpc.core.YuRPCServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 服务提供者
* java -jar target/yurpc-sample-1.2.5.jar
*
* @author xincao9@gmail.com
*/
public class Provider {
private static final Logger LOGGER = LoggerFactory.getLogger(Provider.class);
/**
* 入口方法
*
* @param args 参数
* @throws java.lang.Throwable
*/
public static void main(String... args) throws Throwable {
YuRPCServer yuRPCServer = YuRPCServer.defaultYuRPCServer();
yuRPCServer.register(new SayServiceImpl());
yuRPCServer.start();
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
try {
yuRPCServer.shutdown();
} catch (Throwable ex) {
LOGGER.error(ex.getMessage());
}
}));
}
}
================================================
FILE: yurpc-sample/src/main/java/com/github/xincao9/yurpc/sample/provider/SayServiceImpl.java
================================================
/*
* Copyright 2020 xincao9@gmail.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.xincao9.yurpc.sample.provider;
import com.github.xincao9.yurpc.sample.Say;
import com.github.xincao9.yurpc.sample.SayService;
import com.github.xincao9.yurpc.spring.boot.starter.YUProvider;
/**
* 招呼服务实现
*
* @author xincao9@gmail.com
*/
@YUProvider
public class SayServiceImpl implements SayService {
/**
* 执行
*
* @param say 招呼
* @return 招呼
*/
@Override
public Say perform(Say say) {
return say;
}
}
================================================
FILE: yurpc-sample/src/main/resources/application.yml
================================================
yurpc:
discovery:
zookeeper: localhost:2181
client:
serverList: localhost:12306
connectionTimeoutMS: 5000
invokeTimeoutMS: 1000
server:
port: 12306
================================================
FILE: yurpc-sample/src/main/resources/config.properties
================================================
yurpc.client.serverList=localhost:12306
yurpc.client.connectionTimeoutMS=5000
yurpc.client.invokeTimeoutMS=1000
yurpc.server.port=12306
================================================
FILE: yurpc-spring-boot-starter/pom.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<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">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.github.xincao9</groupId>
<artifactId>yurpc</artifactId>
<version>1.2.6</version>
</parent>
<artifactId>yurpc-spring-boot-starter</artifactId>
<name>yurpc-spring-boot-starter</name>
<packaging>jar</packaging>
<properties>
<spring-boot.version>2.1.3.RELEASE</spring-boot.version>
<curator.version>4.2.0</curator.version>
<zookeeper.version>3.5.6</zookeeper.version>
<guava.version>29.0-jre</guava.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>${spring-boot.version}</version>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>${curator.version}</version>
<exclusions>
<exclusion>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-framework</artifactId>
<version>${curator.version}</version>
<exclusions>
<exclusion>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-client</artifactId>
<version>${curator.version}</version>
<exclusions>
<exclusion>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>${zookeeper.version}</version>
<exclusions>
<exclusion>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</exclusion>
<exclusion>
<groupId>io.netty</groupId>
<artifactId>netty</artifactId>
</exclusion>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>com.github.xincao9</groupId>
<artifactId>yurpc-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-framework</artifactId>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-client</artifactId>
</dependency>
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
</dependencies>
</project>
================================================
FILE: yurpc-spring-boot-starter/src/main/java/com/github/xincao9/yurpc/spring/boot/starter/ConfigConsts.java
================================================
/*
* Copyright 2020 xincao9@gmail.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.xincao9.yurpc.spring.boot.starter;
/**
* @author xincao9@gmail.com
*/
public class ConfigConsts {
public static final String DISCOVERY_ZOOKEEPER = "yurpc.discovery.zookeeper";
}
================================================
FILE: yurpc-spring-boot-starter/src/main/java/com/github/xincao9/yurpc/spring/boot/starter/EnableYuRPC.java
================================================
/*
* Copyright 2020 xincao9@gmail.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.xincao9.yurpc.spring.boot.starter;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.context.annotation.Import;
/**
* 启动注解
*
* @author xincao9@gmail.com
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import({YuRPCImportBeanDefinitionRegistrar.class})
public @interface EnableYuRPC {
/**
* 服务角色
*
* @return
*/
boolean server() default false;
/**
* 客户端角色
*
* @return
*/
boolean client() default false;
}
================================================
FILE: yurpc-spring-boot-starter/src/main/java/com/github/xincao9/yurpc/spring/boot/starter/YUConsumer.java
================================================
/*
* Copyright 2020 xincao9@gmail.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.xincao9.yurpc.spring.boot.starter;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author xincao9@gmail.com
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface YUConsumer {
}
================================================
FILE: yurpc-spring-boot-starter/src/main/java/com/github/xincao9/yurpc/spring/boot/starter/YUProvider.java
================================================
/*
* Copyright 2020 xincao9@gmail.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.xincao9.yurpc.spring.boot.starter;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.annotation.AliasFor;
import org.springframework.stereotype.Component;
/**
* YuRPC 服务注解
*
* @author xincao9@gmail.com
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface YUProvider {
@AliasFor(annotation = Component.class)
String value() default "";
}
================================================
FILE: yurpc-spring-boot-starter/src/main/java/com/github/xincao9/yurpc/spring/boot/starter/YuRPCAutoConfiguration.java
================================================
/*
* Copyright 2020 xincao9@gmail.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.xincao9.yurpc.spring.boot.starter;
import com.github.xincao9.yurpc.core.DiscoveryService;
import com.github.xincao9.yurpc.core.config.ClientConfig;
import com.github.xincao9.yurpc.core.YuRPCClient;
import com.github.xincao9.yurpc.core.impl.YuRPCClientImpl;
import com.github.xincao9.yurpc.core.constant.ClientConsts;
import com.github.xincao9.yurpc.core.constant.ServerConsts;
import com.github.xincao9.yurpc.core.YuRPCServer;
import com.github.xincao9.yurpc.core.impl.YuRPCServerImpl;
import com.github.xincao9.yurpc.core.config.ServerConfig;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
/**
* 自动配置类
*
* @author xincao9@gmail.com
*/
public class YuRPCAutoConfiguration implements EnvironmentAware, InitializingBean, DisposableBean, BeanFactoryPostProcessor {
private static final Logger LOGGER = LoggerFactory.getLogger(YuRPCAutoConfiguration.class);
private Environment environment;
private Boolean server;
private Boolean client;
private YuRPCClient yuRPCClient;
private YuRPCServer yuRPCServer;
private DiscoveryService discoveryService;
private YuRPCBeanPostProcessor yuRPCBeanPostProcessor;
/**
* 修改器
*
* @param environment 环境
*/
@Override
public void setEnvironment(Environment environment) {
this.environment = environment;
}
/**
* 自动扫描,注册服务组件
*
* @return 注册服务组件
* @throws java.lang.Throwable 异常
*/
public YuRPCBeanPostProcessor yuRPCBeanPostProcessor(YuRPCClient yuRPCClient, YuRPCServer yuRPCServer) throws Throwable {
if (server || client) {
yuRPCBeanPostProcessor = new YuRPCBeanPostProcessor(yuRPCClient, yuRPCServer);
return yuRPCBeanPostProcessor;
}
return null;
}
/**
* 释放资源
*
* @throws Exception 异常
*/
@Override
public void destroy() throws Exception {
if (yuRPCClient != null) {
try {
yuRPCClient.shutdown();
} catch (Throwable e) {
LOGGER.error(e.getMessage());
}
}
if (yuRPCServer != null) {
try {
yuRPCServer.shutdown();
} catch (Throwable e) {
LOGGER.error(e.getMessage());
}
}
}
/**
* 服务端角色
*
* @param server 状态
*/
public void setServer(Boolean server) {
this.server = server;
}
/**
* 客户端角色
*
* @param client 状态
*/
public void setClient(Boolean client) {
this.client = client;
}
/**
* 服务发现注册组件
*
* @return 服务发现注册组件
* @throws java.lang.Throwable 异常
*/
public DiscoveryService discoveryService() throws Throwable {
if ((client || server) && environment.containsProperty(ConfigConsts.DISCOVERY_ZOOKEEPER)) {
discoveryService = new ZKDiscoveryServiceImpl(environment.getProperty(ConfigConsts.DISCOVERY_ZOOKEEPER));
return discoveryService;
}
return null;
}
/**
* 服务端
*
* @param discoveryService 服务发现注册组件
* @return 服务端
* @throws java.lang.Throwable 异常
*/
public YuRPCServer yuRPCServer(DiscoveryService discoveryService) throws Throwable {
if (server) {
Properties pros = new Properties();
if (environment.containsProperty(ServerConsts.PORT)) {
pros.setProperty(ServerConsts.PORT, environment.getProperty(ServerConsts.PORT));
}
ServerConfig.init(pros);
yuRPCServer = new YuRPCServerImpl();
yuRPCServer.setDiscoveryService(discoveryService);
yuRPCServer.start();
return yuRPCServer;
}
return null;
}
/**
* 客户端
*
* @param discoveryService 服务发现注册组件
* @return 客户端
* @throws java.lang.Throwable 异常
*/
public YuRPCClient yuRPCClient(DiscoveryService discoveryService) throws Throwable {
if (client) {
Properties pros = new Properties();
if (environment.containsProperty(ClientConsts.SERVER_LIST)) {
pros.setProperty(ClientConsts.SERVER_LIST, environment.getProperty(ClientConsts.SERVER_LIST));
}
if (environment.containsProperty(ClientConsts.CONNECTION_TIMEOUT_MS)) {
pros.setProperty(ClientConsts.CONNECTION_TIMEOUT_MS, environment.getProperty(ClientConsts.CONNECTION_TIMEOUT_MS));
}
if (environment.containsProperty(ClientConsts.INVOKE_TIMEOUT_MS)) {
pros.setProperty(ClientConsts.INVOKE_TIMEOUT_MS, environment.getProperty(ClientConsts.INVOKE_TIMEOUT_MS));
}
ClientConfig.init(pros);
yuRPCClient = new YuRPCClientImpl();
yuRPCClient.setDiscoveryService(discoveryService);
yuRPCClient.start();
return yuRPCClient;
}
return null;
}
/**
* 后置处理组件工厂
*
* @param beanFactory 容器上下文
* @throws BeansException 组件异常
*/
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
if (server || client) {
try {
beanFactory.addBeanPostProcessor(yuRPCBeanPostProcessor);
} catch (Throwable e) {
throw new BeansException(e.getMessage()) {
};
}
}
}
@Override
public void afterPropertiesSet() throws Exception {
try {
discoveryService();
yuRPCClient(discoveryService);
yuRPCServer(discoveryService);
yuRPCBeanPostProcessor(yuRPCClient, yuRPCServer);
} catch (Throwable e) {
throw new Exception(e.getCause());
}
}
}
================================================
FILE: yurpc-spring-boot-starter/src/main/java/com/github/xincao9/yurpc/spring/boot/starter/YuRPCBeanPostProcessor.java
================================================
/*
* Copyright 2020 xincao9@gmail.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.xincao9.yurpc.spring.boot.starter;
import com.github.xincao9.yurpc.core.YuRPCClient;
import com.github.xincao9.yurpc.core.YuRPCServer;
import java.lang.reflect.Field;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.util.ClassUtils;
/**
* 自动扫描,注册服务组件
*
* @author xincao9@gmail.com
*/
public class YuRPCBeanPostProcessor implements BeanPostProcessor {
private static final Logger LOGGER = LoggerFactory.getLogger(YuRPCBeanPostProcessor.class);
private final YuRPCServer yuRPCServer;
private final YuRPCClient yuRPCClient;
public YuRPCBeanPostProcessor(YuRPCClient yuRPCClient, YuRPCServer yuRPCServer) {
this.yuRPCClient = yuRPCClient;
this.yuRPCServer = yuRPCServer;
}
/**
* 初始化前执行
*
* @param bean 实例
* @param beanName 名字
* @return
* @throws BeansException 异常
*/
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (this.yuRPCServer != null && bean != null && bean.getClass().isAnnotationPresent(YUProvider.class)) {
this.yuRPCServer.register(bean);
LOGGER.info("register yurpc service = {}", beanName);
}
if (this.yuRPCClient != null && bean != null) {
// Class clazz = AopUtils.getTargetClass(bean); // AOP代理的目标类 https://github.com/spring-projects/spring-framework/issues/20132
Class clazz = ClassUtils.getUserClass(bean); // the original class for CGLIB-generated classes, consider ClassUtils.getUserClass
Field[] fields = clazz.getDeclaredFields();
if (fields != null && fields.length > 0) {
for (Field field : fields) {
if (field.isAnnotationPresent(YUConsumer.class)) {
Object obj = this.yuRPCClient.proxy(field.getType());
try {
field.setAccessible(true);
field.set(bean, obj);
} catch (IllegalArgumentException | IllegalAccessException ex) {
LOGGER.error(ex.getMessage());
throw new BeansException(ex.getMessage()) {
};
}
LOGGER.info("service reference beanName = {}, field = {}", beanName, field.getName());
}
}
}
}
return BeanPostProcessor.super.postProcessBeforeInitialization(bean, beanName);
}
/**
* 初始化后执行
*
* @param bean 实例
* @param beanName 名字
* @return
* @throws BeansException 异常
*/
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
}
}
================================================
FILE: yurpc-spring-boot-starter/src/main/java/com/github/xincao9/yurpc/spring/boot/starter/YuRPCImportBeanDefinitionRegistrar.java
================================================
/*
* Copyright 2020 xincao9@gmail.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.xincao9.yurpc.spring.boot.starter;
import java.util.Map;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;
/**
* 导入注解属性且初始化自动配置类
*
* @author xincao9@gmail.com
*/
public class YuRPCImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
/**
* 注册组件
*
* @param am 注解元信息
* @param bdr 组件注册器
*/
@Override
public void registerBeanDefinitions(AnnotationMetadata am, BeanDefinitionRegistry bdr) {
Map<String, Object> attributes = am.getAnnotationAttributes(EnableYuRPC.class.getName());
BeanDefinitionBuilder bdb = BeanDefinitionBuilder.rootBeanDefinition(YuRPCAutoConfiguration.class);
if (attributes != null && attributes.containsKey("server")) {
bdb.addPropertyValue("server", (Boolean) attributes.get("server"));
}
if (attributes != null && attributes.containsKey("client")) {
bdb.addPropertyValue("client", (Boolean) attributes.get("client"));
}
bdr.registerBeanDefinition(YuRPCAutoConfiguration.class.getName(), bdb.getBeanDefinition());
}
}
================================================
FILE: yurpc-spring-boot-starter/src/main/java/com/github/xincao9/yurpc/spring/boot/starter/ZKDiscoveryServiceImpl.java
================================================
/*
* Copyright 2020 xincao9@gmail.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.xincao9.yurpc.spring.boot.starter;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.github.xincao9.yurpc.core.DiscoveryService;
import com.github.xincao9.yurpc.core.protocol.Endpoint;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.TreeCache;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent;
import org.apache.curator.framework.recipes.cache.TreeCacheListener;
import org.apache.curator.framework.state.ConnectionState;
import org.apache.curator.framework.state.ConnectionStateListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 服务注册与发现组件
*
* @author xincao9@gmail.com
*/
public final class ZKDiscoveryServiceImpl implements DiscoveryService {
private static final Logger LOGGER = LoggerFactory.getLogger(ZKDiscoveryServiceImpl.class);
private CuratorFramework client;
private static final String YURPC_ROOT = "/yurpc";
private static final String YURPC_SERVICE_PATTERN = "/yurpc/%s";
private static final String YURPC_INSTANCE_PATTERN = "/yurpc/%s/%s";
private final Map<String, List<Endpoint>> services = new ConcurrentHashMap();
private final ExecutorService watcherExecutorService = Executors.newFixedThreadPool(1);
private final Map<String, byte[]> pathValue = new ConcurrentHashMap();
/**
* 构造器
*/
public ZKDiscoveryServiceImpl() {
}
/**
* 构造器
*
* @param zookeeper zookeeper地址,(格式host1:port1,host2:port2,...)
* @throws java.lang.Throwable 异常
*/
public ZKDiscoveryServiceImpl(String zookeeper) throws Throwable {
init(zookeeper);
}
/**
* 初始化方法,(仅在使用无参构造器时使用)
*
* @param zookeeper
* @throws java.lang.Throwable 异常
*/
public void init(String zookeeper) throws Throwable {
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
this.client = CuratorFrameworkFactory.newClient(zookeeper, retryPolicy);
this.client.start();
this.client.getConnectionStateListenable().addListener((ConnectionStateListener) (CuratorFramework cf, ConnectionState cs) -> {
if (cs == ConnectionState.RECONNECTED) {
if (pathValue != null && !pathValue.isEmpty()) {
pathValue.entrySet().forEach((entry) -> {
String path = entry.getKey();
byte[] value = entry.getValue();
try {
cf.create().withMode(CreateMode.EPHEMERAL).forPath(path, value);
} catch (Exception ex) {
LOGGER.error(ex.getMessage());
}
});
}
}
}, watcherExecutorService);
}
/**
* 监控服务
*
* @param service 服务名字(接口名)
*/
private void watcher(String service) {
try {
TreeCache treeCache = TreeCache.newBuilder(this.client, String.format(YURPC_SERVICE_PATTERN, service)).setExecutor(this.watcherExecutorService).build();
treeCache.getListenable().addListener((TreeCacheListener) (CuratorFramework cf, TreeCacheEvent tce) -> {
TreeCacheEvent.Type type = tce.getType();
if (type == TreeCacheEvent.Type.NODE_ADDED || type == TreeCacheEvent.Type.NODE_REMOVED || type == TreeCacheEvent.Type.NODE_UPDATED) {
LOGGER.warn("service = {}, event = {} refresh", service, type);
try {
this.services.put(service, queryZookeeper(service));
} catch (Throwable e) {
LOGGER.error(e.getMessage());
}
}
});
treeCache.start();
} catch (Exception e) {
LOGGER.error(e.getMessage());
}
}
/**
* 注册
*
* @param endpoint 服务信息
*/
@Override
public void register(Endpoint endpoint) {
try {
if (this.client.checkExists().forPath(YURPC_ROOT) == null) {
this.client.create().withMode(CreateMode.PERSISTENT).forPath(YURPC_ROOT);
}
if (this.client.checkExists().forPath(String.format(YURPC_SERVICE_PATTERN, endpoint.getName())) == null) {
this.client.create().withMode(CreateMode.PERSISTENT).forPath(String.format(YURPC_SERVICE_PATTERN, endpoint.getName()));
}
String path = String.format(YURPC_INSTANCE_PATTERN, endpoint.getName(), endpoint.getInstanceId());
byte[] value = JSONObject.toJSONBytes(endpoint, SerializerFeature.DisableCircularReferenceDetect);
this.client.create()
.withMode(CreateMode.EPHEMERAL)
.forPath(path, value);
this.pathValue.put(path, value);
} catch (Exception e) {
LOGGER.error(e.getMessage());
}
}
/**
* 获取注册表
*
* @param service 服务名字(接口名)
* @return 节点列表
*/
@Override
public List<Endpoint> query(String service) {
if (!this.services.containsKey(service)) {
synchronized (this) {
if (!this.services.containsKey(service)) {
try {
this.services.put(service, queryZookeeper(service));
watcher(service);
} catch (Throwable e) {
LOGGER.error(e.getMessage());
}
}
}
}
return this.services.get(service);
}
/**
* 获取注册表
*
* @param service 服务名字(接口名)
* @return 节点列表
* @throws Throwable 异常
*/
private List<Endpoint> queryZookeeper(String service) throws Throwable {
List<String> paths = this.client.getChildren().forPath(String.format(YURPC_SERVICE_PATTERN, service));
if (paths == null || paths.isEmpty()) {
return Collections.EMPTY_LIST;
}
List<Endpoint> endpoints = new ArrayList();
for (String path : paths) {
byte[] data = this.client.getData().forPath(String.format(YURPC_INSTANCE_PATTERN, service, path));
if (data != null && data.length > 0) {
endpoints.add(JSONObject.parseObject(data, Endpoint.class));
}
}
return endpoints;
}
/**
* 续约
*
* @param instanceId 当前实例的id
*/
@Override
public void renew(String instanceId) {
}
/**
* 取消
*
* @param instanceId 当前实例的id
*/
@Override
public void cancel(String instanceId) {
}
}
gitextract_u_twoy7l/
├── .gitignore
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── pom.xml
├── yurpc-core/
│ ├── pom.xml
│ └── src/
│ ├── main/
│ │ └── java/
│ │ └── com/
│ │ └── github/
│ │ └── xincao9/
│ │ └── yurpc/
│ │ └── core/
│ │ ├── DiscoveryService.java
│ │ ├── YuRPCClient.java
│ │ ├── YuRPCServer.java
│ │ ├── codec/
│ │ │ ├── StringDecoder.java
│ │ │ └── StringEncoder.java
│ │ ├── config/
│ │ │ ├── ClientConfig.java
│ │ │ └── ServerConfig.java
│ │ ├── constant/
│ │ │ ├── ClientConsts.java
│ │ │ ├── ResponseCode.java
│ │ │ ├── ServerConsts.java
│ │ │ └── SystemConsts.java
│ │ ├── impl/
│ │ │ ├── ClientHandler.java
│ │ │ ├── ClientInvocationHandler.java
│ │ │ ├── HeartbeatHandler.java
│ │ │ ├── ServerHandler.java
│ │ │ ├── YuRPCClientImpl.java
│ │ │ └── YuRPCServerImpl.java
│ │ ├── protocol/
│ │ │ ├── Endpoint.java
│ │ │ ├── Pair.java
│ │ │ ├── Request.java
│ │ │ └── Response.java
│ │ └── util/
│ │ ├── HostUtils.java
│ │ └── PropertiesUtils.java
│ └── test/
│ ├── java/
│ │ └── com/
│ │ └── github/
│ │ └── xincao9/
│ │ └── yurpc/
│ │ └── YuRPCServerTest.java
│ └── resources/
│ └── config.properties
├── yurpc-sample/
│ ├── dependency-reduced-pom.xml
│ ├── pom.xml
│ └── src/
│ └── main/
│ ├── java/
│ │ └── com/
│ │ └── github/
│ │ └── xincao9/
│ │ └── yurpc/
│ │ └── sample/
│ │ ├── Say.java
│ │ ├── SayService.java
│ │ ├── consumer/
│ │ │ ├── ApplicationConsumer.java
│ │ │ ├── Benchmark.java
│ │ │ ├── Consumer.java
│ │ │ └── SayMethod.java
│ │ └── provider/
│ │ ├── ApplicationProvider.java
│ │ ├── Provider.java
│ │ └── SayServiceImpl.java
│ └── resources/
│ ├── application.yml
│ └── config.properties
└── yurpc-spring-boot-starter/
├── pom.xml
└── src/
└── main/
└── java/
└── com/
└── github/
└── xincao9/
└── yurpc/
└── spring/
└── boot/
└── starter/
├── ConfigConsts.java
├── EnableYuRPC.java
├── YUConsumer.java
├── YUProvider.java
├── YuRPCAutoConfiguration.java
├── YuRPCBeanPostProcessor.java
├── YuRPCImportBeanDefinitionRegistrar.java
└── ZKDiscoveryServiceImpl.java
SYMBOL INDEX (214 symbols across 38 files)
FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/DiscoveryService.java
type DiscoveryService (line 26) | public interface DiscoveryService {
method register (line 33) | void register (Endpoint endpoint);
method query (line 41) | List<Endpoint> query (String service);
method renew (line 48) | void renew (String instanceId);
method cancel (line 55) | void cancel (String instanceId);
FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/YuRPCClient.java
type YuRPCClient (line 29) | public interface YuRPCClient {
method invoke (line 39) | <T> Response<T> invoke(Request request) throws Throwable;
method start (line 46) | void start() throws Throwable;
method shutdown (line 53) | void shutdown() throws Throwable;
method defaultYuRPCClient (line 62) | static YuRPCClient defaultYuRPCClient(String filename, DiscoveryServic...
method defaultYuRPCClient (line 72) | static YuRPCClient defaultYuRPCClient() {
method defaultYuRPCClient (line 82) | static YuRPCClient defaultYuRPCClient(DiscoveryService discoveryServic...
method getRequests (line 91) | Map<Long, Request> getRequests();
method proxy (line 100) | <T> T proxy(Class<T> clazz);
method setDiscoveryService (line 107) | void setDiscoveryService(DiscoveryService discoveryService);
FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/YuRPCServer.java
type YuRPCServer (line 26) | public interface YuRPCServer {
method start (line 33) | void start() throws Throwable;
method shutdown (line 40) | void shutdown() throws Throwable;
method defaultYuRPCServer (line 49) | static YuRPCServer defaultYuRPCServer(String filename, DiscoveryServic...
method defaultYuRPCServer (line 59) | static YuRPCServer defaultYuRPCServer() {
method defaultYuRPCServer (line 70) | static YuRPCServer defaultYuRPCServer(Integer port, DiscoveryService d...
method defaultYuRPCServer (line 81) | static YuRPCServer defaultYuRPCServer(String filename) {
method defaultYuRPCServer (line 91) | static YuRPCServer defaultYuRPCServer(DiscoveryService discovery) {
method register (line 101) | <T> void register(T obj);
method getBean (line 109) | Object getBean(String name);
method setDiscoveryService (line 116) | void setDiscoveryService(DiscoveryService discoveryService);
FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/codec/StringDecoder.java
class StringDecoder (line 30) | public class StringDecoder extends ByteToMessageDecoder {
method decode (line 40) | @Override
FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/codec/StringEncoder.java
class StringEncoder (line 29) | public class StringEncoder extends MessageToByteEncoder<Object> {
method encode (line 39) | @Override
FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/config/ClientConfig.java
class ClientConfig (line 32) | public class ClientConfig {
method init (line 43) | public static void init(String filename) {
method init (line 53) | public static void init(Properties pros) {
FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/config/ServerConfig.java
class ServerConfig (line 29) | public class ServerConfig {
method init (line 40) | public static void init(String filename) {
method init (line 50) | public static void init(Properties pros) {
FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/constant/ClientConsts.java
class ClientConsts (line 23) | public class ClientConsts {
FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/constant/ResponseCode.java
class ResponseCode (line 23) | public class ResponseCode {
FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/constant/ServerConsts.java
class ServerConsts (line 23) | public class ServerConsts {
FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/constant/SystemConsts.java
class SystemConsts (line 22) | public class SystemConsts {
FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/impl/ClientHandler.java
class ClientHandler (line 34) | @Sharable
method channelRead0 (line 47) | @Override
method setYuRPCClient (line 65) | public void setYuRPCClient(YuRPCClient yuRPCClient) {
FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/impl/ClientInvocationHandler.java
class ClientInvocationHandler (line 41) | public class ClientInvocationHandler implements InvocationHandler {
method invoke (line 57) | @Override
method proxy (line 106) | public <T> T proxy(Class<T> clazz) {
method setYuRPCClient (line 124) | public void setYuRPCClient(YuRPCClient yuRPCClient) {
FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/impl/HeartbeatHandler.java
class HeartbeatHandler (line 32) | @Sharable
method userEventTriggered (line 44) | @Override
FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/impl/ServerHandler.java
class ServerHandler (line 40) | @Sharable
method ServerHandler (line 49) | public ServerHandler() {
method submit (line 57) | private void submit(Boolean requestType, Method method, Long rid, Obje...
method exec (line 63) | private void exec(Boolean requestType, Method method, Long rid, Object...
method channelRead0 (line 86) | @Override
method getClass (line 139) | private Class getClass(String classname) throws ClassNotFoundException {
method exception (line 152) | private void exception(ChannelHandlerContext ctx, Long id, Integer res...
method setYuRPCServer (line 161) | public void setYuRPCServer(YuRPCServer yuRPCServer) {
FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/impl/YuRPCClientImpl.java
class YuRPCClientImpl (line 60) | public class YuRPCClientImpl implements YuRPCClient {
method YuRPCClientImpl (line 74) | public YuRPCClientImpl() {
method YuRPCClientImpl (line 83) | public YuRPCClientImpl(DiscoveryService discoveryService) {
method start (line 92) | @Override
method shutdown (line 125) | @Override
method invoke (line 153) | @Override
method getChannel (line 197) | private Channel getChannel(String host, int port) {
method getRequests (line 229) | @Override
method proxy (line 241) | @Override
method setDiscoveryService (line 251) | @Override
FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/impl/YuRPCServerImpl.java
class YuRPCServerImpl (line 51) | public class YuRPCServerImpl implements YuRPCServer {
method YuRPCServerImpl (line 65) | public YuRPCServerImpl() {
method YuRPCServerImpl (line 75) | public YuRPCServerImpl(Integer port, DiscoveryService discoveryService) {
method YuRPCServerImpl (line 87) | public YuRPCServerImpl(DiscoveryService discoveryService) {
method start (line 99) | @Override
method shutdown (line 139) | @Override
method register (line 157) | @Override
method getBean (line 179) | @Override
method setDiscoveryService (line 189) | @Override
FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/protocol/Endpoint.java
class Endpoint (line 30) | public class Endpoint {
method create (line 44) | public static Endpoint create (String name) {
method getInstanceId (line 54) | public String getInstanceId() {
method setInstanceId (line 58) | public void setInstanceId(String instanceId) {
method getHost (line 62) | public String getHost() {
method setHost (line 66) | public void setHost(String host) {
method getPort (line 70) | public Integer getPort() {
method setPort (line 74) | public void setPort(Integer port) {
method getName (line 78) | public String getName() {
method setName (line 82) | public void setName(String name) {
method getCreateTime (line 86) | public Date getCreateTime() {
method setCreateTime (line 90) | public void setCreateTime(Date createTime) {
method toString (line 94) | @Override
FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/protocol/Pair.java
class Pair (line 28) | public class Pair<T1, T2> {
method Pair (line 33) | public Pair() {
method Pair (line 36) | public Pair(T1 o1, T2 o2) {
method getO1 (line 41) | public T1 getO1() {
method setO1 (line 45) | public void setO1(T1 o1) {
method getO2 (line 49) | public T2 getO2() {
method setO2 (line 53) | public void setO2(T2 o2) {
method toString (line 57) | @Override
FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/protocol/Request.java
class Request (line 31) | public class Request {
method createRequest (line 56) | public static Request createRequest(Boolean requestType, String method...
method createEvent (line 76) | public static Request createEvent(String method) {
method waitResponse (line 98) | public <T> Response<T> waitResponse(int timeout, TimeUnit timeUnit) th...
method putResponse (line 108) | public void putResponse(Response response) {
method getRequestType (line 113) | public Boolean getRequestType() {
method setRequestType (line 117) | public void setRequestType(Boolean requestType) {
method getEventType (line 121) | public Boolean getEventType() {
method setEventType (line 125) | public void setEventType(Boolean eventType) {
method getId (line 129) | public Long getId() {
method setId (line 133) | public void setId(Long id) {
method getParams (line 137) | public Object[] getParams() {
method setParams (line 141) | public void setParams(Object[] params) {
method getParamTypes (line 145) | public String[] getParamTypes() {
method setParamTypes (line 149) | public void setParamTypes(String[] paramTypes) {
method getMethod (line 153) | public String getMethod() {
method setMethod (line 157) | public void setMethod(String method) {
method getCreateTime (line 161) | public Long getCreateTime() {
method setCreateTime (line 165) | public void setCreateTime(Long createTime) {
method getHost (line 169) | public String getHost() {
method setHost (line 173) | public void setHost(String host) {
method getPort (line 177) | public int getPort() {
method setPort (line 181) | public void setPort(int port) {
method getResponse (line 185) | public Object getResponse() {
method setResponse (line 189) | public void setResponse(Response response) {
method getSendOk (line 193) | public Boolean getSendOk() {
method setSendOk (line 197) | public void setSendOk(Boolean sendOk) {
method isDirect (line 201) | public Boolean isDirect () {
method getDirect (line 205) | public Boolean getDirect() {
method setDirect (line 209) | public void setDirect(Boolean direct) {
method toString (line 213) | @Override
FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/protocol/Response.java
class Response (line 28) | public class Response<T> {
method createResponse (line 36) | public static <T> Response<T> createResponse(Long id, T data) {
method createResponse (line 43) | public static <T> Response<T> createResponse(Long id, Integer code, St...
method getId (line 51) | public Long getId() {
method setId (line 55) | public void setId(Long id) {
method getCode (line 59) | public Integer getCode() {
method setCode (line 63) | public void setCode(Integer code) {
method getData (line 67) | public T getData() {
method setData (line 71) | public void setData(T data) {
method getMsg (line 75) | public String getMsg() {
method setMsg (line 79) | public void setMsg(String msg) {
method getCreateTime (line 83) | public Long getCreateTime() {
method toString (line 87) | @Override
FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/util/HostUtils.java
class HostUtils (line 31) | public class HostUtils {
method getLocalAddress (line 40) | public static String getLocalAddress() {
FILE: yurpc-core/src/main/java/com/github/xincao9/yurpc/core/util/PropertiesUtils.java
class PropertiesUtils (line 29) | public class PropertiesUtils {
method read (line 40) | public static Properties read(String filename, String defaultFilename) {
FILE: yurpc-core/src/test/java/com/github/xincao9/yurpc/YuRPCServerTest.java
class YuRPCServerTest (line 37) | @BenchmarkMode(Mode.Throughput)
method setUp (line 54) | @Setup
method tearDown (line 69) | @TearDown
method perform (line 75) | @Benchmark
method testMethod (line 87) | @Test
class Say (line 96) | public static class Say {
method Say (line 101) | public Say(Integer id, String body) {
method getId (line 106) | public Integer getId() {
method setId (line 110) | public void setId(Integer id) {
method getBody (line 114) | public String getBody() {
method setBody (line 118) | public void setBody(String body) {
method toString (line 122) | @Override
type SayService (line 128) | public interface SayService {
method perform (line 130) | Say perform(Say say);
class SayServiceImpl (line 133) | public static class SayServiceImpl implements SayService {
method perform (line 135) | @Override
FILE: yurpc-sample/src/main/java/com/github/xincao9/yurpc/sample/Say.java
class Say (line 26) | public class Say {
method Say (line 31) | public Say(Integer id, String body) {
method getId (line 36) | public Integer getId() {
method setId (line 40) | public void setId(Integer id) {
method getBody (line 44) | public String getBody() {
method setBody (line 48) | public void setBody(String body) {
method toString (line 52) | @Override
FILE: yurpc-sample/src/main/java/com/github/xincao9/yurpc/sample/SayService.java
type SayService (line 23) | public interface SayService {
method perform (line 31) | Say perform(Say say);
FILE: yurpc-sample/src/main/java/com/github/xincao9/yurpc/sample/consumer/ApplicationConsumer.java
class ApplicationConsumer (line 33) | @SpringBootApplication
method main (line 45) | public static void main(String... args) {
method commandLineRunner (line 54) | @Bean
FILE: yurpc-sample/src/main/java/com/github/xincao9/yurpc/sample/consumer/Benchmark.java
class Benchmark (line 24) | public class Benchmark {
method main (line 26) | public static void main(String... args) throws Throwable {
FILE: yurpc-sample/src/main/java/com/github/xincao9/yurpc/sample/consumer/Consumer.java
class Consumer (line 30) | public class Consumer {
method main (line 40) | public static void main(String... args) throws Throwable {
FILE: yurpc-sample/src/main/java/com/github/xincao9/yurpc/sample/consumer/SayMethod.java
class SayMethod (line 25) | @Test(name="say")
method SayMethod (line 30) | public SayMethod () {
method exec (line 40) | @Override
FILE: yurpc-sample/src/main/java/com/github/xincao9/yurpc/sample/provider/ApplicationProvider.java
class ApplicationProvider (line 27) | @SpringBootApplication
method main (line 36) | public static void main(String... args) {
FILE: yurpc-sample/src/main/java/com/github/xincao9/yurpc/sample/provider/Provider.java
class Provider (line 28) | public class Provider {
method main (line 38) | public static void main(String... args) throws Throwable {
FILE: yurpc-sample/src/main/java/com/github/xincao9/yurpc/sample/provider/SayServiceImpl.java
class SayServiceImpl (line 27) | @YUProvider
method perform (line 36) | @Override
FILE: yurpc-spring-boot-starter/src/main/java/com/github/xincao9/yurpc/spring/boot/starter/ConfigConsts.java
class ConfigConsts (line 21) | public class ConfigConsts {
FILE: yurpc-spring-boot-starter/src/main/java/com/github/xincao9/yurpc/spring/boot/starter/YuRPCAutoConfiguration.java
class YuRPCAutoConfiguration (line 45) | public class YuRPCAutoConfiguration implements EnvironmentAware, Initial...
method setEnvironment (line 62) | @Override
method yuRPCBeanPostProcessor (line 73) | public YuRPCBeanPostProcessor yuRPCBeanPostProcessor(YuRPCClient yuRPC...
method destroy (line 86) | @Override
method setServer (line 109) | public void setServer(Boolean server) {
method setClient (line 118) | public void setClient(Boolean client) {
method discoveryService (line 128) | public DiscoveryService discoveryService() throws Throwable {
method yuRPCServer (line 143) | public YuRPCServer yuRPCServer(DiscoveryService discoveryService) thro...
method yuRPCClient (line 165) | public YuRPCClient yuRPCClient(DiscoveryService discoveryService) thro...
method postProcessBeanFactory (line 192) | @Override
method afterPropertiesSet (line 204) | @Override
FILE: yurpc-spring-boot-starter/src/main/java/com/github/xincao9/yurpc/spring/boot/starter/YuRPCBeanPostProcessor.java
class YuRPCBeanPostProcessor (line 34) | public class YuRPCBeanPostProcessor implements BeanPostProcessor {
method YuRPCBeanPostProcessor (line 41) | public YuRPCBeanPostProcessor(YuRPCClient yuRPCClient, YuRPCServer yuR...
method postProcessBeforeInitialization (line 54) | @Override
method postProcessAfterInitialization (line 92) | @Override
FILE: yurpc-spring-boot-starter/src/main/java/com/github/xincao9/yurpc/spring/boot/starter/YuRPCImportBeanDefinitionRegistrar.java
class YuRPCImportBeanDefinitionRegistrar (line 30) | public class YuRPCImportBeanDefinitionRegistrar implements ImportBeanDef...
method registerBeanDefinitions (line 38) | @Override
FILE: yurpc-spring-boot-starter/src/main/java/com/github/xincao9/yurpc/spring/boot/starter/ZKDiscoveryServiceImpl.java
class ZKDiscoveryServiceImpl (line 47) | public final class ZKDiscoveryServiceImpl implements DiscoveryService {
method ZKDiscoveryServiceImpl (line 61) | public ZKDiscoveryServiceImpl() {
method ZKDiscoveryServiceImpl (line 70) | public ZKDiscoveryServiceImpl(String zookeeper) throws Throwable {
method init (line 80) | public void init(String zookeeper) throws Throwable {
method watcher (line 106) | private void watcher(String service) {
method register (line 131) | @Override
method query (line 157) | @Override
method queryZookeeper (line 181) | private List<Endpoint> queryZookeeper(String service) throws Throwable {
method renew (line 201) | @Override
method cancel (line 210) | @Override
Condensed preview — 53 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (153K chars).
[
{
"path": ".gitignore",
"chars": 333,
"preview": "HELP.md\ntarget/\n!.mvn/wrapper/maven-wrapper.jar\n!**/src/main/**\n!**/src/test/**\n\n### STS ###\n.apt_generated\n.classpath\n."
},
{
"path": "CONTRIBUTING.md",
"chars": 36,
"preview": "Primary developer xincao9@gmail.com\n"
},
{
"path": "LICENSE",
"chars": 11357,
"preview": " Apache License\n Version 2.0, January 2004\n "
},
{
"path": "README.md",
"chars": 2885,
"preview": "## yurpc\n\n### 高性能RPC框架\n\n#### yurpc 基于java的高性能开源RPC框架,使用方式上类似dubbo,提倡面向接口编程,如果您熟悉dubbo很容易迁移到yurpc;并享受高性能带来的服务体验。提供springb"
},
{
"path": "pom.xml",
"chars": 5676,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2"
},
{
"path": "yurpc-core/pom.xml",
"chars": 5183,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2"
},
{
"path": "yurpc-core/src/main/java/com/github/xincao9/yurpc/core/DiscoveryService.java",
"chars": 1254,
"preview": "/*\n * Copyright 2020 xincao9@gmail.com.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may"
},
{
"path": "yurpc-core/src/main/java/com/github/xincao9/yurpc/core/YuRPCClient.java",
"chars": 2484,
"preview": "/*\n * Copyright 2020 xincao9@gmail.com.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may"
},
{
"path": "yurpc-core/src/main/java/com/github/xincao9/yurpc/core/YuRPCServer.java",
"chars": 2651,
"preview": "/*\n * Copyright 2020 xincao9@gmail.com.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may"
},
{
"path": "yurpc-core/src/main/java/com/github/xincao9/yurpc/core/codec/StringDecoder.java",
"chars": 2221,
"preview": "/*\n * Copyright 2020 xincao9@gmail.com.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may"
},
{
"path": "yurpc-core/src/main/java/com/github/xincao9/yurpc/core/codec/StringEncoder.java",
"chars": 1552,
"preview": "/*\n * Copyright 2020 xincao9@gmail.com.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may"
},
{
"path": "yurpc-core/src/main/java/com/github/xincao9/yurpc/core/config/ClientConfig.java",
"chars": 2155,
"preview": "/*\n * Copyright 2020 xincao9@gmail.com.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may"
},
{
"path": "yurpc-core/src/main/java/com/github/xincao9/yurpc/core/config/ServerConfig.java",
"chars": 1699,
"preview": "/*\n * Copyright 2020 xincao9@gmail.com.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may"
},
{
"path": "yurpc-core/src/main/java/com/github/xincao9/yurpc/core/constant/ClientConsts.java",
"chars": 1189,
"preview": "/*\n * Copyright 2020 xincao9@gmail.com.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may"
},
{
"path": "yurpc-core/src/main/java/com/github/xincao9/yurpc/core/constant/ResponseCode.java",
"chars": 1604,
"preview": "/*\n * Copyright 2020 xincao9@gmail.com.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may"
},
{
"path": "yurpc-core/src/main/java/com/github/xincao9/yurpc/core/constant/ServerConsts.java",
"chars": 1010,
"preview": "/*\n * Copyright 2020 xincao9@gmail.com.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may"
},
{
"path": "yurpc-core/src/main/java/com/github/xincao9/yurpc/core/constant/SystemConsts.java",
"chars": 802,
"preview": "/*\n * Copyright 2020 xincao9@gmail.com.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may"
},
{
"path": "yurpc-core/src/main/java/com/github/xincao9/yurpc/core/impl/ClientHandler.java",
"chars": 2157,
"preview": "/*\n * Copyright 2020 xincao9@gmail.com.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may"
},
{
"path": "yurpc-core/src/main/java/com/github/xincao9/yurpc/core/impl/ClientInvocationHandler.java",
"chars": 4739,
"preview": "/*\n * Copyright 2020 xincao9@gmail.com.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may"
},
{
"path": "yurpc-core/src/main/java/com/github/xincao9/yurpc/core/impl/HeartbeatHandler.java",
"chars": 1720,
"preview": "/*\n * Copyright 2020 xincao9@gmail.com.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may"
},
{
"path": "yurpc-core/src/main/java/com/github/xincao9/yurpc/core/impl/ServerHandler.java",
"chars": 6057,
"preview": "/*\n * Copyright 2020 xincao9@gmail.com.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may"
},
{
"path": "yurpc-core/src/main/java/com/github/xincao9/yurpc/core/impl/YuRPCClientImpl.java",
"chars": 9379,
"preview": "/*\n * Copyright 2020 xincao9@gmail.com.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may"
},
{
"path": "yurpc-core/src/main/java/com/github/xincao9/yurpc/core/impl/YuRPCServerImpl.java",
"chars": 6242,
"preview": "/*\n * Copyright 2020 xincao9@gmail.com.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may"
},
{
"path": "yurpc-core/src/main/java/com/github/xincao9/yurpc/core/protocol/Endpoint.java",
"chars": 2399,
"preview": "/*\n * Copyright 2020 xincao9@gmail.com.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may"
},
{
"path": "yurpc-core/src/main/java/com/github/xincao9/yurpc/core/protocol/Pair.java",
"chars": 1397,
"preview": "/*\n * Copyright 2020 xincao9@gmail.com.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may"
},
{
"path": "yurpc-core/src/main/java/com/github/xincao9/yurpc/core/protocol/Request.java",
"chars": 5518,
"preview": "/*\n * Copyright 2020 xincao9@gmail.com.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may"
},
{
"path": "yurpc-core/src/main/java/com/github/xincao9/yurpc/core/protocol/Response.java",
"chars": 2292,
"preview": "/*\n * Copyright 2020 xincao9@gmail.com.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may"
},
{
"path": "yurpc-core/src/main/java/com/github/xincao9/yurpc/core/util/HostUtils.java",
"chars": 2515,
"preview": "/*\n * Copyright 2020 xincao9@gmail.com.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may"
},
{
"path": "yurpc-core/src/main/java/com/github/xincao9/yurpc/core/util/PropertiesUtils.java",
"chars": 1592,
"preview": "/*\n * Copyright 2020 xincao9@gmail.com.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may"
},
{
"path": "yurpc-core/src/test/java/com/github/xincao9/yurpc/YuRPCServerTest.java",
"chars": 3634,
"preview": "/*\n * Copyright 2020 xincao9@gmail.com.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may"
},
{
"path": "yurpc-core/src/test/resources/config.properties",
"chars": 137,
"preview": "yurpc.client.serverList=localhost:12306\nyurpc.client.connectionTimeoutMS=5000\nyurpc.client.invokeTimeoutMS=1000\n\nyurpc.s"
},
{
"path": "yurpc-sample/dependency-reduced-pom.xml",
"chars": 1572,
"preview": "<?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/"
},
{
"path": "yurpc-sample/pom.xml",
"chars": 2549,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2"
},
{
"path": "yurpc-sample/src/main/java/com/github/xincao9/yurpc/sample/Say.java",
"chars": 1356,
"preview": "/*\n * Copyright 2020 xincao9@gmail.com.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may"
},
{
"path": "yurpc-sample/src/main/java/com/github/xincao9/yurpc/sample/SayService.java",
"chars": 824,
"preview": "/*\n * Copyright 2020 xincao9@gmail.com.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may"
},
{
"path": "yurpc-sample/src/main/java/com/github/xincao9/yurpc/sample/consumer/ApplicationConsumer.java",
"chars": 1919,
"preview": "/*\n * Copyright 2020 xincao9@gmail.com.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may"
},
{
"path": "yurpc-sample/src/main/java/com/github/xincao9/yurpc/sample/consumer/Benchmark.java",
"chars": 1036,
"preview": "/*\n * Copyright 2020 xincao9@gmail.com.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may"
},
{
"path": "yurpc-sample/src/main/java/com/github/xincao9/yurpc/sample/consumer/Consumer.java",
"chars": 1835,
"preview": "/*\n * Copyright 2020 xincao9@gmail.com.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may"
},
{
"path": "yurpc-sample/src/main/java/com/github/xincao9/yurpc/sample/consumer/SayMethod.java",
"chars": 1577,
"preview": "/*\n * Copyright 2020 xincao9@gmail.com.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may"
},
{
"path": "yurpc-sample/src/main/java/com/github/xincao9/yurpc/sample/provider/ApplicationProvider.java",
"chars": 1151,
"preview": "/*\n * Copyright 2020 xincao9@gmail.com.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may"
},
{
"path": "yurpc-sample/src/main/java/com/github/xincao9/yurpc/sample/provider/Provider.java",
"chars": 1507,
"preview": "/*\n * Copyright 2020 xincao9@gmail.com.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may"
},
{
"path": "yurpc-sample/src/main/java/com/github/xincao9/yurpc/sample/provider/SayServiceImpl.java",
"chars": 1078,
"preview": "/*\n * Copyright 2020 xincao9@gmail.com.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may"
},
{
"path": "yurpc-sample/src/main/resources/application.yml",
"chars": 200,
"preview": "yurpc:\n discovery:\n zookeeper: localhost:2181\n client:\n serverList: localhost:12306\n connecti"
},
{
"path": "yurpc-sample/src/main/resources/config.properties",
"chars": 137,
"preview": "yurpc.client.serverList=localhost:12306\nyurpc.client.connectionTimeoutMS=5000\nyurpc.client.invokeTimeoutMS=1000\n\nyurpc.s"
},
{
"path": "yurpc-spring-boot-starter/pom.xml",
"chars": 4543,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2"
},
{
"path": "yurpc-spring-boot-starter/src/main/java/com/github/xincao9/yurpc/spring/boot/starter/ConfigConsts.java",
"chars": 808,
"preview": "/*\n * Copyright 2020 xincao9@gmail.com.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may"
},
{
"path": "yurpc-spring-boot-starter/src/main/java/com/github/xincao9/yurpc/spring/boot/starter/EnableYuRPC.java",
"chars": 1300,
"preview": "/*\n * Copyright 2020 xincao9@gmail.com.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may"
},
{
"path": "yurpc-spring-boot-starter/src/main/java/com/github/xincao9/yurpc/spring/boot/starter/YUConsumer.java",
"chars": 1006,
"preview": "/*\n * Copyright 2020 xincao9@gmail.com.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may"
},
{
"path": "yurpc-spring-boot-starter/src/main/java/com/github/xincao9/yurpc/spring/boot/starter/YUProvider.java",
"chars": 1213,
"preview": "/*\n * Copyright 2020 xincao9@gmail.com.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may"
},
{
"path": "yurpc-spring-boot-starter/src/main/java/com/github/xincao9/yurpc/spring/boot/starter/YuRPCAutoConfiguration.java",
"chars": 6873,
"preview": "/*\n * Copyright 2020 xincao9@gmail.com.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may"
},
{
"path": "yurpc-spring-boot-starter/src/main/java/com/github/xincao9/yurpc/spring/boot/starter/YuRPCBeanPostProcessor.java",
"chars": 3650,
"preview": "/*\n * Copyright 2020 xincao9@gmail.com.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may"
},
{
"path": "yurpc-spring-boot-starter/src/main/java/com/github/xincao9/yurpc/spring/boot/starter/YuRPCImportBeanDefinitionRegistrar.java",
"chars": 1938,
"preview": "/*\n * Copyright 2020 xincao9@gmail.com.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may"
},
{
"path": "yurpc-spring-boot-starter/src/main/java/com/github/xincao9/yurpc/spring/boot/starter/ZKDiscoveryServiceImpl.java",
"chars": 7738,
"preview": "/*\n * Copyright 2020 xincao9@gmail.com.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may"
}
]
About this extraction
This page contains the full source code of the xincao9/jsonrpc GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 53 files (136.4 KB), approximately 33.9k tokens, and a symbol index with 214 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.