├── examples
├── rpc-provider
│ ├── src
│ │ ├── main
│ │ │ ├── resources
│ │ │ │ ├── application-slave1.yml
│ │ │ │ ├── application-slave2.yml
│ │ │ │ └── application.yml
│ │ │ └── java
│ │ │ │ └── com
│ │ │ │ └── github
│ │ │ │ └── linshenkx
│ │ │ │ └── rpcprovider
│ │ │ │ ├── RpcProviderApplication.java
│ │ │ │ └── Impl
│ │ │ │ └── HelloServiceImpl.java
│ │ └── test
│ │ │ └── java
│ │ │ └── com
│ │ │ └── github
│ │ │ └── linshenkx
│ │ │ └── rpcprovider
│ │ │ └── RpcProviderApplicationTests.java
│ ├── .gitignore
│ └── pom.xml
├── rpc-lib
│ ├── src
│ │ └── main
│ │ │ └── java
│ │ │ └── com
│ │ │ └── github
│ │ │ └── linshenkx
│ │ │ └── rpclib
│ │ │ └── HelloService.java
│ ├── .gitignore
│ └── pom.xml
├── rpc-consumer
│ ├── src
│ │ ├── main
│ │ │ ├── resources
│ │ │ │ └── application.yml
│ │ │ └── java
│ │ │ │ └── com
│ │ │ │ └── github
│ │ │ │ └── linshenkx
│ │ │ │ └── rpcconsumer
│ │ │ │ ├── RpcConsumerApplication.java
│ │ │ │ └── controller
│ │ │ │ └── HelloController.java
│ │ └── test
│ │ │ └── java
│ │ │ └── com
│ │ │ └── github
│ │ │ └── linshenkx
│ │ │ └── rpcconsumer
│ │ │ └── RpcConsumerApplicationTests.java
│ ├── .gitignore
│ └── pom.xml
├── .gitignore
└── pom.xml
├── rpc-netty-client-spring-boot-autoconfigure
├── src
│ └── main
│ │ ├── resources
│ │ └── META-INF
│ │ │ └── spring.factories
│ │ └── java
│ │ └── com
│ │ └── github
│ │ └── linshenkx
│ │ └── rpcnettyclientspringbootautoconfigure
│ │ ├── properties
│ │ └── RpcClientProperties.java
│ │ ├── RpcClientAutoConfiguration.java
│ │ ├── processor
│ │ └── RpcClientBeanPostProcessor.java
│ │ ├── discovery
│ │ └── zookeeper
│ │ │ └── ZKServiceDiscovery.java
│ │ └── client
│ │ └── RpcClient.java
├── .gitignore
└── pom.xml
├── rpc-netty-server-spring-boot-autoconfigure
├── src
│ └── main
│ │ ├── resources
│ │ └── META-INF
│ │ │ └── spring.factories
│ │ └── java
│ │ └── com
│ │ └── github
│ │ └── linshenkx
│ │ └── rpcnettyserverspringbootautoconfigure
│ │ ├── properties
│ │ └── RpcServerProperties.java
│ │ ├── RpcServerAutoConfiguration.java
│ │ ├── registry
│ │ └── zookeeper
│ │ │ └── ZKServiceRegistry.java
│ │ └── server
│ │ └── RpcServer.java
├── .gitignore
└── pom.xml
├── rpc-netty-common
├── src
│ └── main
│ │ └── java
│ │ └── com
│ │ └── github
│ │ └── linshenkx
│ │ └── rpcnettycommon
│ │ ├── bean
│ │ ├── BodyContent.java
│ │ ├── RpcResponse.java
│ │ ├── RpcRequest.java
│ │ └── ServiceInfo.java
│ │ ├── route
│ │ ├── WeightGetAble.java
│ │ ├── impl
│ │ │ ├── RandomRouteStrategyImpl.java
│ │ │ ├── HashIPRouteStrategyImpl.java
│ │ │ └── PollingRouteStrategyImpl.java
│ │ ├── RouteStrategy.java
│ │ ├── RouteStrategyEnum.java
│ │ ├── WeightUtil.java
│ │ └── RouteEngine.java
│ │ ├── exception
│ │ └── remoting
│ │ │ ├── RemotingException.java
│ │ │ ├── RemotingNoSighException.java
│ │ │ ├── RemotingContextException.java
│ │ │ ├── RemotingSendRequestException.java
│ │ │ └── RemotingTimeoutException.java
│ │ ├── annotation
│ │ ├── RpcReference.java
│ │ └── RpcService.java
│ │ ├── properties
│ │ └── ZKProperties.java
│ │ ├── serialization
│ │ ├── serializer
│ │ │ ├── ISerializer.java
│ │ │ └── impl
│ │ │ │ ├── XmlSerializer.java
│ │ │ │ ├── ProtocolBufferSerializer.java
│ │ │ │ ├── HessianSerializer.java
│ │ │ │ ├── ThriftSerializer.java
│ │ │ │ ├── DefaultJavaSerializer.java
│ │ │ │ ├── AvroSerializer.java
│ │ │ │ ├── JSONSerializer.java
│ │ │ │ └── ProtoStuffSerializer.java
│ │ ├── SerializeTypeEnum.java
│ │ └── SerializerEngine.java
│ │ ├── handler
│ │ ├── RpcClientHandler.java
│ │ └── RpcServerHandler.java
│ │ ├── codec
│ │ ├── encode
│ │ │ └── RemotingTransporterEncoder.java
│ │ └── decode
│ │ │ └── RemotingTransporterDecoder.java
│ │ └── protocal
│ │ └── xuan
│ │ └── RemotingTransporter.java
├── .gitignore
└── pom.xml
├── .gitignore
├── rpc-netty-client-spring-boot-starter
├── .gitignore
└── pom.xml
├── rpc-netty-server-spring-boot-starter
├── .gitignore
└── pom.xml
├── README.md
└── pom.xml
/examples/rpc-provider/src/main/resources/application-slave1.yml:
--------------------------------------------------------------------------------
1 | rpc:
2 | server:
3 | port: 9991
--------------------------------------------------------------------------------
/examples/rpc-provider/src/main/resources/application-slave2.yml:
--------------------------------------------------------------------------------
1 | rpc:
2 | server:
3 | port: 9992
--------------------------------------------------------------------------------
/examples/rpc-lib/src/main/java/com/github/linshenkx/rpclib/HelloService.java:
--------------------------------------------------------------------------------
1 | package com.github.linshenkx.rpclib;
2 |
3 | public interface HelloService {
4 |
5 | String say(String name);
6 | }
7 |
--------------------------------------------------------------------------------
/rpc-netty-client-spring-boot-autoconfigure/src/main/resources/META-INF/spring.factories:
--------------------------------------------------------------------------------
1 | # AutoConfiguration
2 | org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
3 | com.github.linshenkx.rpcnettyclientspringbootautoconfigure.RpcClientAutoConfiguration
4 |
--------------------------------------------------------------------------------
/rpc-netty-server-spring-boot-autoconfigure/src/main/resources/META-INF/spring.factories:
--------------------------------------------------------------------------------
1 | # AutoConfiguration
2 | org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
3 | com.github.linshenkx.rpcnettyserverspringbootautoconfigure.RpcServerAutoConfiguration
4 |
--------------------------------------------------------------------------------
/examples/rpc-provider/src/main/resources/application.yml:
--------------------------------------------------------------------------------
1 | zk:
2 | address: 116.196.113.170:2181,116.196.113.170:2182,116.196.113.170:2183
3 | connectTimeOut: 10000
4 | sessionTimeOut: 10000
5 | registryPath: "/defaultRegistry"
6 | spring:
7 | profiles:
8 | active: slave1
--------------------------------------------------------------------------------
/rpc-netty-common/src/main/java/com/github/linshenkx/rpcnettycommon/bean/BodyContent.java:
--------------------------------------------------------------------------------
1 | package com.github.linshenkx.rpcnettycommon.bean;
2 |
3 | /**
4 | * @version V1.0
5 | * @author: lin_shen
6 | * @date: 18-11-12
7 | * @Description: TODO
8 | */
9 |
10 | public interface BodyContent {
11 | }
12 |
--------------------------------------------------------------------------------
/examples/rpc-consumer/src/main/resources/application.yml:
--------------------------------------------------------------------------------
1 | server:
2 | port: 9090
3 | zk:
4 | address: 116.196.113.170:2181,116.196.113.170:2182,116.196.113.170:2183
5 | connectTimeOut: 20000
6 | sessionTimeOut: 10000
7 | registryPath: "/defaultRegistry"
8 | rpc:
9 | client:
10 | routeStrategy: Polling
11 | serializeType: ProtoStuff
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /target/
2 | !.mvn/wrapper/maven-wrapper.jar
3 | .mvn
4 | mvnw
5 | mvnw.cmd
6 | ### STS ###
7 | .apt_generated
8 | .classpath
9 | .factorypath
10 | .project
11 | .settings
12 | .springBeans
13 | .sts4-cache
14 |
15 | ### IntelliJ IDEA ###
16 | .idea
17 | *.iws
18 | *.iml
19 | *.ipr
20 |
21 | ### NetBeans ###
22 | /nbproject/private/
23 | /build/
24 | /nbbuild/
25 | /dist/
26 | /nbdist/
27 | /.nb-gradle/
--------------------------------------------------------------------------------
/rpc-netty-common/src/main/java/com/github/linshenkx/rpcnettycommon/route/WeightGetAble.java:
--------------------------------------------------------------------------------
1 | package com.github.linshenkx.rpcnettycommon.route;
2 |
3 | /**
4 | * @version V1.0
5 | * @author: lin_shen
6 | * @date: 18-11-15
7 | * @Description: 权重接口,使用权重负载均衡的列表元素必须实现此接口
8 | */
9 |
10 | public interface WeightGetAble {
11 |
12 | default int getWeightFactors(){
13 | return 1;
14 | }
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/examples/.gitignore:
--------------------------------------------------------------------------------
1 | /target/
2 | !.mvn/wrapper/maven-wrapper.jar
3 | .mvn
4 | mvnw
5 | mvnw.cmd
6 | ### STS ###
7 | .apt_generated
8 | .classpath
9 | .factorypath
10 | .project
11 | .settings
12 | .springBeans
13 | .sts4-cache
14 |
15 | ### IntelliJ IDEA ###
16 | .idea
17 | *.iws
18 | *.iml
19 | *.ipr
20 |
21 | ### NetBeans ###
22 | /nbproject/private/
23 | /build/
24 | /nbbuild/
25 | /dist/
26 | /nbdist/
27 | /.nb-gradle/
--------------------------------------------------------------------------------
/examples/rpc-lib/.gitignore:
--------------------------------------------------------------------------------
1 | /target/
2 | !.mvn/wrapper/maven-wrapper.jar
3 | .mvn
4 | mvnw
5 | mvnw.cmd
6 | ### STS ###
7 | .apt_generated
8 | .classpath
9 | .factorypath
10 | .project
11 | .settings
12 | .springBeans
13 | .sts4-cache
14 |
15 | ### IntelliJ IDEA ###
16 | .idea
17 | *.iws
18 | *.iml
19 | *.ipr
20 |
21 | ### NetBeans ###
22 | /nbproject/private/
23 | /build/
24 | /nbbuild/
25 | /dist/
26 | /nbdist/
27 | /.nb-gradle/
--------------------------------------------------------------------------------
/rpc-netty-common/.gitignore:
--------------------------------------------------------------------------------
1 | /target/
2 | !.mvn/wrapper/maven-wrapper.jar
3 | .mvn
4 | mvnw
5 | mvnw.cmd
6 | ### STS ###
7 | .apt_generated
8 | .classpath
9 | .factorypath
10 | .project
11 | .settings
12 | .springBeans
13 | .sts4-cache
14 |
15 | ### IntelliJ IDEA ###
16 | .idea
17 | *.iws
18 | *.iml
19 | *.ipr
20 |
21 | ### NetBeans ###
22 | /nbproject/private/
23 | /build/
24 | /nbbuild/
25 | /dist/
26 | /nbdist/
27 | /.nb-gradle/
--------------------------------------------------------------------------------
/examples/rpc-consumer/.gitignore:
--------------------------------------------------------------------------------
1 | /target/
2 | !.mvn/wrapper/maven-wrapper.jar
3 | .mvn
4 | mvnw
5 | mvnw.cmd
6 | ### STS ###
7 | .apt_generated
8 | .classpath
9 | .factorypath
10 | .project
11 | .settings
12 | .springBeans
13 | .sts4-cache
14 |
15 | ### IntelliJ IDEA ###
16 | .idea
17 | *.iws
18 | *.iml
19 | *.ipr
20 |
21 | ### NetBeans ###
22 | /nbproject/private/
23 | /build/
24 | /nbbuild/
25 | /dist/
26 | /nbdist/
27 | /.nb-gradle/
--------------------------------------------------------------------------------
/examples/rpc-provider/.gitignore:
--------------------------------------------------------------------------------
1 | /target/
2 | !.mvn/wrapper/maven-wrapper.jar
3 | .mvn
4 | mvnw
5 | mvnw.cmd
6 | ### STS ###
7 | .apt_generated
8 | .classpath
9 | .factorypath
10 | .project
11 | .settings
12 | .springBeans
13 | .sts4-cache
14 |
15 | ### IntelliJ IDEA ###
16 | .idea
17 | *.iws
18 | *.iml
19 | *.ipr
20 |
21 | ### NetBeans ###
22 | /nbproject/private/
23 | /build/
24 | /nbbuild/
25 | /dist/
26 | /nbdist/
27 | /.nb-gradle/
--------------------------------------------------------------------------------
/rpc-netty-client-spring-boot-starter/.gitignore:
--------------------------------------------------------------------------------
1 | /target/
2 | !.mvn/wrapper/maven-wrapper.jar
3 | .mvn
4 | mvnw
5 | mvnw.cmd
6 | ### STS ###
7 | .apt_generated
8 | .classpath
9 | .factorypath
10 | .project
11 | .settings
12 | .springBeans
13 | .sts4-cache
14 |
15 | ### IntelliJ IDEA ###
16 | .idea
17 | *.iws
18 | *.iml
19 | *.ipr
20 |
21 | ### NetBeans ###
22 | /nbproject/private/
23 | /build/
24 | /nbbuild/
25 | /dist/
26 | /nbdist/
27 | /.nb-gradle/
--------------------------------------------------------------------------------
/rpc-netty-server-spring-boot-starter/.gitignore:
--------------------------------------------------------------------------------
1 | /target/
2 | !.mvn/wrapper/maven-wrapper.jar
3 | .mvn
4 | mvnw
5 | mvnw.cmd
6 | ### STS ###
7 | .apt_generated
8 | .classpath
9 | .factorypath
10 | .project
11 | .settings
12 | .springBeans
13 | .sts4-cache
14 |
15 | ### IntelliJ IDEA ###
16 | .idea
17 | *.iws
18 | *.iml
19 | *.ipr
20 |
21 | ### NetBeans ###
22 | /nbproject/private/
23 | /build/
24 | /nbbuild/
25 | /dist/
26 | /nbdist/
27 | /.nb-gradle/
--------------------------------------------------------------------------------
/rpc-netty-client-spring-boot-autoconfigure/.gitignore:
--------------------------------------------------------------------------------
1 | /target/
2 | !.mvn/wrapper/maven-wrapper.jar
3 | .mvn
4 | mvnw
5 | mvnw.cmd
6 | ### STS ###
7 | .apt_generated
8 | .classpath
9 | .factorypath
10 | .project
11 | .settings
12 | .springBeans
13 | .sts4-cache
14 |
15 | ### IntelliJ IDEA ###
16 | .idea
17 | *.iws
18 | *.iml
19 | *.ipr
20 |
21 | ### NetBeans ###
22 | /nbproject/private/
23 | /build/
24 | /nbbuild/
25 | /dist/
26 | /nbdist/
27 | /.nb-gradle/
--------------------------------------------------------------------------------
/rpc-netty-server-spring-boot-autoconfigure/.gitignore:
--------------------------------------------------------------------------------
1 | /target/
2 | !.mvn/wrapper/maven-wrapper.jar
3 | .mvn
4 | mvnw
5 | mvnw.cmd
6 | ### STS ###
7 | .apt_generated
8 | .classpath
9 | .factorypath
10 | .project
11 | .settings
12 | .springBeans
13 | .sts4-cache
14 |
15 | ### IntelliJ IDEA ###
16 | .idea
17 | *.iws
18 | *.iml
19 | *.ipr
20 |
21 | ### NetBeans ###
22 | /nbproject/private/
23 | /build/
24 | /nbbuild/
25 | /dist/
26 | /nbdist/
27 | /.nb-gradle/
--------------------------------------------------------------------------------
/rpc-netty-common/src/main/java/com/github/linshenkx/rpcnettycommon/exception/remoting/RemotingException.java:
--------------------------------------------------------------------------------
1 | package com.github.linshenkx.rpcnettycommon.exception.remoting;
2 |
3 |
4 | public class RemotingException extends Exception {
5 |
6 |
7 |
8 |
9 | public RemotingException(String message) {
10 | super(message);
11 | }
12 |
13 |
14 | public RemotingException(String message, Throwable cause) {
15 | super(message, cause);
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/examples/rpc-consumer/src/main/java/com/github/linshenkx/rpcconsumer/RpcConsumerApplication.java:
--------------------------------------------------------------------------------
1 | package com.github.linshenkx.rpcconsumer;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 |
6 | @SpringBootApplication
7 | public class RpcConsumerApplication {
8 |
9 | public static void main(String[] args) {
10 | SpringApplication.run(RpcConsumerApplication.class, args);
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/examples/rpc-provider/src/main/java/com/github/linshenkx/rpcprovider/RpcProviderApplication.java:
--------------------------------------------------------------------------------
1 | package com.github.linshenkx.rpcprovider;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 |
6 | @SpringBootApplication
7 | public class RpcProviderApplication {
8 |
9 | public static void main(String[] args) {
10 | SpringApplication.run(RpcProviderApplication.class, args);
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/rpc-netty-common/src/main/java/com/github/linshenkx/rpcnettycommon/exception/remoting/RemotingNoSighException.java:
--------------------------------------------------------------------------------
1 | package com.github.linshenkx.rpcnettycommon.exception.remoting;
2 |
3 |
4 | public class RemotingNoSighException extends RemotingException {
5 |
6 |
7 | public RemotingNoSighException(String message) {
8 | super(message, null);
9 | }
10 |
11 |
12 | public RemotingNoSighException(String message, Throwable cause) {
13 | super(message, cause);
14 | }
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/rpc-netty-common/src/main/java/com/github/linshenkx/rpcnettycommon/bean/RpcResponse.java:
--------------------------------------------------------------------------------
1 | package com.github.linshenkx.rpcnettycommon.bean;
2 |
3 | import lombok.Data;
4 |
5 | /**
6 | * @version V1.0
7 | * @author: lin_shen
8 | * @date: 2018/10/31
9 | * @Description: TODO
10 | */
11 | @Data
12 | public class RpcResponse implements BodyContent {
13 |
14 | /**
15 | * 异常信息
16 | */
17 | private Exception exception;
18 | /**
19 | * 响应结果
20 | */
21 | private Object result;
22 | }
23 |
--------------------------------------------------------------------------------
/rpc-netty-common/src/main/java/com/github/linshenkx/rpcnettycommon/exception/remoting/RemotingContextException.java:
--------------------------------------------------------------------------------
1 | package com.github.linshenkx.rpcnettycommon.exception.remoting;
2 |
3 |
4 | public class RemotingContextException extends RemotingException {
5 |
6 |
7 |
8 | public RemotingContextException(String message) {
9 | super(message, null);
10 | }
11 |
12 |
13 | public RemotingContextException(String message, Throwable cause) {
14 | super(message, cause);
15 | }
16 |
17 | }
18 |
--------------------------------------------------------------------------------
/examples/rpc-consumer/src/test/java/com/github/linshenkx/rpcconsumer/RpcConsumerApplicationTests.java:
--------------------------------------------------------------------------------
1 | package com.github.linshenkx.rpcconsumer;
2 |
3 | import org.junit.Test;
4 | import org.junit.runner.RunWith;
5 | import org.springframework.boot.test.context.SpringBootTest;
6 | import org.springframework.test.context.junit4.SpringRunner;
7 |
8 | @RunWith(SpringRunner.class)
9 | @SpringBootTest
10 | public class RpcConsumerApplicationTests {
11 |
12 | @Test
13 | public void contextLoads() {
14 | }
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/examples/rpc-provider/src/main/java/com/github/linshenkx/rpcprovider/Impl/HelloServiceImpl.java:
--------------------------------------------------------------------------------
1 | package com.github.linshenkx.rpcprovider.Impl;
2 |
3 |
4 | import com.github.linshenkx.rpclib.HelloService;
5 | import com.github.linshenkx.rpcnettycommon.annotation.RpcService;
6 |
7 | @RpcService(value = HelloService.class,weight = 2,workerThreads = 3)
8 | public class HelloServiceImpl implements HelloService {
9 |
10 | @Override
11 | public String say(String name) {
12 | return "hello " + name;
13 | }
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/examples/rpc-provider/src/test/java/com/github/linshenkx/rpcprovider/RpcProviderApplicationTests.java:
--------------------------------------------------------------------------------
1 | package com.github.linshenkx.rpcprovider;
2 |
3 | import org.junit.Test;
4 | import org.junit.runner.RunWith;
5 | import org.springframework.boot.test.context.SpringBootTest;
6 | import org.springframework.test.context.junit4.SpringRunner;
7 |
8 | @RunWith(SpringRunner.class)
9 | @SpringBootTest
10 | public class RpcProviderApplicationTests {
11 |
12 | @Test
13 | public void contextLoads() {
14 | }
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/rpc-netty-common/src/main/java/com/github/linshenkx/rpcnettycommon/exception/remoting/RemotingSendRequestException.java:
--------------------------------------------------------------------------------
1 | package com.github.linshenkx.rpcnettycommon.exception.remoting;
2 |
3 |
4 | public class RemotingSendRequestException extends RemotingException {
5 |
6 | public RemotingSendRequestException(String addr) {
7 | this(addr, null);
8 | }
9 |
10 |
11 | public RemotingSendRequestException(String addr, Throwable cause) {
12 | super("send request to <" + addr + "> failed", cause);
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/rpc-netty-server-spring-boot-autoconfigure/src/main/java/com/github/linshenkx/rpcnettyserverspringbootautoconfigure/properties/RpcServerProperties.java:
--------------------------------------------------------------------------------
1 | package com.github.linshenkx.rpcnettyserverspringbootautoconfigure.properties;
2 |
3 | import lombok.Data;
4 | import org.springframework.boot.context.properties.ConfigurationProperties;
5 |
6 | /**
7 | * @version V1.0
8 | * @author: lin_shen
9 | * @date: 2018/11/1
10 | * @Description: TODO
11 | */
12 | @Data
13 | @ConfigurationProperties(prefix = "rpc.server")
14 | public class RpcServerProperties {
15 | private int port=9000;
16 | }
17 |
--------------------------------------------------------------------------------
/rpc-netty-common/src/main/java/com/github/linshenkx/rpcnettycommon/annotation/RpcReference.java:
--------------------------------------------------------------------------------
1 | package com.github.linshenkx.rpcnettycommon.annotation;
2 |
3 | import org.springframework.stereotype.Service;
4 |
5 | import java.lang.annotation.ElementType;
6 | import java.lang.annotation.Retention;
7 | import java.lang.annotation.RetentionPolicy;
8 | import java.lang.annotation.Target;
9 |
10 | /**
11 | * @version V1.0
12 | * @author: lin_shen
13 | * @date: 18-12-1
14 | * @Description: 目前仅起标识作用
15 | */
16 | @Target({ElementType.FIELD})
17 | @Retention(RetentionPolicy.RUNTIME)
18 | @Service
19 | public @interface RpcReference {
20 |
21 | }
--------------------------------------------------------------------------------
/rpc-netty-common/src/main/java/com/github/linshenkx/rpcnettycommon/properties/ZKProperties.java:
--------------------------------------------------------------------------------
1 | package com.github.linshenkx.rpcnettycommon.properties;
2 |
3 | import lombok.Data;
4 | import org.springframework.boot.context.properties.ConfigurationProperties;
5 |
6 | /**
7 | * @version V1.0
8 | * @author: lin_shen
9 | * @date: 2018/11/1
10 | * @Description: TODO
11 | */
12 | @Data
13 | @ConfigurationProperties(prefix = "zk")
14 | public class ZKProperties {
15 | private String address ;
16 | private int sessionTimeOut=5000;
17 | private int connectTimeOut=1000;
18 | private String registryPath="/defaultRegistry";
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/examples/rpc-lib/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | rpc-lib
7 |
8 |
9 | com.github.linshenkx.test
10 | rpc-netty-spring-boot-starter-examples
11 | 2.0.2.RELEASE
12 | ../
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/rpc-netty-common/src/main/java/com/github/linshenkx/rpcnettycommon/route/impl/RandomRouteStrategyImpl.java:
--------------------------------------------------------------------------------
1 | package com.github.linshenkx.rpcnettycommon.route.impl;
2 |
3 | import com.github.linshenkx.rpcnettycommon.route.RouteStrategy;
4 | import org.apache.commons.lang3.RandomUtils;
5 |
6 | import java.util.List;
7 |
8 |
9 | /**
10 | * @version V1.0
11 | * @author: lin_shen
12 | * @date: 18-11-14
13 | * @Description: 随机策略 负载均衡
14 | */
15 | public class RandomRouteStrategyImpl implements RouteStrategy {
16 |
17 | @Override
18 | public T select(List primeList) {
19 | return primeList.get(RandomUtils.nextInt(0, primeList.size()));
20 | }
21 |
22 | }
23 |
--------------------------------------------------------------------------------
/rpc-netty-common/src/main/java/com/github/linshenkx/rpcnettycommon/bean/RpcRequest.java:
--------------------------------------------------------------------------------
1 | package com.github.linshenkx.rpcnettycommon.bean;
2 |
3 | import lombok.Data;
4 |
5 | /**
6 | * @version V1.0
7 | * @author: lin_shen
8 | * @date: 2018/10/31
9 | * @Description: TODO
10 | */
11 | @Data
12 | public class RpcRequest implements BodyContent {
13 |
14 | /**
15 | * 接口名称
16 | */
17 | private String interfaceName;
18 | /**
19 | * 方法名
20 | */
21 | private String methodName;
22 | /**
23 | * 方法参数类型列表
24 | */
25 | private Class>[] parameterTypes;
26 | /**
27 | * 参数列表
28 | */
29 | private Object[] parameters;
30 | }
31 |
--------------------------------------------------------------------------------
/rpc-netty-common/src/main/java/com/github/linshenkx/rpcnettycommon/exception/remoting/RemotingTimeoutException.java:
--------------------------------------------------------------------------------
1 | package com.github.linshenkx.rpcnettycommon.exception.remoting;
2 |
3 | public class RemotingTimeoutException extends RemotingException {
4 |
5 |
6 | public RemotingTimeoutException(String message) {
7 | super(message);
8 | }
9 |
10 |
11 | public RemotingTimeoutException(String addr, long timeoutMillis) {
12 | this(addr, timeoutMillis, null);
13 | }
14 |
15 |
16 | public RemotingTimeoutException(String addr, long timeoutMillis, Throwable cause) {
17 | super("wait response on the channel <" + addr + "> timeout, " + timeoutMillis + "(ms)", cause);
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/rpc-netty-common/src/main/java/com/github/linshenkx/rpcnettycommon/serialization/serializer/ISerializer.java:
--------------------------------------------------------------------------------
1 | package com.github.linshenkx.rpcnettycommon.serialization.serializer;
2 |
3 | /**
4 | * @version V1.0
5 | * @author: lin_shen
6 | * @date: 18-11-12
7 | * @Description: 序列化接口
8 | */
9 | public interface ISerializer {
10 |
11 | /**
12 | * 序列化
13 | * @param obj 序列化对象
14 | * @param 序列化对象原始类型
15 | * @return 字节数组
16 | */
17 | byte[] serialize(T obj);
18 |
19 |
20 | /**
21 | * 反序列化
22 | * @param data 序列化字节数组
23 | * @param clazz 原始类型的类对象
24 | * @param 原始类型
25 | * @return
26 | */
27 | T deserialize(byte[] data, Class clazz);
28 | }
29 |
--------------------------------------------------------------------------------
/rpc-netty-common/src/main/java/com/github/linshenkx/rpcnettycommon/route/RouteStrategy.java:
--------------------------------------------------------------------------------
1 | package com.github.linshenkx.rpcnettycommon.route;
2 |
3 | import java.util.List;
4 |
5 | /**
6 | * @version V1.0
7 | * @author: lin_shen
8 | * @date: 18-11-14
9 | * @Description: 路由策略接口
10 | */
11 | public interface RouteStrategy {
12 |
13 | /**
14 | * 负载策略算法
15 | *
16 | * @param primeList 原始列表
17 | * @return
18 | */
19 | T select(List primeList);
20 |
21 | /**
22 | * 带权负载策略算法
23 | *
24 | * @param primeList 原始列表
25 | * @return
26 | */
27 | default T selectWithWeight(List primeList){
28 | return select(WeightUtil.getWeightList(primeList));
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/rpc-netty-common/src/main/java/com/github/linshenkx/rpcnettycommon/annotation/RpcService.java:
--------------------------------------------------------------------------------
1 | package com.github.linshenkx.rpcnettycommon.annotation;
2 |
3 | import org.springframework.stereotype.Service;
4 |
5 | import java.lang.annotation.ElementType;
6 | import java.lang.annotation.Retention;
7 | import java.lang.annotation.RetentionPolicy;
8 | import java.lang.annotation.Target;
9 |
10 | /**
11 | * @version V1.0
12 | * @author: lin_shen
13 | * @date: 2018/10/31
14 | * @Description:
15 | * RPC服务注解(标注在rpc服务实现类上)
16 | * 使用@Service注解使被@RpcService标注的类都能被Spring管理
17 | */
18 | @Target({ElementType.TYPE})
19 | @Retention(RetentionPolicy.RUNTIME)
20 | @Service
21 | public @interface RpcService {
22 | Class> value();
23 | int weight() default 1;
24 | int workerThreads() default 10;
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/rpc-netty-client-spring-boot-autoconfigure/src/main/java/com/github/linshenkx/rpcnettyclientspringbootautoconfigure/properties/RpcClientProperties.java:
--------------------------------------------------------------------------------
1 | package com.github.linshenkx.rpcnettyclientspringbootautoconfigure.properties;
2 |
3 | import com.github.linshenkx.rpcnettycommon.route.RouteStrategyEnum;
4 | import com.github.linshenkx.rpcnettycommon.serialization.SerializeTypeEnum;
5 | import lombok.Data;
6 | import org.springframework.boot.context.properties.ConfigurationProperties;
7 |
8 | /**
9 | * @version V1.0
10 | * @author: lin_shen
11 | * @date: 2018/11/1
12 | * @Description: TODO
13 | */
14 | @Data
15 | @ConfigurationProperties(prefix = "rpc.client")
16 | public class RpcClientProperties {
17 | private RouteStrategyEnum routeStrategy= RouteStrategyEnum.Random;
18 | private SerializeTypeEnum serializeType=SerializeTypeEnum.JSON;
19 | }
20 |
--------------------------------------------------------------------------------
/rpc-netty-common/src/main/java/com/github/linshenkx/rpcnettycommon/route/RouteStrategyEnum.java:
--------------------------------------------------------------------------------
1 | package com.github.linshenkx.rpcnettycommon.route;
2 |
3 |
4 | /**
5 | * @version V1.0
6 | * @author: lin_shen
7 | * @date: 18-11-14
8 | * @Description: 路由策略 枚举类
9 | */
10 | public enum RouteStrategyEnum {
11 |
12 | //随机算法
13 | Random(0),
14 | //轮询算法
15 | Polling(1),
16 | //源地址hash算法
17 | HashIP(2);
18 |
19 |
20 | private int code;
21 |
22 | RouteStrategyEnum(int code) {
23 | this.code = code;
24 | }
25 |
26 | public static RouteStrategyEnum queryByCode (int code) {
27 | for (RouteStrategyEnum strategy : values()) {
28 | if(strategy.getCode()==code){
29 | return strategy;
30 | }
31 | }
32 | return null;
33 | }
34 |
35 | public int getCode() {
36 | return code;
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/rpc-netty-common/src/main/java/com/github/linshenkx/rpcnettycommon/route/WeightUtil.java:
--------------------------------------------------------------------------------
1 | package com.github.linshenkx.rpcnettycommon.route;
2 |
3 | import avro.shaded.com.google.common.collect.Lists;
4 |
5 | import java.util.List;
6 |
7 | /**
8 | * @version V1.0
9 | * @author: lin_shen
10 | * @date: 18-11-15
11 | * @Description: TODO
12 | */
13 |
14 | public enum WeightUtil {
15 | INSTANCE;
16 | public static List getWeightList(List primeList){
17 | //存放加权后列表
18 | List weightList= Lists.newArrayList();
19 | for (T prime:primeList){
20 | //按权重转化为次数添加进加权后列表
21 | //TODO:需注意权重代表列表长度,故不可过大,此处应优化
22 | int weight=prime.getWeightFactors();
23 | for(int i=0;i byte[] serialize(T obj) {
17 | return xStream.toXML(obj).getBytes();
18 | }
19 |
20 | @Override
21 | public T deserialize(byte[] data, Class clazz) {
22 | String xml = new String(data);
23 | return (T) xStream.fromXML(xml);
24 | }
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/rpc-netty-server-spring-boot-starter/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | rpc-netty-server-spring-boot-starter
7 |
8 |
9 | com.github.linshenkx
10 | rpc-netty-spring-boot-starter
11 | 2.0.2.RELEASE
12 | ../
13 |
14 |
15 |
16 |
17 | com.github.linshenkx
18 | rpc-netty-server-spring-boot-autoconfigure
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/rpc-netty-client-spring-boot-starter/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | rpc-netty-client-spring-boot-starter
7 |
8 |
9 | com.github.linshenkx
10 | rpc-netty-spring-boot-starter
11 | 2.0.2.RELEASE
12 | ../
13 |
14 |
15 |
16 |
17 | com.github.linshenkx
18 | rpc-netty-client-spring-boot-autoconfigure
19 |
20 |
21 |
22 |
23 |
24 |
--------------------------------------------------------------------------------
/rpc-netty-common/src/main/java/com/github/linshenkx/rpcnettycommon/bean/ServiceInfo.java:
--------------------------------------------------------------------------------
1 | package com.github.linshenkx.rpcnettycommon.bean;
2 |
3 | import com.github.linshenkx.rpcnettycommon.route.WeightGetAble;
4 | import lombok.AllArgsConstructor;
5 | import lombok.Data;
6 | import lombok.NoArgsConstructor;
7 |
8 | /**
9 | * @version V1.0
10 | * @author: lin_shen
11 | * @date: 18-11-13
12 | * @Description: 服务信息,用于存储到注册中心
13 | */
14 | @Data
15 | @AllArgsConstructor
16 | @NoArgsConstructor
17 | public class ServiceInfo implements WeightGetAble {
18 |
19 | private String host;
20 | private int port;
21 | /**
22 | * 权重信息
23 | */
24 | private int weight;
25 | /**
26 | * 最大工作线程数
27 | */
28 | private int workerThreads;
29 |
30 | public ServiceInfo (ServiceInfo serviceInfo){
31 | this.host = serviceInfo.host;
32 | this.port = serviceInfo.port;
33 | this.weight = serviceInfo.weight;
34 | this.workerThreads = serviceInfo.workerThreads;
35 | }
36 |
37 | @Override
38 | public int getWeightFactors() {
39 | return getWeight();
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/examples/rpc-consumer/src/main/java/com/github/linshenkx/rpcconsumer/controller/HelloController.java:
--------------------------------------------------------------------------------
1 | package com.github.linshenkx.rpcconsumer.controller;
2 |
3 |
4 | import com.github.linshenkx.rpclib.HelloService;
5 | import com.github.linshenkx.rpcnettycommon.annotation.RpcReference;
6 | import lombok.extern.log4j.Log4j2;
7 | import org.springframework.util.StopWatch;
8 | import org.springframework.web.bind.annotation.GetMapping;
9 | import org.springframework.web.bind.annotation.RequestParam;
10 | import org.springframework.web.bind.annotation.RestController;
11 |
12 | /**
13 | * @version V1.0
14 | * @author: lin_shen
15 | * @date: 2018/11/1
16 | * @Description: TODO
17 | */
18 | @RestController
19 | @Log4j2
20 | public class HelloController {
21 |
22 | @RpcReference
23 | private HelloService helloService;
24 |
25 | @GetMapping("/hello")
26 | public String sayHello(@RequestParam(defaultValue = "lin") String name){
27 | StopWatch stopwatch = new StopWatch();
28 | stopwatch.start();
29 | String returnString= helloService.say(name);
30 | stopwatch.stop();
31 | log.info("耗时:"+stopwatch.getTotalTimeSeconds()+"seconds");
32 | return returnString;
33 | }
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/rpc-netty-common/src/main/java/com/github/linshenkx/rpcnettycommon/serialization/serializer/impl/ProtocolBufferSerializer.java:
--------------------------------------------------------------------------------
1 | package com.github.linshenkx.rpcnettycommon.serialization.serializer.impl;
2 |
3 | import com.github.linshenkx.rpcnettycommon.serialization.serializer.ISerializer;
4 | import org.apache.commons.lang3.reflect.MethodUtils;
5 |
6 | /**
7 | * @version V1.0
8 | * @author: lin_shen
9 | * @date: 2018/11/18
10 | * @Description: ProtocolBuffer序列化(只能序列化IDL产生的类)
11 | */
12 | public class ProtocolBufferSerializer implements ISerializer {
13 |
14 | @Override
15 | public byte[] serialize(T obj) {
16 | try {
17 | return (byte[]) MethodUtils.invokeMethod(obj, "toByteArray");
18 | } catch (Exception e) {
19 | e.printStackTrace();
20 | }
21 | return null;
22 | }
23 |
24 | @Override
25 | public T deserialize(byte[] data, Class cls) {
26 | try {
27 | Object o = MethodUtils.invokeStaticMethod(cls, "getDefaultInstance");
28 | return (T) MethodUtils.invokeMethod(o, "parseFrom", new Object[]{data});
29 | } catch (Exception e) {
30 | e.printStackTrace();
31 | }
32 | return null;
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/rpc-netty-common/src/main/java/com/github/linshenkx/rpcnettycommon/route/impl/HashIPRouteStrategyImpl.java:
--------------------------------------------------------------------------------
1 | package com.github.linshenkx.rpcnettycommon.route.impl;
2 |
3 |
4 | import com.github.linshenkx.rpcnettycommon.route.RouteStrategy;
5 | import org.apache.commons.lang3.RandomUtils;
6 |
7 | import java.net.InetAddress;
8 | import java.net.UnknownHostException;
9 | import java.util.List;
10 |
11 | /**
12 | * @version V1.0
13 | * @author: lin_shen
14 | * @date: 18-11-14
15 | * @Description: 基于本地IP的哈希策略 负载均衡
16 | */
17 | public class HashIPRouteStrategyImpl implements RouteStrategy {
18 |
19 | @Override
20 | public T select(List primeList) {
21 | String localIP=null;
22 | try {
23 | localIP=InetAddress.getLocalHost().getHostName();
24 | } catch (UnknownHostException e) {
25 | e.printStackTrace();
26 | }
27 | //保证程序健壮性,若未取到域名,则采用改用随机字符串
28 | if(localIP==null){
29 | localIP= RandomUtils.nextBytes(5).toString();
30 | }
31 |
32 | //获取源地址对应的hashcode
33 | int hashCode = localIP.hashCode();
34 | //获取服务列表大小
35 | int size = primeList.size();
36 |
37 | return primeList.get(Math.abs(hashCode) % size);
38 | }
39 |
40 | }
41 |
--------------------------------------------------------------------------------
/rpc-netty-common/src/main/java/com/github/linshenkx/rpcnettycommon/serialization/SerializeTypeEnum.java:
--------------------------------------------------------------------------------
1 | package com.github.linshenkx.rpcnettycommon.serialization;
2 |
3 | /**
4 | * @version V1.0
5 | * @author: lin_shen
6 | * @date: 18-11-18
7 | * @Description: 序列化枚举类
8 | */
9 | public enum SerializeTypeEnum {
10 | /**
11 | * Java默认序列化
12 | */
13 | DefaultJava(0),
14 | /**
15 | * Hessian序列化
16 | */
17 | Hessian(1),
18 | /**
19 | * Json序列化(基于Jackson)
20 | */
21 | JSON(2),
22 | /**
23 | * Protostuff序列化
24 | */
25 | ProtoStuff(3),
26 | /**
27 | * Xml序列化
28 | */
29 | Xml(4),
30 |
31 |
32 | /**
33 | * Avro序列化,需借助IDL
34 | */
35 | Avro(5),
36 | /**
37 | * ProtocolBuffer序列化,需借助IDL
38 | */
39 | ProtocolBuffer(6),
40 | /**
41 | * Thrift序列化,需借助IDL
42 | */
43 | Thrift(7);
44 |
45 | private int code;
46 |
47 | SerializeTypeEnum(int code) {
48 | this.code = code;
49 | }
50 |
51 | public static SerializeTypeEnum queryByCode (int code) {
52 | for (SerializeTypeEnum type : values()) {
53 | if(type.getCode()==code){
54 | return type;
55 | }
56 | }
57 | return null;
58 | }
59 |
60 | public int getCode() {
61 | return code;
62 | }
63 |
64 | }
65 |
--------------------------------------------------------------------------------
/rpc-netty-common/src/main/java/com/github/linshenkx/rpcnettycommon/serialization/serializer/impl/HessianSerializer.java:
--------------------------------------------------------------------------------
1 | package com.github.linshenkx.rpcnettycommon.serialization.serializer.impl;
2 |
3 | import com.caucho.hessian.io.HessianInput;
4 | import com.caucho.hessian.io.HessianOutput;
5 | import com.github.linshenkx.rpcnettycommon.serialization.serializer.ISerializer;
6 |
7 | import java.io.ByteArrayInputStream;
8 | import java.io.ByteArrayOutputStream;
9 |
10 | /**
11 | * @version V1.0
12 | * @author: lin_shen
13 | * @date: 18-11-18
14 | * @Description: Hessian序列化(需有Serializable接口)
15 | */
16 | public class HessianSerializer implements ISerializer {
17 |
18 |
19 | @Override
20 | public byte[] serialize(Object obj) {
21 | try(ByteArrayOutputStream os = new ByteArrayOutputStream()) {
22 | HessianOutput ho = new HessianOutput(os);
23 | ho.writeObject(obj);
24 | return os.toByteArray();
25 | } catch (Exception e) {
26 | throw new RuntimeException(e);
27 | }
28 | }
29 |
30 | @Override
31 | public T deserialize(byte[] data, Class clazz) {
32 |
33 | try(ByteArrayInputStream is = new ByteArrayInputStream(data)) {
34 | HessianInput hi = new HessianInput(is);
35 | return (T) hi.readObject();
36 | } catch (Exception e) {
37 | throw new RuntimeException(e);
38 | }
39 |
40 | }
41 |
42 | }
43 |
--------------------------------------------------------------------------------
/rpc-netty-common/src/main/java/com/github/linshenkx/rpcnettycommon/serialization/serializer/impl/ThriftSerializer.java:
--------------------------------------------------------------------------------
1 | package com.github.linshenkx.rpcnettycommon.serialization.serializer.impl;
2 |
3 | import com.github.linshenkx.rpcnettycommon.serialization.serializer.ISerializer;
4 | import org.apache.thrift.TBase;
5 | import org.apache.thrift.TDeserializer;
6 | import org.apache.thrift.TException;
7 | import org.apache.thrift.TSerializer;
8 | import org.apache.thrift.protocol.TBinaryProtocol;
9 |
10 | /**
11 | * @version V1.0
12 | * @author: lin_shen
13 | * @date: 2018/11/18
14 | * @Description: Thrift序列化(只能序列化IDL产生的类)
15 | */
16 | public class ThriftSerializer implements ISerializer {
17 |
18 | @Override
19 | public byte[] serialize(T obj) {
20 | try {
21 | TSerializer serializer = new TSerializer(new TBinaryProtocol.Factory());
22 | return serializer.serialize((TBase) obj);
23 | } catch (TException e) {
24 | throw new RuntimeException(e);
25 | }
26 | }
27 |
28 | @Override
29 | public T deserialize(byte[] data, Class clazz) {
30 | try {
31 | TBase o = (TBase) clazz.newInstance();
32 | TDeserializer tDeserializer = new TDeserializer();
33 | tDeserializer.deserialize(o, data);
34 | return (T) o;
35 | } catch (Exception e) {
36 | throw new RuntimeException(e);
37 | }
38 |
39 | }
40 |
41 | }
42 |
--------------------------------------------------------------------------------
/rpc-netty-common/src/main/java/com/github/linshenkx/rpcnettycommon/route/impl/PollingRouteStrategyImpl.java:
--------------------------------------------------------------------------------
1 | package com.github.linshenkx.rpcnettycommon.route.impl;
2 |
3 |
4 | import com.github.linshenkx.rpcnettycommon.route.RouteStrategy;
5 | import org.apache.commons.lang3.RandomUtils;
6 |
7 | import java.util.List;
8 | import java.util.concurrent.TimeUnit;
9 | import java.util.concurrent.locks.Lock;
10 | import java.util.concurrent.locks.ReentrantLock;
11 |
12 | /**
13 | * @version V1.0
14 | * @author: lin_shen
15 | * @date: 18-11-14
16 | * @Description: 轮询策略 负载均衡
17 | */
18 | public class PollingRouteStrategyImpl implements RouteStrategy {
19 |
20 | /**
21 | * 计数器
22 | */
23 | private int index = 0;
24 | private Lock lock = new ReentrantLock();
25 |
26 | @Override
27 | public T select(List primeList) {
28 | T point=null;
29 | try {
30 | lock.tryLock(10,TimeUnit.MILLISECONDS);
31 | //若计数大于列表元素个数,将计数器归0
32 | if (index >= primeList.size()) {
33 | index = 0;
34 | }
35 | point=primeList.get(index++);
36 | }catch (InterruptedException e){
37 | e.printStackTrace();
38 | }finally {
39 | lock.unlock();
40 | }
41 | //保证程序健壮性,若未取到服务,则改用随机算法
42 | if (point == null) {
43 | point = primeList.get(RandomUtils.nextInt(0, primeList.size()));
44 | }
45 | return point;
46 | }
47 |
48 | }
49 |
--------------------------------------------------------------------------------
/rpc-netty-common/src/main/java/com/github/linshenkx/rpcnettycommon/handler/RpcClientHandler.java:
--------------------------------------------------------------------------------
1 | package com.github.linshenkx.rpcnettycommon.handler;
2 |
3 | import com.github.linshenkx.rpcnettycommon.protocal.xuan.RemotingTransporter;
4 | import io.netty.channel.ChannelHandlerContext;
5 | import io.netty.channel.SimpleChannelInboundHandler;
6 | import lombok.extern.log4j.Log4j2;
7 |
8 | import java.util.concurrent.ConcurrentMap;
9 |
10 | /**
11 | * @version V1.0
12 | * @author: lin_shen
13 | * @date: 2018/11/1
14 | * @Description: TODO
15 | */
16 | @Log4j2
17 | public class RpcClientHandler extends SimpleChannelInboundHandler {
18 |
19 | private ConcurrentMap remotingTransporterMap;
20 |
21 | public RpcClientHandler(ConcurrentMap remotingTransporterMap){
22 | this.remotingTransporterMap=remotingTransporterMap;
23 | }
24 |
25 | @Override
26 | protected void channelRead0(ChannelHandlerContext channelHandlerContext, RemotingTransporter remotingTransporter) throws Exception {
27 | log.info("read a Response,invokeId: "+remotingTransporter.getInvokeId());
28 | remotingTransporterMap.put(remotingTransporter.getInvokeId(),remotingTransporter);
29 | }
30 | @Override
31 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
32 | throws Exception {
33 | log.error("client caught exception",cause);
34 | ctx.close();
35 | }
36 |
37 |
38 | }
39 |
--------------------------------------------------------------------------------
/rpc-netty-common/src/main/java/com/github/linshenkx/rpcnettycommon/codec/encode/RemotingTransporterEncoder.java:
--------------------------------------------------------------------------------
1 | package com.github.linshenkx.rpcnettycommon.codec.encode;
2 |
3 | import com.github.linshenkx.rpcnettycommon.protocal.xuan.RemotingTransporter;
4 | import com.github.linshenkx.rpcnettycommon.serialization.SerializeTypeEnum;
5 | import com.github.linshenkx.rpcnettycommon.serialization.SerializerEngine;
6 | import io.netty.buffer.ByteBuf;
7 | import io.netty.channel.ChannelHandlerContext;
8 | import io.netty.handler.codec.MessageToByteEncoder;
9 | import lombok.extern.log4j.Log4j2;
10 |
11 | /**
12 | * @version V1.0
13 | * @author: lin_shen
14 | * @date: 18-11-12
15 | * @Description: TODO
16 | */
17 | @Log4j2
18 | public class RemotingTransporterEncoder extends MessageToByteEncoder {
19 |
20 |
21 | @Override
22 | protected void encode(ChannelHandlerContext channelHandlerContext, RemotingTransporter remotingTransporter, ByteBuf byteBuf) throws Exception {
23 | //获取请求体数组
24 | //使用序列化引擎
25 | byte[] body= SerializerEngine.serialize(remotingTransporter.getBodyContent(), SerializeTypeEnum.queryByCode(remotingTransporter.getFlag().getSerializeType()));
26 | //magic+flag+invokeId+bodyLength+bodyContent
27 | byteBuf.writeShort(RemotingTransporter.MAGIC)
28 | .writeByte(remotingTransporter.getFlag().getThisByte())
29 | .writeLong(remotingTransporter.getInvokeId())
30 | .writeInt(body.length)
31 | .writeBytes(body);
32 | log.info("write end");
33 |
34 | }
35 |
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/rpc-netty-common/src/main/java/com/github/linshenkx/rpcnettycommon/serialization/serializer/impl/DefaultJavaSerializer.java:
--------------------------------------------------------------------------------
1 | package com.github.linshenkx.rpcnettycommon.serialization.serializer.impl;
2 |
3 |
4 | import com.github.linshenkx.rpcnettycommon.serialization.serializer.ISerializer;
5 |
6 | import java.io.ByteArrayInputStream;
7 | import java.io.ByteArrayOutputStream;
8 | import java.io.ObjectInputStream;
9 | import java.io.ObjectOutputStream;
10 |
11 | /**
12 | * @version V1.0
13 | * @author: lin_shen
14 | * @date: 18-11-18
15 | * @Description: Java默认序列化(需有Serializable接口)
16 | */
17 | public class DefaultJavaSerializer implements ISerializer {
18 |
19 |
20 | @Override
21 | public byte[] serialize(T obj) {
22 | ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
23 | try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream)){
24 | objectOutputStream.writeObject(obj);
25 | } catch (Exception e) {
26 | throw new RuntimeException(e);
27 | }
28 | return byteArrayOutputStream.toByteArray();
29 | }
30 |
31 |
32 | @Override
33 | public T deserialize(byte[] data, Class clazz) {
34 |
35 | ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data);
36 | try {
37 | ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
38 | return (T) objectInputStream.readObject();
39 | } catch (Exception e) {
40 | throw new RuntimeException(e);
41 | }
42 | }
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/rpc-netty-common/src/main/java/com/github/linshenkx/rpcnettycommon/route/RouteEngine.java:
--------------------------------------------------------------------------------
1 | package com.github.linshenkx.rpcnettycommon.route;
2 |
3 |
4 | import com.github.linshenkx.rpcnettycommon.route.impl.HashIPRouteStrategyImpl;
5 | import com.github.linshenkx.rpcnettycommon.route.impl.PollingRouteStrategyImpl;
6 | import com.github.linshenkx.rpcnettycommon.route.impl.RandomRouteStrategyImpl;
7 |
8 | /**
9 | * @version V1.0
10 | * @author: lin_shen
11 | * @date: 18-11-12
12 | * @Description: 路由均衡引擎
13 | */
14 | public class RouteEngine {
15 |
16 | private final static RouteStrategy RANDOM_ROUTE_STRATEGY_IMPL =new RandomRouteStrategyImpl();
17 |
18 | private final static RouteStrategy HASHIP_ROUTE_STRATEGY_IMPL =new HashIPRouteStrategyImpl();
19 |
20 | public static RouteStrategy queryClusterStrategy(int clusterStrategyCode) {
21 | RouteStrategyEnum clusterStrategyEnum = RouteStrategyEnum.queryByCode(clusterStrategyCode);
22 | return queryClusterStrategy(clusterStrategyEnum);
23 | }
24 |
25 | public static RouteStrategy queryClusterStrategy(RouteStrategyEnum routeStrategyEnum) {
26 | if(routeStrategyEnum==null){
27 | return new RandomRouteStrategyImpl();
28 | }
29 | switch (routeStrategyEnum){
30 | case Random:
31 | return RANDOM_ROUTE_STRATEGY_IMPL ;
32 | case Polling:
33 | return new PollingRouteStrategyImpl();
34 | case HashIP:
35 | return HASHIP_ROUTE_STRATEGY_IMPL ;
36 | default:
37 | return RANDOM_ROUTE_STRATEGY_IMPL ;
38 | }
39 | }
40 |
41 | }
42 |
--------------------------------------------------------------------------------
/rpc-netty-server-spring-boot-autoconfigure/src/main/java/com/github/linshenkx/rpcnettyserverspringbootautoconfigure/RpcServerAutoConfiguration.java:
--------------------------------------------------------------------------------
1 | package com.github.linshenkx.rpcnettyserverspringbootautoconfigure;
2 |
3 |
4 | import com.github.linshenkx.rpcnettycommon.properties.ZKProperties;
5 | import com.github.linshenkx.rpcnettyserverspringbootautoconfigure.properties.RpcServerProperties;
6 | import com.github.linshenkx.rpcnettyserverspringbootautoconfigure.registry.zookeeper.ZKServiceRegistry;
7 | import com.github.linshenkx.rpcnettyserverspringbootautoconfigure.server.RpcServer;
8 | import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
9 | import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
10 | import org.springframework.context.annotation.Bean;
11 | import org.springframework.context.annotation.Configuration;
12 |
13 | /**
14 | * @version V1.0
15 | * @author: lin_shen
16 | * @date: 2018/11/2
17 | * @Description: TODO
18 | */
19 | @Configuration
20 | @ConditionalOnClass(RpcServer.class)
21 | public class RpcServerAutoConfiguration {
22 | @ConditionalOnMissingBean
23 | @Bean
24 | public RpcServerProperties defaultRpcServerProperties(){
25 | return new RpcServerProperties();
26 | }
27 |
28 | @ConditionalOnMissingBean
29 | @Bean
30 | public ZKProperties defaultZKProperties(){
31 | return new ZKProperties();
32 | }
33 |
34 | @ConditionalOnMissingBean
35 | @Bean
36 | public ZKServiceRegistry zkServiceRegistry(){
37 | return new ZKServiceRegistry();
38 | }
39 |
40 | @Bean
41 | public RpcServer rpcServer(){
42 | return new RpcServer();
43 | }
44 |
45 |
46 |
47 | }
48 |
--------------------------------------------------------------------------------
/examples/rpc-provider/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | rpc-provider
7 |
8 |
9 | com.github.linshenkx.test
10 | rpc-netty-spring-boot-starter-examples
11 | 2.0.2.RELEASE
12 | ../
13 |
14 |
15 |
16 |
17 | com.github.linshenkx.test
18 | rpc-lib
19 |
20 |
21 | com.github.linshenkx
22 | rpc-netty-server-spring-boot-starter
23 |
24 |
25 | org.springframework.boot
26 | spring-boot-starter
27 |
28 |
29 | org.springframework.boot
30 | spring-boot-starter-test
31 | test
32 |
33 |
34 |
35 |
36 |
37 |
38 | org.springframework.boot
39 | spring-boot-maven-plugin
40 |
41 |
42 |
43 |
44 |
45 |
46 |
--------------------------------------------------------------------------------
/rpc-netty-client-spring-boot-autoconfigure/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | rpc-netty-client-spring-boot-autoconfigure
7 |
8 |
9 | com.github.linshenkx
10 | rpc-netty-spring-boot-starter
11 | 2.0.2.RELEASE
12 | ../
13 |
14 |
15 |
16 |
17 | org.springframework.boot
18 | spring-boot-starter
19 |
20 |
21 | org.springframework.boot
22 | spring-boot-configuration-processor
23 |
24 |
25 | com.github.linshenkx
26 | rpc-netty-common
27 |
28 |
29 | org.projectlombok
30 | lombok
31 | true
32 |
33 |
34 | io.netty
35 | netty-all
36 |
37 |
38 | com.101tec
39 | zkclient
40 |
41 |
42 |
43 |
44 |
--------------------------------------------------------------------------------
/rpc-netty-server-spring-boot-autoconfigure/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | rpc-netty-server-spring-boot-autoconfigure
7 |
8 |
9 | com.github.linshenkx
10 | rpc-netty-spring-boot-starter
11 | 2.0.2.RELEASE
12 | ../
13 |
14 |
15 |
16 |
17 | org.springframework.boot
18 | spring-boot-starter
19 |
20 |
21 | org.springframework.boot
22 | spring-boot-configuration-processor
23 |
24 |
25 | com.github.linshenkx
26 | rpc-netty-common
27 |
28 |
29 | org.projectlombok
30 | lombok
31 | true
32 |
33 |
34 | io.netty
35 | netty-all
36 |
37 |
38 | com.101tec
39 | zkclient
40 |
41 |
42 |
43 |
44 |
--------------------------------------------------------------------------------
/rpc-netty-common/src/main/java/com/github/linshenkx/rpcnettycommon/serialization/serializer/impl/AvroSerializer.java:
--------------------------------------------------------------------------------
1 | package com.github.linshenkx.rpcnettycommon.serialization.serializer.impl;
2 |
3 |
4 |
5 |
6 | import com.github.linshenkx.rpcnettycommon.serialization.serializer.ISerializer;
7 | import org.apache.avro.io.*;
8 | import org.apache.avro.specific.SpecificDatumReader;
9 | import org.apache.avro.specific.SpecificDatumWriter;
10 | import java.io.ByteArrayInputStream;
11 | import java.io.ByteArrayOutputStream;
12 |
13 | /**
14 | * @version V1.0
15 | * @author: lin_shen
16 | * @date: 2018/11/18
17 | * @Description: AvroSerializer(只能序列化IDL产生的类)
18 | */
19 | public class AvroSerializer implements ISerializer {
20 |
21 |
22 | @Override
23 | public byte[] serialize(T obj) {
24 | try {
25 | DatumWriter userDatumWriter = new SpecificDatumWriter(obj.getClass());
26 | ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
27 | BinaryEncoder binaryEncoder = EncoderFactory.get().directBinaryEncoder(outputStream, null);
28 | userDatumWriter.write(obj, binaryEncoder);
29 | return outputStream.toByteArray();
30 | } catch (Exception e) {
31 | throw new RuntimeException(e);
32 | }
33 | }
34 |
35 |
36 | @Override
37 | public T deserialize(byte[] data, Class clazz) {
38 | try {
39 | DatumReader userDatumReader = new SpecificDatumReader(clazz);
40 | BinaryDecoder binaryDecoder = DecoderFactory.get().directBinaryDecoder(new ByteArrayInputStream(data), null);
41 | return (T) userDatumReader.read(clazz.newInstance(), binaryDecoder);
42 | } catch (Exception e) {
43 | throw new RuntimeException(e);
44 | }
45 |
46 | }
47 |
48 | }
49 |
--------------------------------------------------------------------------------
/examples/rpc-consumer/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | rpc-consumer
7 |
8 |
9 | com.github.linshenkx.test
10 | rpc-netty-spring-boot-starter-examples
11 | 2.0.2.RELEASE
12 | ../
13 |
14 |
15 |
16 |
17 | com.github.linshenkx.test
18 | rpc-lib
19 |
20 |
21 | com.github.linshenkx
22 | rpc-netty-client-spring-boot-starter
23 |
24 |
25 | org.springframework.boot
26 | spring-boot-starter-web
27 |
28 |
29 | org.projectlombok
30 | lombok
31 | true
32 |
33 |
34 | org.springframework.boot
35 | spring-boot-starter-test
36 | test
37 |
38 |
39 |
40 |
41 |
42 |
43 | org.springframework.boot
44 | spring-boot-maven-plugin
45 |
46 |
47 |
48 |
49 |
50 |
51 |
--------------------------------------------------------------------------------
/rpc-netty-common/src/main/java/com/github/linshenkx/rpcnettycommon/serialization/SerializerEngine.java:
--------------------------------------------------------------------------------
1 | package com.github.linshenkx.rpcnettycommon.serialization;
2 |
3 |
4 | import avro.shaded.com.google.common.collect.Maps;
5 | import com.github.linshenkx.rpcnettycommon.serialization.serializer.ISerializer;
6 | import com.github.linshenkx.rpcnettycommon.serialization.serializer.impl.*;
7 |
8 | import java.util.Map;
9 |
10 | /**
11 | * @version V1.0
12 | * @author: lin_shen
13 | * @date: 18-11-18
14 | * @Description: 序列化引擎
15 | */
16 | public class SerializerEngine {
17 |
18 | private static final Map SERIALIZER_MAP = Maps.newConcurrentMap();
19 |
20 | static {
21 | SERIALIZER_MAP.put(SerializeTypeEnum.DefaultJava, new DefaultJavaSerializer());
22 | SERIALIZER_MAP.put(SerializeTypeEnum.Hessian, new HessianSerializer());
23 | SERIALIZER_MAP.put(SerializeTypeEnum.JSON, new JSONSerializer());
24 | SERIALIZER_MAP.put(SerializeTypeEnum.Xml, new XmlSerializer());
25 | SERIALIZER_MAP.put(SerializeTypeEnum.ProtoStuff, new ProtoStuffSerializer());
26 |
27 | //以下三类不能使用普通的java bean,需借助IDL
28 | SERIALIZER_MAP.put(SerializeTypeEnum.Avro, new AvroSerializer());
29 | SERIALIZER_MAP.put(SerializeTypeEnum.Thrift, new ThriftSerializer());
30 | SERIALIZER_MAP.put(SerializeTypeEnum.ProtocolBuffer, new ProtocolBufferSerializer());
31 | }
32 |
33 | public static byte[] serialize(T obj, SerializeTypeEnum serializeTypeEnum) {
34 |
35 | ISerializer serializer = SERIALIZER_MAP.get(serializeTypeEnum);
36 | return serializer.serialize(obj);
37 | }
38 |
39 | public static T deserialize(byte[] data, Class clazz, SerializeTypeEnum serializeTypeEnum) {
40 |
41 | ISerializer serializer = SERIALIZER_MAP.get(serializeTypeEnum);
42 | return serializer.deserialize(data, clazz);
43 |
44 | }
45 |
46 | }
47 |
--------------------------------------------------------------------------------
/rpc-netty-common/src/main/java/com/github/linshenkx/rpcnettycommon/serialization/serializer/impl/JSONSerializer.java:
--------------------------------------------------------------------------------
1 | package com.github.linshenkx.rpcnettycommon.serialization.serializer.impl;
2 |
3 |
4 | import com.fasterxml.jackson.core.JsonParser;
5 | import com.fasterxml.jackson.databind.DeserializationFeature;
6 | import com.fasterxml.jackson.databind.ObjectMapper;
7 | import com.github.linshenkx.rpcnettycommon.serialization.serializer.ISerializer;
8 |
9 | /**
10 | * @version V1.0
11 | * @author: lin_shen
12 | * @date: 18-11-18
13 | * @Description: Json序列化(基于jackson实现)
14 | */
15 | public class JSONSerializer implements ISerializer {
16 |
17 |
18 | /**
19 | * ObjectMapper可配置json序列化规则,该类的创建需要消耗较多资源,故应配置为类成员对象
20 | */
21 | private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
22 |
23 |
24 |
25 | static {
26 | //允许字段名不带引号(这不符合JSON标准,但在JS中合法)
27 | OBJECT_MAPPER.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
28 | //允许使用单引号代替双引号(这不符合JSON标准,但这一些JSON生成器中合法)
29 | OBJECT_MAPPER.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
30 | //允许携带不加引号的控制字符(即ASCII码小于32的),不符合JSON标准,故默认为false
31 | OBJECT_MAPPER.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
32 | //允许出现未定义处理方法(没有对应的setter方法或其他的处理器)的未知字段
33 | OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
34 |
35 | }
36 |
37 | @Override
38 | public byte[] serialize(T obj) {
39 | try {
40 | String json = OBJECT_MAPPER.writeValueAsString(obj);
41 | return json.getBytes();
42 | } catch (Exception e) {
43 | throw new RuntimeException(e);
44 | }
45 | }
46 |
47 | @Override
48 | public T deserialize(byte[] data, Class clazz) {
49 | String json = new String(data);
50 | try {
51 | return (T) OBJECT_MAPPER.readValue(json, clazz);
52 | } catch (Exception e) {
53 | throw new RuntimeException(e);
54 | }
55 | }
56 |
57 | }
58 |
--------------------------------------------------------------------------------
/rpc-netty-client-spring-boot-autoconfigure/src/main/java/com/github/linshenkx/rpcnettyclientspringbootautoconfigure/RpcClientAutoConfiguration.java:
--------------------------------------------------------------------------------
1 | package com.github.linshenkx.rpcnettyclientspringbootautoconfigure;
2 |
3 |
4 | import com.github.linshenkx.rpcnettyclientspringbootautoconfigure.processor.RpcClientBeanPostProcessor;
5 | import com.github.linshenkx.rpcnettyclientspringbootautoconfigure.client.RpcClient;
6 | import com.github.linshenkx.rpcnettyclientspringbootautoconfigure.discovery.zookeeper.ZKServiceDiscovery;
7 | import com.github.linshenkx.rpcnettyclientspringbootautoconfigure.properties.RpcClientProperties;
8 | import com.github.linshenkx.rpcnettycommon.properties.ZKProperties;
9 | import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
10 | import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
11 | import org.springframework.boot.context.properties.EnableConfigurationProperties;
12 | import org.springframework.context.annotation.Bean;
13 | import org.springframework.context.annotation.Configuration;
14 |
15 | /**
16 | * @version V1.0
17 | * @author: lin_shen
18 | * @date: 2018/11/2
19 | * @Description: TODO
20 | */
21 | @Configuration
22 | @EnableConfigurationProperties
23 | @ConditionalOnClass(RpcClient.class)
24 | public class RpcClientAutoConfiguration {
25 |
26 | @ConditionalOnMissingBean
27 | @Bean
28 | public RpcClientProperties defaultRpcServerProperties(){
29 | return new RpcClientProperties();
30 | }
31 |
32 | @ConditionalOnMissingBean
33 | @Bean
34 | public ZKProperties defaultZKProperties(){
35 | return new ZKProperties();
36 | }
37 |
38 | @ConditionalOnMissingBean
39 | @Bean
40 | public ZKServiceDiscovery zkServiceDiscovery(){
41 | return new ZKServiceDiscovery();
42 | }
43 |
44 | @Bean
45 | public RpcClient rpcClient(){
46 | return new RpcClient();
47 | }
48 |
49 | @Bean
50 | public RpcClientBeanPostProcessor rpcClientBeanPostProcessor(){
51 | return new RpcClientBeanPostProcessor();
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/rpc-netty-client-spring-boot-autoconfigure/src/main/java/com/github/linshenkx/rpcnettyclientspringbootautoconfigure/processor/RpcClientBeanPostProcessor.java:
--------------------------------------------------------------------------------
1 | package com.github.linshenkx.rpcnettyclientspringbootautoconfigure.processor;
2 |
3 | import com.github.linshenkx.rpcnettyclientspringbootautoconfigure.client.RpcClient;
4 | import com.github.linshenkx.rpcnettycommon.annotation.RpcReference;
5 | import lombok.extern.log4j.Log4j2;
6 | import org.springframework.beans.BeansException;
7 | import org.springframework.beans.factory.annotation.Autowired;
8 | import org.springframework.beans.factory.config.BeanPostProcessor;
9 | import org.springframework.stereotype.Component;
10 |
11 | import java.lang.reflect.Field;
12 |
13 | /**
14 | * @version V1.0
15 | * @author: lin_shen
16 | * @date: 18-12-1
17 | * @Description: 在 Bean 完成实例化后增加自己的处理逻辑
18 | */
19 | @Component
20 | @Log4j2
21 | public class RpcClientBeanPostProcessor implements BeanPostProcessor {
22 |
23 | @Autowired
24 | private RpcClient rpcClient;
25 |
26 | @Override
27 | public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
28 |
29 | processRpcReference(bean);
30 |
31 | return bean;
32 | }
33 |
34 | private void processRpcReference(Object bean) {
35 | Class beanClass = bean.getClass();
36 | do {
37 | Field[] fields = beanClass.getDeclaredFields();
38 | for (Field field : fields) {
39 | if(field.getAnnotation(RpcReference.class)!=null){
40 | field.setAccessible(true);
41 | try {
42 | field.set(bean, rpcClient.create(field.getType()));
43 | } catch (IllegalAccessException e) {
44 | log.error(e.getMessage());
45 | }
46 | }
47 | }
48 | } while ((beanClass = beanClass.getSuperclass()) != null);
49 | }
50 |
51 | @Override
52 | public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
53 | return bean;
54 | }
55 |
56 | }
57 |
--------------------------------------------------------------------------------
/rpc-netty-server-spring-boot-autoconfigure/src/main/java/com/github/linshenkx/rpcnettyserverspringbootautoconfigure/registry/zookeeper/ZKServiceRegistry.java:
--------------------------------------------------------------------------------
1 | package com.github.linshenkx.rpcnettyserverspringbootautoconfigure.registry.zookeeper;
2 |
3 |
4 | import com.github.linshenkx.rpcnettycommon.properties.ZKProperties;
5 | import lombok.extern.log4j.Log4j2;
6 | import org.I0Itec.zkclient.ZkClient;
7 | import org.springframework.beans.factory.annotation.Autowired;
8 | import org.springframework.boot.context.properties.EnableConfigurationProperties;
9 |
10 | import javax.annotation.PostConstruct;
11 |
12 | /**
13 | * @version V1.0
14 | * @author: lin_shen
15 | * @date: 2018/10/31
16 | * @Description: zookeeper服务注册中心
17 | */
18 | @Log4j2
19 | @EnableConfigurationProperties(ZKProperties.class)
20 | public class ZKServiceRegistry {
21 |
22 |
23 | @Autowired
24 | private ZKProperties zkProperties;
25 |
26 | private ZkClient zkClient;
27 |
28 | @PostConstruct
29 | public void init() {
30 | // 创建 ZooKeeper 客户端
31 | zkClient = new ZkClient(zkProperties.getAddress(), zkProperties.getSessionTimeOut(), zkProperties.getConnectTimeOut());
32 | log.info("connect to zookeeper");
33 | }
34 |
35 |
36 |
37 | /**
38 | * 为服务端提供注册
39 | * 将服务地址注册到对应服务名下
40 | * 断开连接后地址自动清除
41 | * @param serviceName
42 | * @param serviceInfo
43 | */
44 | public void register(String serviceName, String serviceInfo) {
45 | // 创建 registry 节点(持久)
46 | String registryPath = zkProperties.getRegistryPath();
47 | if (!zkClient.exists(registryPath)) {
48 | zkClient.createPersistent(registryPath);
49 | log.info("create registry node: {}", registryPath);
50 | }
51 | // 创建 service 节点(持久)
52 | String servicePath = registryPath + "/" + serviceName;
53 | if (!zkClient.exists(servicePath)) {
54 | zkClient.createPersistent(servicePath);
55 | log.info("create service node: {}", servicePath);
56 | }
57 | // 创建 address 节点(临时)
58 | String addressPath = servicePath + "/address-";
59 | String addressNode = zkClient.createEphemeralSequential(addressPath, serviceInfo);
60 | log.info("create address node: {}", addressNode);
61 | }
62 |
63 |
64 |
65 | }
--------------------------------------------------------------------------------
/rpc-netty-common/src/main/java/com/github/linshenkx/rpcnettycommon/serialization/serializer/impl/ProtoStuffSerializer.java:
--------------------------------------------------------------------------------
1 | package com.github.linshenkx.rpcnettycommon.serialization.serializer.impl;
2 |
3 | import com.github.linshenkx.rpcnettycommon.serialization.serializer.ISerializer;
4 | import io.protostuff.LinkedBuffer;
5 | import io.protostuff.ProtostuffIOUtil;
6 | import io.protostuff.Schema;
7 | import io.protostuff.runtime.RuntimeSchema;
8 | import org.objenesis.Objenesis;
9 | import org.objenesis.ObjenesisStd;
10 |
11 | import java.util.Map;
12 | import java.util.concurrent.ConcurrentHashMap;
13 |
14 | /**
15 | * @version V1.0
16 | * @author: lin_shen
17 | * @date: 2018/11/18
18 | * @Description: protocolbuffer序列化工具(基于protostuff)
19 | */
20 | public class ProtoStuffSerializer implements ISerializer {
21 |
22 | /**
23 | * 用于缓存类对象与Schema的对应关系,避免重复创建Schema
24 | */
25 | private static final Map, Schema>> CACHED_SCHEMA = new ConcurrentHashMap<>();
26 |
27 | /**
28 | * 用于高效便捷地生成类实例,而无需构造方法支持
29 | */
30 | private static final Objenesis OBJENESIS = new ObjenesisStd(true);
31 |
32 | /**
33 | * 序列化(对象 -> 字节数组)
34 | */
35 | @Override
36 | @SuppressWarnings("unchecked")
37 | public byte[] serialize(T obj) {
38 | Class cls = (Class) obj.getClass();
39 | LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
40 | try {
41 | Schema schema = getSchema(cls);
42 | return ProtostuffIOUtil.toByteArray(obj, schema, buffer);
43 | } catch (Exception e) {
44 | throw new IllegalStateException(e.getMessage(), e);
45 | } finally {
46 | buffer.clear();
47 | }
48 | }
49 |
50 | /**
51 | * 反序列化(字节数组 -> 对象)
52 | */
53 | @Override
54 | public T deserialize(byte[] data, Class cls) {
55 | try {
56 | T message = OBJENESIS.newInstance(cls);
57 | Schema schema = getSchema(cls);
58 | ProtostuffIOUtil.mergeFrom(data, message, schema);
59 | return message;
60 | } catch (Exception e) {
61 | throw new IllegalStateException(e.getMessage(), e);
62 | }
63 | }
64 |
65 | @SuppressWarnings("unchecked")
66 | private Schema getSchema(Class cls) {
67 | Schema schema = (Schema) CACHED_SCHEMA.get(cls);
68 | if (schema == null) {
69 | schema = RuntimeSchema.createFrom(cls);
70 | CACHED_SCHEMA.put(cls, schema);
71 | }
72 | return schema;
73 | }
74 | }
75 |
--------------------------------------------------------------------------------
/rpc-netty-common/src/main/java/com/github/linshenkx/rpcnettycommon/protocal/xuan/RemotingTransporter.java:
--------------------------------------------------------------------------------
1 | package com.github.linshenkx.rpcnettycommon.protocal.xuan;
2 |
3 | import com.github.linshenkx.rpcnettycommon.bean.BodyContent;
4 | import lombok.*;
5 |
6 | import java.util.concurrent.atomic.AtomicLong;
7 |
8 | /**
9 | * @version V1.0
10 | * @author: lin_shen
11 | * @date: 18-11-12
12 | * @Description: 自定义远程传输实体 (magic+flag+invokeId+bodyLength+bodyContent)
13 | */
14 | @Data
15 | @Builder
16 | @AllArgsConstructor
17 | @NoArgsConstructor
18 | public class RemotingTransporter {
19 |
20 | /**
21 | * 魔数
22 | */
23 | public static final short MAGIC=(short)0x9826;
24 |
25 | /**
26 | * 用原子递增的方式来获取不重复invokeId
27 | */
28 | private static final AtomicLong invokeIdGnerator=new AtomicLong(0L);
29 |
30 |
31 | /**
32 | * 标志位, 一共8个地址位。
33 | * 低四位用来表示消息体数据用的序列化工具的类型
34 | * 高四位中,第一位为1表示是request请求,为0表示是reponse应答
35 | * TODO:第二位为1表示双向传输(即有返回response)
36 | * TODO:第三位为1表示是心跳ping事件
37 | * TODO:预留位
38 | */
39 | private Flag flag;
40 |
41 | @Getter
42 | @ToString
43 | public static class Flag{
44 | private boolean isRequest;
45 | private boolean isTwoway;
46 | private boolean isPing;
47 | private boolean isOther;
48 |
49 | private int serializeType;
50 |
51 | private byte thisByte;
52 |
53 |
54 | public Flag(boolean isRequest, boolean isTwoway, boolean isPing, boolean isOther, int serializeType) {
55 |
56 | if(serializeType<0||serializeType>15){
57 | throw new IllegalArgumentException("serializeType 对应整数应该在 0 到 15 之间");
58 | }
59 |
60 | this.isRequest = isRequest;
61 | this.isTwoway = isTwoway;
62 | this.isPing = isPing;
63 | this.isOther = isOther;
64 | this.serializeType = serializeType;
65 |
66 | int byteTem= (isRequest?1:0)<<7;
67 | byteTem=byteTem | ((isTwoway?1:0)<<6);
68 | byteTem=byteTem | ((isPing?1:0)<<5);
69 | byteTem=byteTem | ((isOther?1:0)<<4);
70 | byteTem=byteTem | serializeType;
71 |
72 | this.thisByte= (byte) byteTem;
73 | }
74 |
75 | public Flag(byte thisByte){
76 | this.thisByte=thisByte;
77 |
78 | isRequest=((thisByte>>>7)&1)==1;
79 | isTwoway=((thisByte>>>6)&1)==1;
80 | isPing=((thisByte>>>5)&1)==1;
81 | isOther=((thisByte>>>4)&1)==1;
82 |
83 | serializeType=thisByte & 15;
84 |
85 | }
86 |
87 | }
88 |
89 |
90 | /**
91 | * 每一个请求的唯一识别id(由于采用异步通讯的方式,用来把请求request和返回的response对应上)
92 | */
93 | private long invokeId=invokeIdGnerator.getAndIncrement();
94 |
95 | /**
96 | * 消息体字节数组长度
97 | */
98 | private int bodyLength;
99 |
100 | /**
101 | * 消息体内容(还需要编码序列化成字节数组)
102 | */
103 | private transient BodyContent bodyContent;
104 |
105 |
106 | }
107 |
--------------------------------------------------------------------------------
/examples/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | com.github.linshenkx.test
7 | rpc-netty-spring-boot-starter-examples
8 | 2.0.2.RELEASE
9 | pom
10 |
11 |
12 | org.springframework.boot
13 | spring-boot-starter-parent
14 | 2.0.5.RELEASE
15 |
16 |
17 |
18 | UTF-8
19 | UTF-8
20 | 1.8
21 | Finchley.SR2
22 | ${project.parent.version}
23 | 2.0.2.RELEASE
24 |
25 |
26 |
27 | rpc-lib
28 | rpc-provider
29 | rpc-consumer
30 |
31 |
32 |
33 |
34 |
35 | org.springframework.cloud
36 | spring-cloud-dependencies
37 | ${spring-cloud.version}
38 | pom
39 | import
40 |
41 |
42 |
43 | com.github.linshenkx.test
44 | rpc-lib
45 | ${project.version}
46 |
47 |
48 |
49 | com.github.linshenkx
50 | rpc-netty-client-spring-boot-starter
51 | ${rpc-netty-linshen.version}
52 |
53 |
54 | com.github.linshenkx
55 | rpc-netty-server-spring-boot-starter
56 | ${rpc-netty-linshen.version}
57 |
58 |
59 |
60 |
61 |
62 |
63 | sonatype-repository
64 | sonatype-repository
65 | https://oss.sonatype.org/content/groups/staging
66 |
67 | true
68 |
69 |
70 | true
71 |
72 |
73 |
74 |
75 |
76 |
--------------------------------------------------------------------------------
/rpc-netty-client-spring-boot-autoconfigure/src/main/java/com/github/linshenkx/rpcnettyclientspringbootautoconfigure/discovery/zookeeper/ZKServiceDiscovery.java:
--------------------------------------------------------------------------------
1 | package com.github.linshenkx.rpcnettyclientspringbootautoconfigure.discovery.zookeeper;
2 |
3 |
4 | import com.github.linshenkx.rpcnettycommon.properties.ZKProperties;
5 | import lombok.extern.log4j.Log4j2;
6 | import org.I0Itec.zkclient.IZkChildListener;
7 | import org.I0Itec.zkclient.ZkClient;
8 | import org.springframework.beans.factory.annotation.Autowired;
9 | import org.springframework.boot.context.properties.EnableConfigurationProperties;
10 | import org.springframework.stereotype.Component;
11 | import org.springframework.util.CollectionUtils;
12 |
13 | import javax.annotation.PostConstruct;
14 | import java.util.ArrayList;
15 | import java.util.List;
16 | import java.util.concurrent.ConcurrentHashMap;
17 | import java.util.concurrent.ConcurrentMap;
18 |
19 | /**
20 | * @version V1.0
21 | * @author: lin_shen
22 | * @date: 2018/10/31
23 | * @Description: zookeeper服务注册中心
24 | */
25 | @Component
26 | @Log4j2
27 | @EnableConfigurationProperties(ZKProperties.class)
28 | public class ZKServiceDiscovery {
29 |
30 | @Autowired
31 | private ZKProperties zkProperties;
32 |
33 | /**
34 | * 服务名和服务地址列表的Map
35 | */
36 | private ConcurrentMap> servicePathsMap=new ConcurrentHashMap<>();
37 |
38 | /**
39 | * 服务监听器 Map,监听子节点服务信息
40 | */
41 | private ConcurrentMap zkChildListenerMap=new ConcurrentHashMap<>();
42 |
43 | private ZkClient zkClient;
44 |
45 | @PostConstruct
46 | public void init() {
47 | // 创建 ZooKeeper 客户端
48 | zkClient = new ZkClient(zkProperties.getAddress(), zkProperties.getSessionTimeOut(), zkProperties.getConnectTimeOut());
49 | log.info("connect to zookeeper");
50 | }
51 |
52 | /**
53 | *
54 | * 根据服务名获取服务地址并保持监控
55 | * @param serviceName
56 | * @return
57 | */
58 | public void discover(String serviceName){
59 | log.info("discovering:"+serviceName);
60 | String servicePath=zkProperties.getRegistryPath()+"/"+serviceName;
61 | //找不到对应服务
62 | if(!zkClient.exists(servicePath)){
63 | throw new RuntimeException("can not find any service node on path: "+servicePath);
64 | }
65 | //获取服务地址列表
66 | List addressList=zkClient.getChildren(servicePath);
67 | if(CollectionUtils.isEmpty(addressList)){
68 | throw new RuntimeException("can not find any address node on path: "+servicePath);
69 | }
70 | //保存地址列表
71 | List paths=new ArrayList<>(addressList.size());
72 | for(String address:addressList){
73 | paths.add(zkClient.readData(servicePath+"/"+address));
74 | }
75 | servicePathsMap.put(serviceName,paths);
76 | //保持监控
77 | if(!zkChildListenerMap.containsKey(serviceName)){
78 | IZkChildListener iZkChildListener= (parentPath, currentChilds) -> {
79 | //当子节点列表变化时重新discover
80 | discover(serviceName);
81 | log.info("子节点列表发生变化 ");
82 | };
83 | zkClient.subscribeChildChanges(servicePath, iZkChildListener);
84 | zkChildListenerMap.put(serviceName,iZkChildListener);
85 | }
86 | }
87 |
88 | public List getAddressList(String serviceName){
89 | List addressList=servicePathsMap.get(serviceName);
90 | if(addressList==null||addressList.isEmpty()){
91 | discover(serviceName);
92 | return servicePathsMap.get(serviceName);
93 | }
94 | return addressList;
95 | }
96 |
97 | }
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # 基于Netty的简易RPC框架
2 | 一个基于Netty,Zookeeper和SpringBoot的RPC框架
3 |
4 | 作者CSDN主页:[鲸临于空](https://blog.csdn.net/alinyua)
5 |
6 | ### 特性:
7 | * 基于Spring Boot 2的自动发现,添加Starter依赖即可快速集成,开箱即用
8 | * 基于ZooKeeper的服务发现,支持ZooKeeper集群
9 | * 基于Netty的底层通信
10 |
11 | ### 版本:2.0
12 |
13 | ### 版本说明:
14 | 1.0版本实现了原型功能,达到初步可用状态,但性能较差,仅作学习交流用
15 |
16 | 2.0版本针对性能做了优化,并添加一些新功能:
17 |
18 | * 增加@RpcReference注解,自动注入服务实现
19 | * 增加负载均衡路由策略引擎(含随机、轮询、哈希等及其带权形式)
20 | * 增加序列化引擎(支持 JDK默认、Hessian、Json、Protostuff、Xml、Avro、ProtocolBuffer、Thrift等序列化方式)
21 | * 服务提供者提供服务时可注解参数指定最大工作线程数来限流
22 | * 服务消费者对服务地址列表进行缓存,并监听变化
23 | * 传输协议修改,使用消息头+消息体的模式以支持新特性并避免粘包半包问题和留下扩展空间
24 |
25 | 后续将对核心进行改造,使其支持异步模型
26 |
27 | ### 设计:
28 | 
29 | ### 快速启动
30 |
31 | 以下例子可参考:[examples](https://github.com/linshenkx/rpc-netty-spring-boot-starter/tree/master/examples)
32 |
33 | 1. 定义公共接口:
34 |
35 | public interface HelloService {
36 | String hello(String name);
37 | }
38 |
39 | 2. 添加对应依赖(注意更新到最新版本)
40 | - 服务提供者:
41 | ```xml
42 |
43 | com.github.linshenkx
44 | rpc-netty-server-spring-boot-starter
45 | 2.0.2.RELEASE
46 |
47 | ```
48 |
49 | - 服务消费者:
50 | ```xml
51 |
52 | com.github.linshenkx
53 | rpc-netty-client-spring-boot-starter
54 | 2.0.2.RELEASE
55 |
56 | ```
57 |
58 | 3. 在Spring配置文件里配置zookeeper地址列表和rpc端口,如下例,
59 |
60 | 其中connectTimeOut和sessionTimeOut都有默认值,应根据网络环境配置修改
61 |
62 | 服务提供者和服务消费者应使用相同 registryPath,一般无需配置,使用默认值即可(如果有多个不同系统则可修改,达到隔离目的)
63 |
64 | 1. 服务提供者 application 文件
65 |
66 | ```yml
67 | zk:
68 | address: 127.0.0.1:2181,127.0.0.1:2182,127.0.0.1:2183
69 | connectTimeOut: 10000
70 | sessionTimeOut: 10000
71 | registryPath: "/defaultRegistry"
72 | rpc:
73 | server:
74 | port: 9991
75 | ```
76 | 2. 服务消费者 application 文件
77 |
78 | ```yml
79 | server:
80 | port: 9090
81 | zk:
82 | address: 127.0.0.1:2181,127.0.0.1:2182,127.0.0.1:2183
83 | connectTimeOut: 20000
84 | sessionTimeOut: 10000
85 | registryPath: "/defaultRegistry"
86 | rpc:
87 | client:
88 | routeStrategy: Polling
89 | serializeType: ProtoStuff
90 | ```
91 | 4. 服务提供方使用@RpcService标注接口实现 :
92 | 其中weight代表权重,默认为1。workerThreads代表工作线程数,可用于限流,默认为10.
93 | ```java
94 | @RpcService(value = HelloService.class,weight = 2,workerThreads = 3)
95 | public class HelloServiceImpl implements HelloService {
96 |
97 | @Override
98 | public String say(String name) {
99 | return "hello " + name;
100 | }
101 |
102 | }
103 | ```
104 |
105 | 5. 服务消费者使用@RpcReference标记服务接口,即可注入服务实现类代理
106 |
107 | ```java
108 | @RestController
109 | public class HelloController {
110 |
111 | @RpcReference
112 | private HelloService helloService;
113 |
114 | @GetMapping("/hello")
115 | public String sayHello(@RequestParam(defaultValue = "lin") String name){
116 | return helloService.say(name);
117 | }
118 |
119 | }
120 | ```
121 |
122 |
--------------------------------------------------------------------------------
/rpc-netty-common/src/main/java/com/github/linshenkx/rpcnettycommon/handler/RpcServerHandler.java:
--------------------------------------------------------------------------------
1 | package com.github.linshenkx.rpcnettycommon.handler;
2 |
3 |
4 | import com.github.linshenkx.rpcnettycommon.bean.RpcRequest;
5 | import com.github.linshenkx.rpcnettycommon.bean.RpcResponse;
6 | import com.github.linshenkx.rpcnettycommon.protocal.xuan.RemotingTransporter;
7 | import io.netty.channel.ChannelFutureListener;
8 | import io.netty.channel.ChannelHandlerContext;
9 | import io.netty.channel.SimpleChannelInboundHandler;
10 | import lombok.extern.log4j.Log4j2;
11 |
12 | import java.lang.reflect.Method;
13 | import java.util.Map;
14 | import java.util.concurrent.Semaphore;
15 |
16 | /**
17 | * @version V1.0
18 | * @author: lin_shen
19 | * @date: 2018/10/31
20 | * @Description: RPC服务端处理器(处理RpcRequest)
21 | */
22 | @Log4j2
23 | public class RpcServerHandler extends SimpleChannelInboundHandler {
24 |
25 | /**
26 | * 存放 服务名称 与 服务实例 之间的映射关系
27 | */
28 | private final Map handlerMap;
29 |
30 | /**
31 | * 存放 服务名称 与 信号量 之间的映射关系
32 | * 用于限制每个服务的工作线程数
33 | */
34 | private final Map serviceSemaphoreMap;
35 |
36 | public RpcServerHandler(Map handlerMap,Map serviceSemaphoreMap) {
37 | this.handlerMap = handlerMap;
38 | this.serviceSemaphoreMap=serviceSemaphoreMap;
39 | }
40 |
41 | @Override
42 | protected void channelRead0(ChannelHandlerContext channelHandlerContext, RemotingTransporter remotingTransporter) throws Exception {
43 | log.info("channelRead0 begin");
44 | remotingTransporter.setFlag(new RemotingTransporter.Flag(false,true,false,false,remotingTransporter.getFlag().getSerializeType()));
45 | RpcResponse rpcResponse=new RpcResponse();
46 | RpcRequest rpcRequest=(RpcRequest)remotingTransporter.getBodyContent();
47 | Semaphore semaphore = serviceSemaphoreMap.get(rpcRequest.getInterfaceName());
48 | boolean acquire=false;
49 | try {
50 | // 处理 RPC 请求成功
51 | log.info("进入限流");
52 | acquire=semaphore.tryAcquire();
53 | if(acquire){
54 | Object result= handle(rpcRequest);
55 | rpcResponse.setResult(result);
56 | }
57 |
58 | } catch (Exception e) {
59 | // 处理 RPC 请求失败
60 | rpcResponse.setException(e);
61 | log.error("handle result failure", e);
62 | } finally {
63 | if(acquire){
64 | semaphore.release();
65 | log.info("释放信号量");
66 | }
67 | }
68 | remotingTransporter.setBodyContent(rpcResponse);
69 | channelHandlerContext.writeAndFlush(remotingTransporter).addListener(ChannelFutureListener.CLOSE);
70 | }
71 |
72 |
73 | @Override
74 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
75 | log.error("server caught exception", cause);
76 | ctx.close();
77 | }
78 |
79 | private Object handle(RpcRequest request) throws Exception {
80 | log.info("开始执行handle");
81 | // 获取服务实例
82 | String serviceName = request.getInterfaceName();
83 | Object serviceBean = handlerMap.get(serviceName);
84 | if (serviceBean == null) {
85 | throw new RuntimeException(String.format("can not find service bean by key: %s", serviceName));
86 | }
87 | // 获取反射调用所需的变量
88 | Class> serviceClass = serviceBean.getClass();
89 | String methodName = request.getMethodName();
90 | log.info(methodName);
91 | Class>[] parameterTypes = request.getParameterTypes();
92 | log.info(parameterTypes[0].getName());
93 | Object[] parameters = request.getParameters();
94 | // 执行反射调用
95 | Method method = serviceClass.getMethod(methodName, parameterTypes);
96 | method.setAccessible(true);
97 | return method.invoke(serviceBean, parameters);
98 | }
99 |
100 |
101 | }
102 |
--------------------------------------------------------------------------------
/rpc-netty-common/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | rpc-netty-common
7 |
8 |
9 | com.github.linshenkx
10 | rpc-netty-spring-boot-starter
11 | 2.0.2.RELEASE
12 | ../
13 |
14 |
15 |
16 |
17 | org.springframework.boot
18 | spring-boot-starter
19 |
20 |
21 | org.springframework.boot
22 | spring-boot-configuration-processor
23 |
24 |
25 | org.projectlombok
26 | lombok
27 | true
28 |
29 |
30 | io.netty
31 | netty-all
32 |
33 |
34 | com.101tec
35 | zkclient
36 |
37 |
38 | com.alibaba
39 | fastjson
40 |
41 |
42 | io.protostuff
43 | protostuff-core
44 |
45 |
46 | io.protostuff
47 | protostuff-runtime
48 |
49 |
50 | org.objenesis
51 | objenesis
52 |
53 |
54 | org.slf4j
55 | slf4j-api
56 |
57 |
58 | com.fasterxml.jackson.core
59 | jackson-core
60 |
61 |
62 | com.fasterxml.jackson.core
63 | jackson-databind
64 |
65 |
66 | org.apache.commons
67 | commons-lang3
68 |
69 |
70 | joda-time
71 | joda-time
72 |
73 |
74 | org.apache.avro
75 | avro
76 |
77 |
78 | com.caucho
79 | hessian
80 |
81 |
82 | org.jboss.marshalling
83 | jboss-marshalling
84 |
85 |
86 | io.protostuff
87 | protostuff-api
88 |
89 |
90 | org.apache.thrift
91 | libthrift
92 |
93 |
94 | com.thoughtworks.xstream
95 | xstream
96 |
97 |
98 |
99 |
100 |
101 |
102 |
--------------------------------------------------------------------------------
/rpc-netty-common/src/main/java/com/github/linshenkx/rpcnettycommon/codec/decode/RemotingTransporterDecoder.java:
--------------------------------------------------------------------------------
1 | package com.github.linshenkx.rpcnettycommon.codec.decode;
2 |
3 | import com.github.linshenkx.rpcnettycommon.bean.BodyContent;
4 | import com.github.linshenkx.rpcnettycommon.bean.RpcRequest;
5 | import com.github.linshenkx.rpcnettycommon.bean.RpcResponse;
6 | import com.github.linshenkx.rpcnettycommon.exception.remoting.RemotingContextException;
7 | import com.github.linshenkx.rpcnettycommon.protocal.xuan.RemotingTransporter;
8 | import com.github.linshenkx.rpcnettycommon.serialization.SerializeTypeEnum;
9 | import com.github.linshenkx.rpcnettycommon.serialization.SerializerEngine;
10 | import io.netty.buffer.ByteBuf;
11 | import io.netty.channel.ChannelHandlerContext;
12 | import io.netty.handler.codec.ReplayingDecoder;
13 | import lombok.extern.log4j.Log4j2;
14 |
15 | import java.util.List;
16 |
17 | /**
18 | * @version V1.0
19 | * @author: lin_shen
20 | * @date: 18-11-12
21 | * @Description: TODO
22 | */
23 | @Log4j2
24 | public class RemotingTransporterDecoder extends ReplayingDecoder {
25 |
26 | private static final int MAX_BODY_SIZE = 1024 * 1024 * 5;
27 |
28 | /**
29 | * 用于暂存解码RemotingTransporter信息,一个就够了
30 | */
31 | private static RemotingTransporter remotingTransporter=RemotingTransporter.builder().build();
32 |
33 | /**
34 | * 用于ReplayingDecoder的状态管理
35 | */
36 | enum State {
37 | HEADER_MAGIC, HEADER_FLAG, HEADER_INVOKE_ID, HEADER_BODY_LENGTH, BODY
38 | }
39 |
40 | public RemotingTransporterDecoder( ){
41 | //设置 state() 的初始值,以便进入switch
42 | super(State.HEADER_MAGIC);
43 | }
44 |
45 | @Override
46 | protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List