├── .gitignore ├── README.md ├── dubbo-api ├── .gitignore ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── hks │ │ │ └── dubboapi │ │ │ ├── DubboApiApplication.java │ │ │ └── service │ │ │ └── GreetingService.java │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── com │ └── hks │ └── dubboapi │ └── DubboApiApplicationTests.java ├── dubbo-consumer ├── .gitignore ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── hks │ │ │ └── dubboconsumer │ │ │ └── DubboConsumerApplication.java │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── com │ └── hks │ └── dubboconsumer │ └── DubboConsumerApplicationTests.java ├── dubbo-provider ├── .gitignore ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── hks │ │ │ └── dubboprovider │ │ │ ├── DubboProviderApplication.java │ │ │ └── service │ │ │ └── GreetingServiceImpl.java │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── com │ └── hks │ └── dubboprovider │ └── DubboProviderApplicationTests.java ├── google-protocol-buffer ├── .gitignore ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── hks │ │ │ └── googleprotocolbuffer │ │ │ └── GoogleProtocolBufferApplication.java │ ├── proto │ │ ├── date_time.proto │ │ └── person.proto │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── com │ └── hks │ └── googleprotocolbuffer │ └── GoogleProtocolBufferApplicationTests.java ├── google-snappy ├── .gitignore ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── hks │ │ │ └── googlesnappy │ │ │ ├── DemoTest.java │ │ │ └── GoogleSnappyApplication.java │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── com │ └── hks │ └── googlesnappy │ └── GoogleSnappyApplicationTests.java ├── grpc-api ├── .gitignore ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── hks │ │ │ └── grpc │ │ │ ├── GrpcApplication.java │ │ │ ├── bean │ │ │ ├── HelloRequestStuff.java │ │ │ └── Hellorequest.java │ │ │ ├── service │ │ │ ├── AddressBookProtos.java │ │ │ ├── GreeterGrpc.java │ │ │ ├── HelloProto.java │ │ │ └── HelloRequestJava.java │ │ │ └── util │ │ │ └── ProtoBufUtil.java │ └── resources │ │ ├── application.properties │ │ └── proto │ │ ├── addressbook.proto │ │ └── hello.proto │ └── test │ └── java │ └── com │ └── hks │ └── grpc │ └── GrpcApplicationTests.java ├── grpc-consumer ├── .gitignore ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── hks │ │ │ └── grpc │ │ │ ├── GrpcApplication.java │ │ │ └── client │ │ │ └── HelloClient.java │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── com │ └── hks │ └── grpc │ └── GrpcApplicationTests.java ├── grpc-provider ├── .gitignore ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── hks │ │ │ └── grpc │ │ │ ├── GrpcApplication.java │ │ │ └── server │ │ │ └── HelloServer.java │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── com │ └── hks │ └── grpc │ └── GrpcApplicationTests.java ├── grpc-stream-client ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── hks │ │ └── rpc │ │ ├── client │ │ ├── AdditionClient.java │ │ └── CallBack.java │ │ └── server │ │ ├── AdditionServer.java │ │ └── AdditionServiceImplBaseImpl.java │ └── proto │ └── additionService.proto ├── grpc-stream-double ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── hks │ │ └── rpc │ │ ├── client │ │ └── CalculatorClient.java │ │ └── server │ │ ├── CalculateServiceImpl.java │ │ └── CalculatorServer.java │ └── proto │ └── calculateService.proto ├── grpc-stream-server ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── hks │ │ └── rpc │ │ ├── client │ │ └── NameClient.java │ │ └── server │ │ ├── NameServer.java │ │ └── NameServersImplBaseImpl.java │ └── proto │ └── nameServers.proto ├── log └── TestWeb.log.2018-07-04.log ├── pom.xml ├── spring-dubbo-api ├── .gitignore ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── hks │ │ │ └── springdubboapi │ │ │ ├── SpringDubboApiApplication.java │ │ │ └── service │ │ │ └── HelloWorldService.java │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── com │ └── hks │ └── springdubboapi │ └── SpringDubboApiApplicationTests.java ├── spring-dubbo-consumer ├── .gitignore ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── hks │ │ │ └── springdubboconsumer │ │ │ ├── SpringDubboConsumerApplication.java │ │ │ ├── config │ │ │ └── PropertiesConfig.java │ │ │ ├── controller │ │ │ └── HelloWoldConsumerController.java │ │ │ └── service │ │ │ └── ConsumerDemoService.java │ └── resources │ │ ├── application.properties │ │ ├── dubbo.properties │ │ ├── dubbo │ │ ├── dubbo-consumer.xml │ │ └── dubbo.xml │ │ └── log4j.properties │ └── test │ └── java │ └── com │ └── hks │ └── springdubboconsumer │ └── SpringDubboConsumerApplicationTests.java ├── spring-dubbo-provider ├── .gitignore ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── hks │ │ │ └── springdubboprovider │ │ │ ├── SpringDubboProviderApplication.java │ │ │ ├── config │ │ │ └── PropertiesConfig.java │ │ │ └── service │ │ │ └── HelloWorldServiceImpl.java │ └── resources │ │ ├── application.properties │ │ ├── dubbo.properties │ │ ├── dubbo │ │ ├── dubbo-provider.xml │ │ └── dubbo.xml │ │ └── log4j.properties │ └── test │ └── java │ └── com │ └── hks │ └── springdubboprovider │ └── SpringDubboProviderApplicationTests.java ├── spring-grpc-common ├── pom.xml └── src │ └── main │ └── resources │ └── META-INF │ └── spring.factories ├── spring-thrift-api ├── .gitignore ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── hks │ │ │ └── springthriftapi │ │ │ ├── SpringThriftApiApplication.java │ │ │ └── service │ │ │ └── HelloWorldService.java │ ├── resources │ │ └── application.properties │ └── thrift │ │ └── User.thrift │ └── test │ └── java │ └── com │ └── hks │ └── springthriftapi │ └── SpringThriftApiApplicationTests.java ├── spring-thrift-client ├── .gitignore ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── hks │ │ │ └── springthriftclient │ │ │ ├── SpringThriftClientApplication.java │ │ │ ├── config │ │ │ └── ThriftClientConfig.java │ │ │ ├── controller │ │ │ └── HelloWordController.java │ │ │ └── util │ │ │ └── ApplicationContextUtil.java │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── com │ └── hks │ └── springthriftclient │ └── SpringThriftClientApplicationTests.java ├── spring-thrift-common ├── .gitignore ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── hks │ │ │ └── springthriftcommon │ │ │ ├── SpringThriftCommonApplication.java │ │ │ ├── exception │ │ │ └── ThriftException.java │ │ │ ├── thrift │ │ │ ├── PoolOperationCallBack.java │ │ │ ├── ThriftClientPoolFactory.java │ │ │ ├── ThriftServiceClient2Proxy.java │ │ │ ├── ThriftServiceClientProxy.java │ │ │ ├── ThriftServiceClientProxyFactory.java │ │ │ ├── ThriftServiceServerFactory.java │ │ │ └── impl │ │ │ │ └── PoolOperationCallBackImpl.java │ │ │ └── zookeeper │ │ │ ├── ThriftServerAddressProvider.java │ │ │ ├── ThriftServerAddressRegister.java │ │ │ ├── ThriftServerIpResolve.java │ │ │ ├── ZookeeperFactory.java │ │ │ └── impl │ │ │ ├── ThriftServerAddressProviderZookeeper.java │ │ │ ├── ThriftServerAddressRegisterZookeeper.java │ │ │ └── ThriftServerIpLocalNetworkResolve.java │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── com │ └── hks │ └── springthriftcommon │ └── SpringThriftCommonApplicationTests.java ├── spring-thrift-server ├── .gitignore ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── hks │ │ │ └── springthriftserver │ │ │ ├── SpringThriftServerApplication.java │ │ │ ├── config │ │ │ └── ThriftServerConfig.java │ │ │ └── serviceImpl │ │ │ └── HelloWorldServiceImpl.java │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── com │ └── hks │ └── springthriftserver │ └── SpringThriftServerApplicationTests.java ├── spring-zookeeper-invoker ├── .gitignore ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── hks │ │ │ └── springzookeeperweb │ │ │ ├── SpringZookeeperWebApplication.java │ │ │ ├── consumer │ │ │ ├── ServiceHelp.java │ │ │ └── impl │ │ │ │ └── ServiceHelpImpl.java │ │ │ └── controller │ │ │ └── ZookeeperRead.java │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── com │ └── hks │ └── springzookeeperweb │ └── SpringZookeeperWebApplicationTests.java ├── spring-zookeeper-register ├── .gitignore ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── hks │ │ │ └── springzookeeper │ │ │ ├── SpringZookeeperApplication.java │ │ │ ├── config │ │ │ ├── RegistryConfig.java │ │ │ └── WebListener.java │ │ │ ├── controller │ │ │ ├── DemoTest.java │ │ │ └── RestBizController.java │ │ │ └── register │ │ │ ├── ServiceRegistry.java │ │ │ └── impl │ │ │ └── ServiceRegistryImpl.java │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── com │ └── hks │ └── springzookeeper │ ├── SpringZookeeperApplicationTests.java │ ├── distributeLock │ └── RecipesLock.java │ └── leaderSelector │ └── Test.java ├── thrift-api ├── .gitignore ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── hks │ │ │ └── thriftapi │ │ │ ├── ThriftApiApplication.java │ │ │ └── service │ │ │ └── Hello.java │ ├── resources │ │ └── application.properties │ └── thrift │ │ ├── Hello.thrift │ │ └── gen-java │ │ └── com │ │ └── hks │ │ └── thriftapi │ │ └── service │ │ └── Hello.java │ └── test │ └── java │ └── com │ └── hks │ └── thriftapi │ └── ThriftApiApplicationTests.java ├── thrift-client ├── .gitignore ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── hks │ │ │ └── thriftclient │ │ │ └── ThriftClientApplication.java │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── com │ └── hks │ └── thriftclient │ └── ThriftClientApplicationTests.java └── thrift-server ├── .gitignore ├── pom.xml └── src ├── main ├── java │ └── com │ │ └── hks │ │ └── thriftserver │ │ ├── ThriftServerApplication.java │ │ └── service │ │ └── HelloServiceImpl.java └── resources │ └── application.properties └── test └── java └── com └── hks └── thriftserver └── ThriftServerApplicationTests.java /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | .sts4-cache 12 | 13 | ### IntelliJ IDEA ### 14 | .idea 15 | *.iws 16 | *.iml 17 | *.ipr 18 | *.log-* 19 | 20 | ### NetBeans ### 21 | /nbproject/private/ 22 | /build/ 23 | /nbbuild/ 24 | /dist/ 25 | /nbdist/ 26 | /.nb-gradle/ 27 | /logs 28 | /log 29 | /data -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Java-RPC系列生态 2 | 干净的springboot-dubbo 3 | 4 | 干净的springboot-thrift 5 | 6 | 干净的google-protocol-buffer 7 | 8 | 关于原理的讲解:https://blog.csdn.net/singgel/article/category/8277371 9 | 10 | grpc过程:https://segmentfault.com/a/1190000015042409 11 | 12 | -------------------------------------------------------------------------------- /dubbo-api/.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | .sts4-cache 12 | 13 | ### IntelliJ IDEA ### 14 | .idea 15 | *.iws 16 | *.iml 17 | *.ipr 18 | 19 | ### NetBeans ### 20 | /nbproject/private/ 21 | /build/ 22 | /nbbuild/ 23 | /dist/ 24 | /nbdist/ 25 | /.nb-gradle/ -------------------------------------------------------------------------------- /dubbo-api/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.hks 7 | dubbo-api 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | dubbo-api 12 | dubbo-api project for Spring Boot 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 2.1.0.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 1.8 25 | 26 | 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter 31 | 32 | 33 | 34 | com.alibaba 35 | dubbo 36 | 2.6.4 37 | 38 | 39 | 40 | org.springframework.boot 41 | spring-boot-starter-test 42 | test 43 | 44 | 45 | 46 | 47 | 48 | 49 | org.springframework.boot 50 | spring-boot-maven-plugin 51 | 52 | 53 | 54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /dubbo-api/src/main/java/com/hks/dubboapi/DubboApiApplication.java: -------------------------------------------------------------------------------- 1 | package com.hks.dubboapi; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class DubboApiApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(DubboApiApplication.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /dubbo-api/src/main/java/com/hks/dubboapi/service/GreetingService.java: -------------------------------------------------------------------------------- 1 | package com.hks.dubboapi.service; 2 | 3 | /** 4 | * @Author: hekuangsheng 5 | * @Date: 2018/11/13 6 | */ 7 | public interface GreetingService { 8 | String sayHello(String name); 9 | } -------------------------------------------------------------------------------- /dubbo-api/src/main/resources/application.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/singgel/RPC-SkillTree/67bfbc076b18bca17850c64fd2a935fdcd88d9ee/dubbo-api/src/main/resources/application.properties -------------------------------------------------------------------------------- /dubbo-api/src/test/java/com/hks/dubboapi/DubboApiApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.hks.dubboapi; 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 DubboApiApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /dubbo-consumer/.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | .sts4-cache 12 | 13 | ### IntelliJ IDEA ### 14 | .idea 15 | *.iws 16 | *.iml 17 | *.ipr 18 | 19 | ### NetBeans ### 20 | /nbproject/private/ 21 | /build/ 22 | /nbbuild/ 23 | /dist/ 24 | /nbdist/ 25 | /.nb-gradle/ -------------------------------------------------------------------------------- /dubbo-consumer/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.hks 7 | dubbo-consumer 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | dubbo-consumer 12 | dubbo-consumer project for Spring Boot 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 2.1.0.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 1.8 25 | 26 | 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter 31 | 32 | 33 | 34 | org.springframework.boot 35 | spring-boot-starter-test 36 | test 37 | 38 | 39 | com.hks 40 | dubbo-api 41 | 0.0.1-SNAPSHOT 42 | 43 | 44 | com.alibaba 45 | dubbo 46 | 2.6.4 47 | 48 | 49 | 50 | 51 | 52 | 53 | org.springframework.boot 54 | spring-boot-maven-plugin 55 | 56 | 57 | 58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /dubbo-consumer/src/main/java/com/hks/dubboconsumer/DubboConsumerApplication.java: -------------------------------------------------------------------------------- 1 | package com.hks.dubboconsumer; 2 | 3 | import com.alibaba.dubbo.config.ApplicationConfig; 4 | import com.alibaba.dubbo.config.ReferenceConfig; 5 | import com.alibaba.dubbo.config.RegistryConfig; 6 | import com.hks.dubboapi.service.GreetingService; 7 | import org.springframework.boot.SpringApplication; 8 | import org.springframework.boot.autoconfigure.SpringBootApplication; 9 | 10 | @SpringBootApplication 11 | public class DubboConsumerApplication { 12 | 13 | public static void main(String[] args) { 14 | SpringApplication.run(DubboConsumerApplication.class, args); 15 | try{ 16 | ReferenceConfig referenceConfig = new ReferenceConfig(); 17 | referenceConfig.setApplication(new ApplicationConfig("first-dubbo-consumer")); 18 | referenceConfig.setRegistry(new RegistryConfig("multicast://224.5.6.7:1234")); 19 | referenceConfig.setInterface(GreetingService.class); 20 | GreetingService greetingService = referenceConfig.get(); 21 | System.out.println(greetingService.sayHello("world")); 22 | } 23 | catch (Exception ex){ 24 | ex.printStackTrace(); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /dubbo-consumer/src/main/resources/application.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/singgel/RPC-SkillTree/67bfbc076b18bca17850c64fd2a935fdcd88d9ee/dubbo-consumer/src/main/resources/application.properties -------------------------------------------------------------------------------- /dubbo-consumer/src/test/java/com/hks/dubboconsumer/DubboConsumerApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.hks.dubboconsumer; 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 DubboConsumerApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /dubbo-provider/.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | .sts4-cache 12 | 13 | ### IntelliJ IDEA ### 14 | .idea 15 | *.iws 16 | *.iml 17 | *.ipr 18 | 19 | ### NetBeans ### 20 | /nbproject/private/ 21 | /build/ 22 | /nbbuild/ 23 | /dist/ 24 | /nbdist/ 25 | /.nb-gradle/ -------------------------------------------------------------------------------- /dubbo-provider/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.hks 7 | dubbo-provider 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | dubbo-provider 12 | dubbo-provider project for Spring Boot 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 2.1.0.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 1.8 25 | 26 | 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter 31 | 32 | 33 | 34 | com.hks 35 | dubbo-api 36 | 0.0.1-SNAPSHOT 37 | 38 | 39 | 40 | com.alibaba 41 | dubbo 42 | 2.6.4 43 | 44 | 45 | 46 | 47 | io.netty 48 | netty-all 49 | 4.1.42.Final 50 | 51 | 52 | 53 | org.springframework.boot 54 | spring-boot-starter-test 55 | test 56 | 57 | 58 | 59 | 60 | 61 | 62 | org.springframework.boot 63 | spring-boot-maven-plugin 64 | 65 | 66 | 67 | 68 | 69 | 70 | -------------------------------------------------------------------------------- /dubbo-provider/src/main/java/com/hks/dubboprovider/DubboProviderApplication.java: -------------------------------------------------------------------------------- 1 | package com.hks.dubboprovider; 2 | 3 | import com.alibaba.dubbo.config.ApplicationConfig; 4 | import com.alibaba.dubbo.config.RegistryConfig; 5 | import com.alibaba.dubbo.config.ServiceConfig; 6 | import com.hks.dubboapi.service.GreetingService; 7 | import com.hks.dubboprovider.service.GreetingServiceImpl; 8 | import org.springframework.boot.SpringApplication; 9 | import org.springframework.boot.autoconfigure.SpringBootApplication; 10 | 11 | @SpringBootApplication 12 | public class DubboProviderApplication { 13 | 14 | public static void main(String[] args) { 15 | SpringApplication.run(DubboProviderApplication.class, args); 16 | 17 | try{ 18 | ServiceConfig serviceConfig = new ServiceConfig(); 19 | serviceConfig.setApplication(new ApplicationConfig("first-dubbo-provider")); 20 | serviceConfig.setRegistry(new RegistryConfig("multicast://224.5.6.7:1234")); 21 | serviceConfig.setInterface(GreetingService.class); 22 | serviceConfig.setRef(new GreetingServiceImpl()); 23 | serviceConfig.export(); 24 | System.in.read(); 25 | } 26 | catch (Exception ex){ 27 | ex.printStackTrace(); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /dubbo-provider/src/main/java/com/hks/dubboprovider/service/GreetingServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.hks.dubboprovider.service; 2 | 3 | import com.hks.dubboapi.service.GreetingService; 4 | 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | 8 | /** 9 | * @Author: hekuangsheng 10 | * @Date: 2018/11/13 11 | */ 12 | public class GreetingServiceImpl implements GreetingService { 13 | public String sayHello(String name) { 14 | return "Hello " + name; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /dubbo-provider/src/main/resources/application.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/singgel/RPC-SkillTree/67bfbc076b18bca17850c64fd2a935fdcd88d9ee/dubbo-provider/src/main/resources/application.properties -------------------------------------------------------------------------------- /dubbo-provider/src/test/java/com/hks/dubboprovider/DubboProviderApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.hks.dubboprovider; 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 DubboProviderApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /google-protocol-buffer/.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | .sts4-cache 12 | 13 | ### IntelliJ IDEA ### 14 | .idea 15 | *.iws 16 | *.iml 17 | *.ipr 18 | 19 | ### NetBeans ### 20 | /nbproject/private/ 21 | /build/ 22 | /nbbuild/ 23 | /dist/ 24 | /nbdist/ 25 | /.nb-gradle/ -------------------------------------------------------------------------------- /google-protocol-buffer/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.hks 7 | google-protocol-buffer 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | google-protocol-buffer 12 | google-protocol-buffer project for Spring Boot 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 2.0.4.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 1.8 25 | 26 | 1.7.0 27 | 28 | 3.4.0 29 | 30 | 31 | 32 | 33 | org.springframework.boot 34 | spring-boot-starter 35 | 36 | 37 | com.google.protobuf 38 | protobuf-java 39 | ${protobuf.version} 40 | 41 | 42 | io.grpc 43 | grpc-netty 44 | ${grpc.version} 45 | provided 46 | 47 | 48 | io.grpc 49 | grpc-protobuf 50 | ${grpc.version} 51 | provided 52 | 53 | 54 | io.grpc 55 | grpc-stub 56 | ${grpc.version} 57 | provided 58 | 59 | 60 | 61 | org.springframework.boot 62 | spring-boot-starter-test 63 | test 64 | 65 | 66 | 67 | 68 | 69 | 70 | kr.motd.maven 71 | os-maven-plugin 72 | 1.5.0.Final 73 | 74 | 75 | 76 | 77 | org.springframework.boot 78 | spring-boot-maven-plugin 79 | 80 | 81 | org.xolstice.maven.plugins 82 | protobuf-maven-plugin 83 | 0.5.1 84 | 85 | com.google.protobuf:protoc:${protobuf.version}:exe:${os.detected.classifier} 86 | grpc-java 87 | io.grpc:protoc-gen-grpc-java:${grpc.version}}:exe:${os.detected.classifier} 88 | 89 | 90 | 91 | 92 | compile 93 | compile-custom 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | -------------------------------------------------------------------------------- /google-protocol-buffer/src/main/java/com/hks/googleprotocolbuffer/GoogleProtocolBufferApplication.java: -------------------------------------------------------------------------------- 1 | package com.hks.googleprotocolbuffer; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class GoogleProtocolBufferApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(GoogleProtocolBufferApplication.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /google-protocol-buffer/src/main/proto/date_time.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | package com.hks.googleprotocolbuffer.protobuf; 3 | option java_outer_classname = "DateTimeBuilder"; 4 | message DateTime { 5 | int32 id = 1; 6 | } -------------------------------------------------------------------------------- /google-protocol-buffer/src/main/proto/person.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | package com.hks.googleprotocolbuffer.protobuf; 3 | import "date_time.proto"; 4 | option java_outer_classname = "PersonBuilder"; 5 | message Person { 6 | int32 id = 1; 7 | string name = 2; 8 | string email = 3; 9 | } -------------------------------------------------------------------------------- /google-protocol-buffer/src/main/resources/application.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/singgel/RPC-SkillTree/67bfbc076b18bca17850c64fd2a935fdcd88d9ee/google-protocol-buffer/src/main/resources/application.properties -------------------------------------------------------------------------------- /google-protocol-buffer/src/test/java/com/hks/googleprotocolbuffer/GoogleProtocolBufferApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.hks.googleprotocolbuffer; 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 GoogleProtocolBufferApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /google-snappy/.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | .sts4-cache 12 | 13 | ### IntelliJ IDEA ### 14 | .idea 15 | *.iws 16 | *.iml 17 | *.ipr 18 | 19 | ### NetBeans ### 20 | /nbproject/private/ 21 | /build/ 22 | /nbbuild/ 23 | /dist/ 24 | /nbdist/ 25 | /.nb-gradle/ -------------------------------------------------------------------------------- /google-snappy/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.hks 7 | google-snappy 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | google-snappy 12 | google-snappy project for Spring Boot 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 2.0.6.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 1.8 25 | 26 | 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter 31 | 32 | 33 | 34 | org.xerial.snappy 35 | snappy-java 36 | 1.1.1.7 37 | 38 | 39 | 40 | org.springframework.boot 41 | spring-boot-starter-test 42 | test 43 | 44 | 45 | 46 | 47 | 48 | 49 | org.springframework.boot 50 | spring-boot-maven-plugin 51 | 52 | 53 | 54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /google-snappy/src/main/java/com/hks/googlesnappy/DemoTest.java: -------------------------------------------------------------------------------- 1 | package com.hks.googlesnappy; 2 | 3 | import java.util.Arrays; 4 | import org.xerial.snappy.Snappy; 5 | /** 6 | * @Author: hekuangsheng 7 | * @Date: 2018/10/29 8 | * 9 | * Snappy是Google开源的压缩/解压缩库。 10 | * 和其他压缩库相比,snappy的压缩率并不是最高的,兼容性也并非最好的。 11 | * 相反,它的诞生旨在以极高的压缩/解压缩速率提供合理的压缩率。 12 | */ 13 | public class DemoTest { 14 | 15 | public static void main(String[] args) { 16 | try{ 17 | String input = "Hello snappy-java! Snappy-java is a JNI-based wrapper of Snappy, a fast compresser/decompresser."; 18 | { 19 | byte[] compressed = Snappy.compress(input.getBytes("UTF-8")); 20 | byte[] uncompressed = Snappy.uncompress(compressed); 21 | String result = new String(uncompressed, "UTF-8"); 22 | System.out.println(result); 23 | } 24 | 25 | { 26 | byte[] compressed = Snappy.compress(input); 27 | System.out.println(Snappy.uncompressString(compressed)); 28 | } 29 | 30 | { 31 | double [] arr = new double[]{123.456,234.567,345.678}; 32 | byte[] compressed = Snappy.compress(arr); 33 | double [] unarr = Snappy.uncompressDoubleArray(compressed); 34 | System.out.println(Arrays.toString(unarr)); 35 | } 36 | } 37 | catch (Exception ex){ 38 | ex.printStackTrace(); 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /google-snappy/src/main/java/com/hks/googlesnappy/GoogleSnappyApplication.java: -------------------------------------------------------------------------------- 1 | package com.hks.googlesnappy; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class GoogleSnappyApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(GoogleSnappyApplication.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /google-snappy/src/main/resources/application.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/singgel/RPC-SkillTree/67bfbc076b18bca17850c64fd2a935fdcd88d9ee/google-snappy/src/main/resources/application.properties -------------------------------------------------------------------------------- /google-snappy/src/test/java/com/hks/googlesnappy/GoogleSnappyApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.hks.googlesnappy; 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 GoogleSnappyApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /grpc-api/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | /target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | 5 | ### STS ### 6 | .apt_generated 7 | .classpath 8 | .factorypath 9 | .project 10 | .settings 11 | .springBeans 12 | .sts4-cache 13 | 14 | ### IntelliJ IDEA ### 15 | .idea 16 | *.iws 17 | *.iml 18 | *.ipr 19 | 20 | ### NetBeans ### 21 | /nbproject/private/ 22 | /nbbuild/ 23 | /dist/ 24 | /nbdist/ 25 | /.nb-gradle/ 26 | /build/ 27 | 28 | ### VS Code ### 29 | .vscode/ 30 | -------------------------------------------------------------------------------- /grpc-api/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.1.5.RELEASE 9 | 10 | 11 | com.hks 12 | grpc-api 13 | 0.0.1-SNAPSHOT 14 | grpc-api 15 | Demo project for Spring Boot 16 | 17 | 18 | 1.8 19 | 20 | 21 | 22 | 23 | org.springframework.boot 24 | spring-boot-starter 25 | 26 | 27 | org.springframework.boot 28 | spring-boot-starter-test 29 | test 30 | 31 | 32 | io.grpc 33 | grpc-netty 34 | RELEASE 35 | 36 | 37 | io.grpc 38 | grpc-protobuf 39 | RELEASE 40 | 41 | 42 | io.grpc 43 | grpc-stub 44 | RELEASE 45 | 46 | 47 | io.grpc 48 | grpc-core 49 | RELEASE 50 | 51 | 52 | com.baidu 53 | jprotobuf 54 | 2.2.11 55 | 56 | 57 | org.projectlombok 58 | lombok 59 | 60 | 61 | io.protostuff 62 | protostuff-core 63 | 1.4.0 64 | 65 | 66 | io.protostuff 67 | protostuff-runtime 68 | 1.4.0 69 | 70 | 87 | 88 | 89 | 90 | 91 | 92 | org.springframework.boot 93 | spring-boot-maven-plugin 94 | 95 | 96 | 97 | 98 | 99 | -------------------------------------------------------------------------------- /grpc-api/src/main/java/com/hks/grpc/GrpcApplication.java: -------------------------------------------------------------------------------- 1 | package com.hks.grpc; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class GrpcApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(GrpcApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /grpc-api/src/main/java/com/hks/grpc/bean/HelloRequestStuff.java: -------------------------------------------------------------------------------- 1 | package com.hks.grpc.bean; 2 | 3 | import com.baidu.bjf.remoting.protobuf.FieldType; 4 | import com.baidu.bjf.remoting.protobuf.annotation.Protobuf; 5 | import io.protostuff.Tag; 6 | import lombok.Data; 7 | 8 | @Data 9 | public class HelloRequestStuff { 10 | @Tag(1) 11 | private String name; 12 | 13 | @Tag(2) 14 | private int age; 15 | 16 | @Tag(3) 17 | private Double profit_rate; 18 | } 19 | -------------------------------------------------------------------------------- /grpc-api/src/main/java/com/hks/grpc/bean/Hellorequest.java: -------------------------------------------------------------------------------- 1 | package com.hks.grpc.bean; 2 | 3 | import com.baidu.bjf.remoting.protobuf.FieldType; 4 | import com.baidu.bjf.remoting.protobuf.annotation.Protobuf; 5 | import lombok.Data; 6 | 7 | @Data 8 | public class Hellorequest { 9 | @Protobuf(fieldType = FieldType.STRING, order = 1) 10 | private String name; 11 | 12 | @Protobuf(fieldType = FieldType.SINT32, order = 2) 13 | private int age; 14 | 15 | @Protobuf(fieldType = FieldType.DOUBLE, order = 3) 16 | private Double profit_rate; 17 | } 18 | -------------------------------------------------------------------------------- /grpc-api/src/main/java/com/hks/grpc/service/HelloRequestJava.java: -------------------------------------------------------------------------------- 1 | package com.hks.grpc.service; 2 | 3 | public class HelloRequestJava { 4 | private String name; 5 | private int age; 6 | private double profit_rate; 7 | 8 | public String getName() { 9 | return name; 10 | } 11 | 12 | public void setName(String name) { 13 | this.name = name; 14 | } 15 | 16 | public int getAge() { 17 | return age; 18 | } 19 | 20 | public void setAge(int age) { 21 | this.age = age; 22 | } 23 | 24 | public double getProfit_rate() { 25 | return profit_rate; 26 | } 27 | 28 | public void setProfit_rate(double profit_rate) { 29 | this.profit_rate = profit_rate; 30 | } 31 | 32 | public HelloRequestJava(String name, int age, double profit_rate) { 33 | this.name = name; 34 | this.age = age; 35 | this.profit_rate = profit_rate; 36 | } 37 | 38 | public HelloRequestJava() { 39 | } 40 | 41 | @Override 42 | public String toString() { 43 | return "HelloRequestJava{" + 44 | "name='" + name + '\'' + 45 | ", age=" + age + 46 | ", profit_rate=" + profit_rate + 47 | '}'; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /grpc-api/src/main/java/com/hks/grpc/util/ProtoBufUtil.java: -------------------------------------------------------------------------------- 1 | package com.hks.grpc.util; 2 | 3 | import io.protostuff.LinkedBuffer; 4 | import io.protostuff.ProtobufIOUtil; 5 | import io.protostuff.ProtostuffIOUtil; 6 | import io.protostuff.Schema; 7 | import io.protostuff.runtime.RuntimeSchema; 8 | 9 | /** 10 | * Created by zhangzh on 2017/2/20. 11 | */ 12 | public class ProtoBufUtil { 13 | public ProtoBufUtil() { 14 | } 15 | 16 | public static byte[] serializer(T o) { 17 | Schema schema = RuntimeSchema.getSchema(o.getClass()); 18 | return ProtobufIOUtil.toByteArray(o, schema, LinkedBuffer.allocate(256)); 19 | } 20 | 21 | public static T deserializer(byte[] bytes, Class clazz) { 22 | 23 | T obj = null; 24 | try { 25 | obj = clazz.newInstance(); 26 | Schema schema = RuntimeSchema.getSchema(obj.getClass()); 27 | ProtostuffIOUtil.mergeFrom(bytes, obj, schema); 28 | } catch (InstantiationException e) { 29 | e.printStackTrace(); 30 | } catch (IllegalAccessException e) { 31 | e.printStackTrace(); 32 | } 33 | 34 | return obj; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /grpc-api/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /grpc-api/src/main/resources/proto/addressbook.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto2"; 2 | 3 | package tutorial; 4 | 5 | option java_package = "com.hks.grpc.service"; 6 | option java_outer_classname = "AddressBookProtos"; 7 | 8 | message Person { 9 | required string name = 1; 10 | required int32 id = 2; 11 | optional string email = 3; 12 | 13 | enum PhoneType { 14 | MOBILE = 0; 15 | HOME = 1; 16 | WORK = 2; 17 | } 18 | 19 | message PhoneNumber { 20 | required string number = 1; 21 | optional PhoneType type = 2 [default = HOME]; 22 | } 23 | 24 | repeated PhoneNumber phones = 4; 25 | optional int32 age = 5; 26 | } 27 | 28 | message AddressBook { 29 | repeated Person people = 1; 30 | } 31 | -------------------------------------------------------------------------------- /grpc-api/src/main/resources/proto/hello.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | import "google/protobuf/wrappers.proto"; 4 | option java_multiple_files = false; 5 | option java_package = "com.hks.grpc.service"; 6 | option java_outer_classname = "HelloProto"; 7 | 8 | package hello; 9 | 10 | service Greeter { 11 | rpc SayHello (HelloRequest) returns (HelloReply) { 12 | } 13 | } 14 | 15 | message HelloRequest { 16 | string name = 1; 17 | int32 age = 2; 18 | google.protobuf.DoubleValue profit_rate = 3; 19 | } 20 | 21 | message HelloReply { 22 | string message = 1; 23 | oneof has_code { 24 | int32 code = 2; 25 | } 26 | } -------------------------------------------------------------------------------- /grpc-api/src/test/java/com/hks/grpc/GrpcApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.hks.grpc; 2 | 3 | import com.baidu.bjf.remoting.protobuf.Codec; 4 | import com.baidu.bjf.remoting.protobuf.ProtobufProxy; 5 | import com.google.protobuf.Descriptors.FieldDescriptor; 6 | import com.google.protobuf.DoubleValue; 7 | import com.hks.grpc.bean.HelloRequestStuff; 8 | import com.hks.grpc.bean.Hellorequest; 9 | import com.hks.grpc.service.AddressBookProtos.Person; 10 | import com.hks.grpc.service.HelloProto.HelloRequest; 11 | import com.hks.grpc.service.HelloProto.HelloReply; 12 | import com.hks.grpc.service.HelloRequestJava; 13 | import com.hks.grpc.util.ProtoBufUtil; 14 | import org.junit.Test; 15 | import org.junit.runner.RunWith; 16 | import org.springframework.boot.test.context.SpringBootTest; 17 | import org.springframework.test.context.junit4.SpringRunner; 18 | 19 | import java.io.IOException; 20 | import java.util.HashMap; 21 | 22 | @RunWith(SpringRunner.class) 23 | @SpringBootTest 24 | public class GrpcApplicationTests { 25 | 26 | @Test 27 | public void contextLoads() throws Exception{ 28 | Person john = 29 | Person.newBuilder() 30 | .setId(1234) 31 | .setName("John Doe") 32 | .setEmail("jdoe@example.com") 33 | .addPhones( 34 | Person.PhoneNumber.newBuilder() 35 | .setNumber("555-4321") 36 | .setType(Person.PhoneType.HOME)) 37 | .build(); 38 | /*FileOutputStream output = new FileOutputStream("./demo.db"); 39 | john.toBuilder().build().writeTo(output); 40 | output.close(); 41 | john = Person.parseFrom(new FileInputStream("./demo.db"));*/ 42 | 43 | System.out.println(john.hasAge()); 44 | System.out.println(john.getAge()); 45 | System.out.println("=============="); 46 | john = john.toBuilder().setAge(0).build(); 47 | System.out.println(john.hasAge()); 48 | System.out.println(john.getAge()); 49 | System.out.println("=============="); 50 | john = john.toBuilder().setAge(200).build(); 51 | System.out.println(john.hasAge()); 52 | } 53 | 54 | @Test 55 | public void testRequest() { 56 | HelloRequest hello = 57 | HelloRequest.newBuilder() 58 | .setName("john") 59 | .build(); 60 | FieldDescriptor fieldDesc = hello.getDescriptorForType().findFieldByName("age"); 61 | System.out.println(hello.hasField(fieldDesc)); 62 | System.out.println(hello); 63 | System.out.println("=============="); 64 | hello = hello.toBuilder().setAge(0).build(); 65 | System.out.println(hello.hasField(fieldDesc)); 66 | System.out.println("=============="); 67 | hello = hello.toBuilder().setAge(200).build(); 68 | System.out.println(hello.hasField(fieldDesc)); 69 | System.out.println(hello); 70 | 71 | /*HelloRequestJava helloRequestJava = (HelloRequestJava)BeanHelper.protoBeanToJavaBean(hello,new HelloRequestJava(), new HashMap<>()); 72 | System.out.println(helloRequestJava.toString());*/ 73 | } 74 | 75 | @Test 76 | public void testRequestWrapper() { 77 | HelloRequest hello = 78 | HelloRequest.newBuilder() 79 | .setName("john") 80 | .build(); 81 | System.out.println(hello.hasProfitRate()); 82 | System.out.println(hello); 83 | System.out.println("=============="); 84 | hello = hello.toBuilder().setProfitRate(DoubleValue.newBuilder().setValue(0).build()).build(); 85 | System.out.println(hello.hasProfitRate()); 86 | System.out.println("=============="); 87 | hello = hello.toBuilder().setProfitRate(DoubleValue.newBuilder().setValue(200).build()).build(); 88 | System.out.println(hello.hasProfitRate()); 89 | System.out.println(hello); 90 | } 91 | 92 | @Test 93 | public void testReplyOneOf(){ 94 | HelloReply reply = HelloReply.newBuilder() 95 | .setMessage("hello") 96 | .build(); 97 | System.out.println(reply.getHasCodeCase()); 98 | System.out.println("=============="); 99 | reply = reply.toBuilder().setCode(0).build(); 100 | System.out.println(reply.getHasCodeCase()); 101 | System.out.println("=============="); 102 | reply = reply.toBuilder().setCode(200).build(); 103 | System.out.println(reply.getHasCodeCase()); 104 | } 105 | 106 | @Test 107 | public void testJprotobuf(){ 108 | Codec simpleTypeCodec = ProtobufProxy 109 | .create(Hellorequest.class); 110 | 111 | HelloRequest hellorequest = 112 | HelloRequest.newBuilder() 113 | .setName("john") 114 | .setAge(100) 115 | .setProfitRate(DoubleValue.of(0.0)) 116 | .build(); 117 | /*Hellorequest hellorequest = new Hellorequest(); 118 | hellorequest.setName("john"); 119 | hellorequest.setAge(100); 120 | hellorequest.setProfit_rate(0.0);*/ 121 | try { 122 | // 序列化 123 | byte[] bb = hellorequest.toByteArray(); 124 | // byte[] bb = simpleTypeCodec.encode(hellorequest); 125 | // 反序列化 126 | HelloRequest hello = HelloRequest.parseFrom(bb); 127 | System.out.println(hello); 128 | Hellorequest newHellorequest = simpleTypeCodec.decode(bb); 129 | System.out.println(newHellorequest); 130 | HelloRequestStuff request = ProtoBufUtil.deserializer(bb,HelloRequestStuff.class); 131 | System.out.println(request); 132 | } catch (IOException e) { 133 | e.printStackTrace(); 134 | } 135 | } 136 | } 137 | -------------------------------------------------------------------------------- /grpc-consumer/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | /target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | 5 | ### STS ### 6 | .apt_generated 7 | .classpath 8 | .factorypath 9 | .project 10 | .settings 11 | .springBeans 12 | .sts4-cache 13 | 14 | ### IntelliJ IDEA ### 15 | .idea 16 | *.iws 17 | *.iml 18 | *.ipr 19 | 20 | ### NetBeans ### 21 | /nbproject/private/ 22 | /nbbuild/ 23 | /dist/ 24 | /nbdist/ 25 | /.nb-gradle/ 26 | /build/ 27 | 28 | ### VS Code ### 29 | .vscode/ 30 | -------------------------------------------------------------------------------- /grpc-consumer/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.1.5.RELEASE 9 | 10 | 11 | com.hks 12 | grpc-consumer 13 | 0.0.1-SNAPSHOT 14 | grpc-consumer 15 | Demo project for Spring Boot 16 | 17 | 18 | 1.8 19 | 20 | 21 | 22 | 23 | org.springframework.boot 24 | spring-boot-starter 25 | 26 | 27 | com.hks 28 | grpc-api 29 | 0.0.1-SNAPSHOT 30 | 31 | 32 | io.grpc 33 | grpc-netty 34 | RELEASE 35 | 36 | 37 | io.grpc 38 | grpc-protobuf 39 | 1.53.0 40 | 41 | 42 | io.grpc 43 | grpc-stub 44 | RELEASE 45 | 46 | 47 | io.grpc 48 | grpc-core 49 | RELEASE 50 | 51 | 52 | org.springframework.boot 53 | spring-boot-starter-test 54 | test 55 | 56 | 57 | 58 | 59 | 60 | 61 | org.springframework.boot 62 | spring-boot-maven-plugin 63 | 64 | 65 | 66 | 67 | 68 | -------------------------------------------------------------------------------- /grpc-consumer/src/main/java/com/hks/grpc/GrpcApplication.java: -------------------------------------------------------------------------------- 1 | package com.hks.grpc; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class GrpcApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(GrpcApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /grpc-consumer/src/main/java/com/hks/grpc/client/HelloClient.java: -------------------------------------------------------------------------------- 1 | package com.hks.grpc.client; 2 | 3 | import com.hks.grpc.service.GreeterGrpc; 4 | import com.hks.grpc.service.HelloProto; 5 | import io.grpc.ManagedChannel; 6 | import io.grpc.ManagedChannelBuilder; 7 | import io.grpc.StatusRuntimeException; 8 | 9 | import java.util.concurrent.TimeUnit; 10 | import java.util.logging.Level; 11 | import java.util.logging.Logger; 12 | 13 | public class HelloClient { 14 | private static final Logger logger = Logger.getLogger(HelloClient.class.getName()); 15 | 16 | private final ManagedChannel channel; 17 | private final GreeterGrpc.GreeterBlockingStub blockingStub; 18 | 19 | /** Construct client connecting to HelloWorld server at {@code host:port}. */ 20 | // 首先,我们需要为stub创建一个grpc的channel,指定我们连接服务端的地址和端口 21 | // 使用ManagedChannelBuilder方法来创建channel 22 | public HelloClient(String host, int port) { 23 | channel = ManagedChannelBuilder.forAddress(host, port) 24 | // Channels are secure by default (via SSL/TLS). For the example we disable TLS to avoid 25 | // needing certificates. 26 | .usePlaintext(true) 27 | .build(); 28 | // 使用我们从proto文件生成的GreeterGrpc类提供的newBlockingStub方法指定channel创建stubs 29 | blockingStub = GreeterGrpc.newBlockingStub(channel); 30 | } 31 | 32 | public void shutdown() throws InterruptedException { 33 | channel.shutdown().awaitTermination(5, TimeUnit.SECONDS); 34 | } 35 | // 调用服务端方法 36 | /** Say hello to server. */ 37 | public void greet(String name) { 38 | logger.info("Will try to greet " + name + " ..."); 39 | // 创建并定制protocol buffer对象,使用该对象调用服务端的sayHello方法,获得response 40 | HelloProto.HelloRequest request = HelloProto.HelloRequest.newBuilder().setName(name).build(); 41 | HelloProto.HelloReply response; 42 | try { 43 | response = blockingStub.sayHello(request); 44 | // 如果有异常发生,则异常被编码成Status,可以从StatusRuntimeException异常中捕获 45 | } catch (StatusRuntimeException e) { 46 | logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus()); 47 | return; 48 | } 49 | logger.info("Greeting: " + response.getMessage()); 50 | } 51 | 52 | /** 53 | * Greet server. If provided, the first element of {@code args} is the name to use in the 54 | * greeting. 55 | */ 56 | public static void main(String[] args) throws Exception { 57 | HelloClient client = new HelloClient("localhost", 50051); 58 | try { 59 | /* Access a service running on the local machine on port 50051 */ 60 | String user = "hans"; 61 | if (args.length > 0) { 62 | user = args[0]; /* Use the arg as the name to greet if provided */ 63 | } 64 | client.greet(user); 65 | } finally { 66 | client.shutdown(); 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /grpc-consumer/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /grpc-consumer/src/test/java/com/hks/grpc/GrpcApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.hks.grpc; 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 GrpcApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /grpc-provider/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | /target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | 5 | ### STS ### 6 | .apt_generated 7 | .classpath 8 | .factorypath 9 | .project 10 | .settings 11 | .springBeans 12 | .sts4-cache 13 | 14 | ### IntelliJ IDEA ### 15 | .idea 16 | *.iws 17 | *.iml 18 | *.ipr 19 | 20 | ### NetBeans ### 21 | /nbproject/private/ 22 | /nbbuild/ 23 | /dist/ 24 | /nbdist/ 25 | /.nb-gradle/ 26 | /build/ 27 | 28 | ### VS Code ### 29 | .vscode/ 30 | -------------------------------------------------------------------------------- /grpc-provider/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.1.5.RELEASE 9 | 10 | 11 | com.hks 12 | grpc-provider 13 | 0.0.1-SNAPSHOT 14 | grpc-provider 15 | Demo project for Spring Boot 16 | 17 | 18 | 1.8 19 | 20 | 21 | 22 | 23 | org.springframework.boot 24 | spring-boot-starter 25 | 26 | 27 | com.hks 28 | grpc-api 29 | 0.0.1-SNAPSHOT 30 | 31 | 32 | io.grpc 33 | grpc-netty 34 | RELEASE 35 | 36 | 37 | io.grpc 38 | grpc-protobuf 39 | RELEASE 40 | 41 | 42 | io.grpc 43 | grpc-stub 44 | RELEASE 45 | 46 | 47 | io.grpc 48 | grpc-core 49 | RELEASE 50 | 51 | 52 | org.springframework.boot 53 | spring-boot-starter-test 54 | test 55 | 56 | 57 | 58 | 59 | 60 | 61 | org.springframework.boot 62 | spring-boot-maven-plugin 63 | 64 | 65 | 66 | 67 | 68 | -------------------------------------------------------------------------------- /grpc-provider/src/main/java/com/hks/grpc/GrpcApplication.java: -------------------------------------------------------------------------------- 1 | package com.hks.grpc; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class GrpcApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(GrpcApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /grpc-provider/src/main/java/com/hks/grpc/server/HelloServer.java: -------------------------------------------------------------------------------- 1 | package com.hks.grpc.server; 2 | 3 | import com.hks.grpc.service.GreeterGrpc; 4 | import com.hks.grpc.service.HelloProto; 5 | import io.grpc.Server; 6 | import io.grpc.ServerBuilder; 7 | import io.grpc.stub.StreamObserver; 8 | 9 | import java.io.IOException; 10 | import java.util.logging.Logger; 11 | 12 | public class HelloServer { 13 | private static final Logger logger = Logger.getLogger(HelloServer.class.getName()); 14 | private int port = 50051; 15 | private Server server; 16 | 17 | private void start() throws IOException { 18 | // 使用ServerBuilder来构建和启动服务,通过使用forPort方法来指定监听的地址和端口 19 | // 创建一个实现方法的服务GreeterImpl的实例,并通过addService方法将该实例纳入 20 | // 调用build() start()方法构建和启动rpcserver 21 | server = ServerBuilder.forPort(port) 22 | .addService(new GreeterImpl()) 23 | .build() 24 | .start(); 25 | logger.info("Server started, listening on " + port); 26 | 27 | Runtime.getRuntime().addShutdownHook(new Thread() { 28 | @Override 29 | public void run() { 30 | // Use stderr here since the logger may have been reset by its JVM shutdown hook. 31 | System.err.println("*** shutting down gRPC server since JVM is shutting down"); 32 | HelloServer.this.stop(); 33 | System.err.println("*** server shut down"); 34 | } 35 | }); 36 | } 37 | 38 | private void stop() { 39 | if (server != null) { 40 | server.shutdown(); 41 | } 42 | } 43 | 44 | /** 45 | * Await termination on the main thread since the grpc library uses daemon threads. 46 | */ 47 | private void blockUntilShutdown() throws InterruptedException { 48 | if (server != null) { 49 | server.awaitTermination(); 50 | } 51 | } 52 | 53 | /** 54 | * Main launches the server from the command line. 55 | */ 56 | public static void main(String[] args) throws IOException, InterruptedException { 57 | final HelloServer server = new HelloServer(); 58 | server.start(); 59 | server.blockUntilShutdown(); 60 | } 61 | 62 | // 我们的服务GreeterImpl继承了生成抽象类GreeterGrpc.GreeterImplBase,实现了服务的所有方法 63 | private class GreeterImpl extends GreeterGrpc.GreeterImplBase { 64 | 65 | @Override 66 | public void sayHello(HelloProto.HelloRequest req, StreamObserver responseObserver) { 67 | HelloProto.HelloReply reply = HelloProto.HelloReply.newBuilder() 68 | .setMessage("Hello " + req.getName()) 69 | .build(); 70 | // 使用响应监视器的onNext方法返回HelloReply 71 | responseObserver.onNext(reply); 72 | // 使用onCompleted方法指定本次调用已经完成 73 | responseObserver.onCompleted(); 74 | } 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /grpc-provider/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /grpc-provider/src/test/java/com/hks/grpc/GrpcApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.hks.grpc; 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 GrpcApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /grpc-stream-client/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | RPC-SkillTree 7 | com.hks.rpc 8 | 0.0.1-SNAPSHOT 9 | 10 | 4.0.0 11 | 12 | grpc-stream-client 13 | 14 | 15 | 16 | UTF-8 17 | 1.8 18 | 1.12.0 19 | 3.5.1-1 20 | 21 | 22 | 23 | 24 | io.grpc 25 | grpc-all 26 | ${grpc.version} 27 | 28 | 29 | 30 | 31 | 32 | 33 | kr.motd.maven 34 | os-maven-plugin 35 | 1.5.0.Final 36 | 37 | 38 | 39 | 40 | org.xolstice.maven.plugins 41 | protobuf-maven-plugin 42 | 0.5.1 43 | 44 | com.google.protobuf:protoc:${protoc.version}:exe:${os.detected.classifier} 45 | grpc-java 46 | io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier} 47 | 48 | 49 | 50 | 51 | compile 52 | compile-custom 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | -------------------------------------------------------------------------------- /grpc-stream-client/src/main/java/com/hks/rpc/client/AdditionClient.java: -------------------------------------------------------------------------------- 1 | package com.hks.rpc.client; 2 | 3 | import io.grpc.ManagedChannel; 4 | import io.grpc.ManagedChannelBuilder; 5 | import com.hks.rpc.AdditionServiceGrpc; 6 | import com.hks.rpc.Result; 7 | import com.hks.rpc.Value; 8 | import io.grpc.stub.StreamObserver; 9 | 10 | import java.util.ArrayList; 11 | import java.util.List; 12 | import java.util.Random; 13 | import java.util.concurrent.CountDownLatch; 14 | import java.util.concurrent.TimeUnit; 15 | import java.util.logging.Level; 16 | import java.util.logging.Logger; 17 | 18 | public class AdditionClient { 19 | 20 | private static final String DEFAULT_HOST = "localhost"; 21 | 22 | private static final int DEFAULT_PORT = 8088; 23 | 24 | private static final int VALUE_NUM = 10; 25 | 26 | private static final int VALUE_UPPER_BOUND = 10; 27 | 28 | private Logger logger = Logger.getLogger(AdditionClient.class.getName()); 29 | 30 | private ManagedChannel managedChannel; 31 | 32 | //服务存根,用于客户端本地调用 33 | //private AdditionServiceGrpc.AdditionServiceBlockingStub additionServiceBlockingStub; 34 | 35 | //这里用异步请求存根 36 | private AdditionServiceGrpc.AdditionServiceStub additionServiceStub; 37 | 38 | public AdditionClient(String host, int port) { 39 | 40 | this(ManagedChannelBuilder.forAddress(host,port).usePlaintext(true).build()); 41 | 42 | } 43 | 44 | public AdditionClient(ManagedChannel managedChannel) { 45 | this.managedChannel = managedChannel; 46 | this.additionServiceStub = AdditionServiceGrpc.newStub(managedChannel); 47 | } 48 | 49 | // public void shutdown() throws InterruptedException { 50 | // managedChannel.shutdown().awaitTermination(5, TimeUnit.SECONDS); 51 | // } 52 | 53 | public void getResult(final CallBack callBack, List nums){ 54 | 55 | //判断调用状态。在内部类中被访问,需要加final修饰 56 | final CountDownLatch countDownLatch = new CountDownLatch(1); 57 | 58 | StreamObserver responseObserver = new StreamObserver() { 59 | public void onNext(Result result) { 60 | //静态方法回调 61 | //CallBack.callBackStatic(result); 62 | 63 | //实例方法回调 64 | callBack.setResult(result); 65 | callBack.callBackInstance(); 66 | } 67 | 68 | public void onError(Throwable throwable) { 69 | logger.log(Level.SEVERE,throwable.getMessage()); 70 | countDownLatch.countDown(); 71 | } 72 | 73 | public void onCompleted() { 74 | logger.log(Level.INFO,"completed"); 75 | countDownLatch.countDown(); 76 | } 77 | 78 | }; 79 | 80 | StreamObserver requestObserver = additionServiceStub.getResult(responseObserver); 81 | 82 | for(int i=0;i list = new ArrayList(); 115 | Random random = new Random(); 116 | 117 | for(int i=0; i serverBuilder){ 25 | 26 | this.port = port; 27 | 28 | //构造服务器,添加我们实际的服务 29 | server = serverBuilder.addService(new AdditionServiceImplBaseImpl()).build(); 30 | 31 | } 32 | 33 | private void start() throws IOException { 34 | server.start(); 35 | logger.info("Server has started, listening on " + port); 36 | Runtime.getRuntime().addShutdownHook(new Thread() { 37 | @Override 38 | public void run() { 39 | 40 | AdditionServer.this.stop(); 41 | 42 | } 43 | }); 44 | } 45 | 46 | private void stop() { 47 | 48 | if(server != null) 49 | server.shutdown(); 50 | 51 | } 52 | 53 | //阻塞到应用停止 54 | private void blockUntilShutdown() throws InterruptedException { 55 | if (server != null) { 56 | server.awaitTermination(); 57 | } 58 | } 59 | 60 | public static void main(String[] args) { 61 | 62 | AdditionServer addtionServer; 63 | 64 | if(args.length > 0){ 65 | addtionServer = new AdditionServer(Integer.parseInt(args[0])); 66 | }else{ 67 | addtionServer = new AdditionServer(DEFAULT_PORT); 68 | } 69 | 70 | try { 71 | addtionServer.start(); 72 | addtionServer.blockUntilShutdown(); 73 | } catch (IOException e) { 74 | e.printStackTrace(); 75 | } catch (InterruptedException e) { 76 | e.printStackTrace(); 77 | } 78 | 79 | } 80 | 81 | } 82 | -------------------------------------------------------------------------------- /grpc-stream-client/src/main/java/com/hks/rpc/server/AdditionServiceImplBaseImpl.java: -------------------------------------------------------------------------------- 1 | package com.hks.rpc.server; 2 | 3 | import com.hks.rpc.AdditionServiceGrpc; 4 | import com.hks.rpc.Result; 5 | import com.hks.rpc.Value; 6 | import io.grpc.stub.StreamObserver; 7 | 8 | import java.util.logging.Level; 9 | import java.util.logging.Logger; 10 | 11 | public class AdditionServiceImplBaseImpl extends AdditionServiceGrpc.AdditionServiceImplBase { 12 | 13 | private Logger logger = Logger.getLogger(AdditionServiceImplBaseImpl.class.getName()); 14 | 15 | @Override 16 | public StreamObserver getResult(final StreamObserver responseObserver) { 17 | //如果处理过程较为复杂,可以考虑单独写一个类来实现。这里用匿名内部类的方式,在内部类中用到参数需要加final修饰符 18 | return new StreamObserver() { 19 | 20 | private int sum = 0; 21 | private int cnt = 0; 22 | private double avg; 23 | 24 | @Override 25 | public void onNext(Value value) { 26 | sum += value.getValue(); 27 | cnt++; 28 | } 29 | 30 | @Override 31 | public void onError(Throwable throwable) { 32 | logger.log(Level.SEVERE, throwable.getMessage()); 33 | } 34 | 35 | @Override 36 | public void onCompleted() { 37 | avg = 1.0 * sum / cnt; 38 | responseObserver.onNext(Result.newBuilder().setSum(sum).setCnt(cnt).setAvg(avg).build()); 39 | responseObserver.onCompleted(); 40 | } 41 | }; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /grpc-stream-client/src/main/proto/additionService.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | //生成多文件,可以将类都生成在一个文件中 4 | option java_multiple_files = true; 5 | //包名 6 | option java_package = "com.hks.rpc"; 7 | //生成的类名 8 | option java_outer_classname = "AddtitionProto"; 9 | //object-c类名前缀避免类名冲突 10 | //option objc_class_prefix = "NS"; 11 | 12 | package addition; 13 | 14 | // 定义服务 15 | service AdditionService { 16 | // 服务中的方法,传过来一个Value类型的流,返回一个Result类型 17 | rpc getResult (stream Value) returns (Result) {} 18 | } 19 | //定义Value消息类型,用于客户端消息 20 | message Value { 21 | int32 value = 1; 22 | } 23 | //定义Result消息类型,包含总和,数字数量和平均值,用于服务端消息返回 24 | message Result { 25 | int32 sum = 1; 26 | int32 cnt = 2; 27 | double avg = 3; 28 | } 29 | -------------------------------------------------------------------------------- /grpc-stream-double/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | RPC-SkillTree 7 | com.hks.rpc 8 | 0.0.1-SNAPSHOT 9 | 10 | 4.0.0 11 | 12 | grpc-stream-double 13 | 14 | 15 | 16 | UTF-8 17 | 1.8 18 | 1.12.0 19 | 3.5.1-1 20 | 21 | 22 | 23 | 24 | io.grpc 25 | grpc-all 26 | ${grpc.version} 27 | 28 | 29 | org.slf4j 30 | slf4j-simple 31 | 1.7.25 32 | 33 | 34 | 35 | 36 | 37 | 38 | kr.motd.maven 39 | os-maven-plugin 40 | 1.5.0.Final 41 | 42 | 43 | 44 | 45 | org.xolstice.maven.plugins 46 | protobuf-maven-plugin 47 | 0.5.1 48 | 49 | com.google.protobuf:protoc:${protoc.version}:exe:${os.detected.classifier} 50 | grpc-java 51 | io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier} 52 | 53 | 54 | 55 | 56 | compile 57 | compile-custom 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | -------------------------------------------------------------------------------- /grpc-stream-double/src/main/java/com/hks/rpc/client/CalculatorClient.java: -------------------------------------------------------------------------------- 1 | package com.hks.rpc.client; 2 | 3 | 4 | import io.grpc.ManagedChannel; 5 | import io.grpc.ManagedChannelBuilder; 6 | import com.hks.rpc.CalculateProto; 7 | import com.hks.rpc.CalculateServiceGrpc; 8 | import io.grpc.stub.StreamObserver; 9 | import org.slf4j.Logger; 10 | import org.slf4j.LoggerFactory; 11 | 12 | import java.util.ArrayList; 13 | import java.util.List; 14 | import java.util.Random; 15 | import java.util.concurrent.CountDownLatch; 16 | import java.util.concurrent.TimeUnit; 17 | 18 | public class CalculatorClient { 19 | 20 | private static final String DEFAULT_HOST = "localhost"; 21 | 22 | private static final int DEFAULT_PORT = 8088; 23 | 24 | private static final int VALUE_NUM = 10; 25 | 26 | private static final int VALUE_UPPER_BOUND = 10; 27 | 28 | private static final Logger log = LoggerFactory.getLogger(CalculatorClient.class); 29 | 30 | //这里用异步请求存根 31 | private CalculateServiceGrpc.CalculateServiceStub calculateServiceStub; 32 | 33 | public CalculatorClient(String host, int port) { 34 | 35 | //使用明文通讯,这里简单化,实际生产环境需要通讯加密 36 | this(ManagedChannelBuilder.forAddress(host,port).usePlaintext(true).build()); 37 | 38 | } 39 | 40 | public CalculatorClient(ManagedChannel managedChannel) { 41 | this.calculateServiceStub = CalculateServiceGrpc.newStub(managedChannel); 42 | } 43 | 44 | /** 45 | * 实际调用部分 46 | * @param nums 传到服务端的数据流 47 | */ 48 | public void getResult( List nums){ 49 | 50 | //判断调用状态。在内部类中被访问,需要加final修饰 51 | final CountDownLatch countDownLatch = new CountDownLatch(1); 52 | 53 | StreamObserver responseObserver = new StreamObserver() { 54 | private int cnt = 0; 55 | @Override 56 | public void onNext(CalculateProto.Result result) { 57 | //此处直接打印结果,其他也可用回调进行复杂处理 58 | log.info("第{}次调用得到结果为:{}",++cnt,result); 59 | } 60 | 61 | @Override 62 | public void onError(Throwable throwable) { 63 | log.warn("调用出错:{}",throwable.getMessage()); 64 | countDownLatch.countDown(); 65 | } 66 | 67 | @Override 68 | public void onCompleted() { 69 | log.info("调用完成"); 70 | countDownLatch.countDown(); 71 | } 72 | 73 | }; 74 | 75 | StreamObserver requestObserver = calculateServiceStub.getResult(responseObserver); 76 | 77 | for(int num: nums){ 78 | CalculateProto.Value value = CalculateProto.Value.newBuilder().setValue(num).build(); 79 | requestObserver.onNext(value); 80 | 81 | //判断调用结束状态。如果整个调用已经结束,继续发送数据不会报错,但是会被舍弃 82 | if(countDownLatch.getCount() == 0){ 83 | return; 84 | } 85 | } 86 | //异步请求,无法确保onNext与onComplete的完成先后顺序 87 | requestObserver.onCompleted(); 88 | 89 | try { 90 | //如果在规定时间内没有请求完,则让程序停止 91 | if(!countDownLatch.await(5, TimeUnit.MINUTES)){ 92 | log.warn("未在规定时间内完成调用"); 93 | } 94 | } catch (InterruptedException e) { 95 | e.printStackTrace(); 96 | } 97 | 98 | 99 | } 100 | 101 | 102 | public static void main(String[] args) { 103 | 104 | CalculatorClient additionClient = new CalculatorClient(DEFAULT_HOST,DEFAULT_PORT); 105 | 106 | //生成value值 107 | List list = new ArrayList(); 108 | Random random = new Random(); 109 | 110 | for(int i=0; i getResult(StreamObserver responseObserver) { 15 | return new StreamObserver() { 16 | 17 | private int sum = 0; 18 | private int cnt = 0; 19 | private double avg; 20 | 21 | @Override 22 | public void onNext(CalculateProto.Value value) { 23 | log.info("接收到消息为:{}",value.getValue()); 24 | sum += value.getValue(); 25 | cnt++; 26 | avg = 1.0*sum/cnt; 27 | //返回当前统计结果 28 | CalculateProto.Result response = CalculateProto.Result.newBuilder().setSum(sum).setCnt(cnt).setAvg(avg).build(); 29 | log.info("返回消息为:{}",response); 30 | responseObserver.onNext(response); 31 | } 32 | 33 | @Override 34 | public void onError(Throwable throwable) { 35 | log.warn("调用出错:{}",throwable.getMessage()); 36 | } 37 | 38 | @Override 39 | public void onCompleted() { 40 | responseObserver.onCompleted(); 41 | } 42 | }; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /grpc-stream-double/src/main/java/com/hks/rpc/server/CalculatorServer.java: -------------------------------------------------------------------------------- 1 | package com.hks.rpc.server; 2 | 3 | import io.grpc.Server; 4 | import io.grpc.ServerBuilder; 5 | 6 | import java.io.IOException; 7 | import java.util.logging.Logger; 8 | 9 | public class CalculatorServer { 10 | 11 | private static final Logger logger = Logger.getLogger(CalculatorServer.class.getName()); 12 | 13 | private static final int DEFAULT_PORT = 8088; 14 | 15 | private int port;//服务端口号 16 | 17 | private Server server; 18 | 19 | public CalculatorServer(int port) { 20 | this(port, ServerBuilder.forPort(port)); 21 | } 22 | 23 | public CalculatorServer(int port, ServerBuilder serverBuilder) { 24 | this.port = port; 25 | 26 | //构造服务器,添加我们实际的服务 27 | server = serverBuilder.addService(new CalculateServiceImpl()).build(); 28 | } 29 | 30 | private void start() throws IOException { 31 | server.start(); 32 | logger.info("Server has started, listening on " + port); 33 | Runtime.getRuntime().addShutdownHook(new Thread() { 34 | @Override 35 | public void run() { 36 | 37 | CalculatorServer.this.stop(); 38 | 39 | } 40 | }); 41 | 42 | } 43 | 44 | private void stop() { 45 | 46 | if(server != null) 47 | server.shutdown(); 48 | 49 | } 50 | 51 | //阻塞到应用停止 52 | private void blockUntilShutdown() throws InterruptedException { 53 | if (server != null) { 54 | server.awaitTermination(); 55 | } 56 | } 57 | 58 | public static void main(String[] args) { 59 | 60 | CalculatorServer addtionServer; 61 | 62 | if(args.length > 0){ 63 | addtionServer = new CalculatorServer(Integer.parseInt(args[0])); 64 | }else{ 65 | addtionServer = new CalculatorServer(DEFAULT_PORT); 66 | } 67 | 68 | try { 69 | addtionServer.start(); 70 | addtionServer.blockUntilShutdown(); 71 | } catch (IOException e) { 72 | e.printStackTrace(); 73 | } catch (InterruptedException e) { 74 | e.printStackTrace(); 75 | } 76 | 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /grpc-stream-double/src/main/proto/calculateService.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | //生成多文件,可以将类都生成在一个文件中 4 | option java_multiple_files = false; 5 | //包名 6 | option java_package = "com.hks.rpc"; 7 | //生成的类名 8 | option java_outer_classname = "CalculateProto"; 9 | 10 | package calculate; 11 | 12 | // 定义服务 13 | service CalculateService { 14 | // 服务中的方法,传过来一个Value类型的流,返回一个Result类型的流信息 15 | rpc getResult (stream Value) returns (stream Result) {} 16 | } 17 | //定义Value消息类型,用于客户端消息 18 | message Value { 19 | int32 value = 1; 20 | } 21 | //定义Result消息类型,包含总和,数字数量和平均值,用于服务端消息返回 22 | message Result { 23 | int32 sum = 1; 24 | int32 cnt = 2; 25 | double avg = 3; 26 | } 27 | -------------------------------------------------------------------------------- /grpc-stream-server/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | RPC-SkillTree 7 | com.hks.rpc 8 | 0.0.1-SNAPSHOT 9 | 10 | 4.0.0 11 | 12 | grpc-stream-server 13 | 14 | 15 | 16 | UTF-8 17 | 1.8 18 | 1.12.0 19 | 3.5.1-1 20 | 21 | 22 | 23 | 24 | io.grpc 25 | grpc-all 26 | ${grpc.version} 27 | 28 | 29 | 30 | 31 | 32 | 33 | kr.motd.maven 34 | os-maven-plugin 35 | 1.5.0.Final 36 | 37 | 38 | 39 | 40 | org.xolstice.maven.plugins 41 | protobuf-maven-plugin 42 | 0.5.1 43 | 44 | com.google.protobuf:protoc:${protoc.version}:exe:${os.detected.classifier} 45 | grpc-java 46 | io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier} 47 | 48 | 49 | 50 | 51 | compile 52 | compile-custom 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | -------------------------------------------------------------------------------- /grpc-stream-server/src/main/java/com/hks/rpc/client/NameClient.java: -------------------------------------------------------------------------------- 1 | package com.hks.rpc.client; 2 | 3 | import io.grpc.ManagedChannel; 4 | import io.grpc.ManagedChannelBuilder; 5 | import com.hks.rpc.Ip; 6 | import com.hks.rpc.Name; 7 | import com.hks.rpc.NameServersGrpc; 8 | 9 | import java.util.ArrayList; 10 | import java.util.Iterator; 11 | import java.util.List; 12 | import java.util.concurrent.TimeUnit; 13 | 14 | public class NameClient { 15 | 16 | private static final String DEFAULT_HOST = "localhost"; 17 | 18 | private static final int DEFAULT_PORT = 8088; 19 | 20 | private ManagedChannel managedChannel; 21 | 22 | //服务存根,用于客户端本地调用 23 | private NameServersGrpc.NameServersBlockingStub nameServiceBlockingStub; 24 | 25 | public NameClient(String host, int port) { 26 | 27 | this(ManagedChannelBuilder.forAddress(host,port).usePlaintext(true).build()); 28 | 29 | } 30 | 31 | public NameClient(ManagedChannel managedChannel) { 32 | this.managedChannel = managedChannel; 33 | this.nameServiceBlockingStub = NameServersGrpc.newBlockingStub(managedChannel); 34 | } 35 | 36 | public void shutdown() throws InterruptedException { 37 | managedChannel.shutdown().awaitTermination(5, TimeUnit.SECONDS); 38 | } 39 | 40 | public List getIpsByName(String n){ 41 | 42 | List result = new ArrayList(); 43 | 44 | Name name = Name.newBuilder().setName(n).build(); 45 | 46 | Iterator iterator = nameServiceBlockingStub.getIpsByName(name); 47 | 48 | while (iterator.hasNext()){ 49 | 50 | result.add(iterator.next()); 51 | 52 | } 53 | 54 | return result; 55 | } 56 | 57 | public static void main(String[] args) { 58 | 59 | NameClient nameClient = new NameClient(DEFAULT_HOST,DEFAULT_PORT); 60 | 61 | for(String arg : args){ 62 | 63 | List result = nameClient.getIpsByName(arg); 64 | 65 | for(int i=0;i serverBuilder){ 25 | 26 | this.port = port; 27 | 28 | //构造服务器,添加我们实际的服务 29 | server = serverBuilder.addService(new NameServersImplBaseImpl()).build(); 30 | 31 | } 32 | 33 | private void start() throws IOException { 34 | server.start(); 35 | logger.info("Server has started, listening on " + port); 36 | Runtime.getRuntime().addShutdownHook(new Thread() { 37 | @Override 38 | public void run() { 39 | 40 | NameServer.this.stop(); 41 | 42 | } 43 | }); 44 | } 45 | 46 | private void stop() { 47 | 48 | if(server != null) 49 | server.shutdown(); 50 | 51 | } 52 | 53 | //阻塞到应用停止 54 | private void blockUntilShutdown() throws InterruptedException { 55 | if (server != null) { 56 | server.awaitTermination(); 57 | } 58 | } 59 | 60 | public static void main(String[] args) throws IOException, InterruptedException { 61 | 62 | NameServer nameServer; 63 | 64 | if(args.length > 0){ 65 | nameServer = new NameServer(Integer.parseInt(args[0])); 66 | }else{ 67 | nameServer = new NameServer(DEFAULT_PORT); 68 | } 69 | 70 | nameServer.start(); 71 | 72 | nameServer.blockUntilShutdown(); 73 | 74 | } 75 | } 76 | 77 | -------------------------------------------------------------------------------- /grpc-stream-server/src/main/java/com/hks/rpc/server/NameServersImplBaseImpl.java: -------------------------------------------------------------------------------- 1 | package com.hks.rpc.server; 2 | 3 | import com.hks.rpc.Ip; 4 | import com.hks.rpc.Name; 5 | import com.hks.rpc.NameServersGrpc; 6 | import io.grpc.stub.StreamObserver; 7 | 8 | import java.util.ArrayList; 9 | import java.util.Iterator; 10 | import java.util.List; 11 | 12 | public class NameServersImplBaseImpl extends NameServersGrpc.NameServersImplBase { 13 | 14 | //记录名称内容的list,实际项目中应该放置在数据库 15 | private List list = new ArrayList(); 16 | 17 | //构造方法中加入一些条目 18 | public NameServersImplBaseImpl() { 19 | 20 | list.add(new DataType(Name.newBuilder().setName("Sunny").build(),Ip.newBuilder().setIp("125.216.242.51").build())); 21 | list.add(new DataType(Name.newBuilder().setName("Sunny").build(),Ip.newBuilder().setIp("126.216.242.51").build())); 22 | list.add(new DataType(Name.newBuilder().setName("David").build(),Ip.newBuilder().setIp("117.226.178.139").build())); 23 | list.add(new DataType(Name.newBuilder().setName("David").build(),Ip.newBuilder().setIp("117.227.178.139").build())); 24 | list.add(new DataType(Name.newBuilder().setName("Tom").build(),Ip.newBuilder().setIp("111.222.336.11").build())); 25 | list.add(new DataType(Name.newBuilder().setName("Tom").build(),Ip.newBuilder().setIp("111.333.336.11").build())); 26 | list.add(new DataType(Name.newBuilder().setName("Tom").build(),Ip.newBuilder().setIp("111.222.335.11").build())); 27 | 28 | } 29 | 30 | 31 | @Override 32 | public void getIpsByName(Name requestName, StreamObserver responseObserver) { 33 | 34 | Iterator iter = list.iterator(); 35 | 36 | while (iter.hasNext()){ 37 | 38 | DataType data = iter.next(); 39 | 40 | if(requestName.equals(data.getName())){ 41 | 42 | System.out.println("get " + data.getIp() + " from " + requestName); 43 | 44 | responseObserver.onNext(data.getIp()); 45 | 46 | } 47 | 48 | } 49 | 50 | responseObserver.onCompleted(); 51 | 52 | } 53 | 54 | } 55 | 56 | class DataType{ 57 | private Name name; 58 | private Ip ip; 59 | 60 | public DataType(Name name, Ip ip) { 61 | this.name = name; 62 | this.ip = ip; 63 | } 64 | 65 | public Name getName() { 66 | return name; 67 | } 68 | 69 | public void setName(Name name) { 70 | this.name = name; 71 | } 72 | 73 | public Ip getIp() { 74 | return ip; 75 | } 76 | 77 | public void setIp(Ip ip) { 78 | this.ip = ip; 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /grpc-stream-server/src/main/proto/nameServers.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | option java_multiple_files = true; 4 | option java_package = "com.hks.rpc"; 5 | option java_outer_classname = "NameProto"; 6 | option objc_class_prefix = "NSS"; 7 | 8 | package nameservers; 9 | 10 | // 定义服务 11 | service NameServers { 12 | // 服务中的方法,用于根据Name类型的参数获得一系列ip,以流的方式返回 13 | rpc getIpsByName (Name) returns (stream Ip) {} 14 | } 15 | //定义Name消息类型,其中name为其序列为1的字段 16 | message Name { 17 | string name = 1; 18 | } 19 | //定义Ip消息类型,其中ip为其序列为1的字段 20 | message Ip { 21 | string ip = 1; 22 | } -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.hks.rpc 7 | RPC-SkillTree 8 | 0.0.1-SNAPSHOT 9 | pom 10 | 11 | SkillTree 12 | rpc project for Spring Boot 13 | 14 | google-protocol-buffer 15 | google-snappy 16 | 17 | dubbo-api 18 | dubbo-consumer 19 | dubbo-provider 20 | 21 | grpc-api 22 | grpc-consumer 23 | grpc-provider 24 | 25 | thrift-api 26 | thrift-client 27 | thrift-server 28 | 29 | spring-dubbo-api 30 | spring-dubbo-consumer 31 | spring-dubbo-provider 32 | 33 | spring-thrift-api 34 | spring-thrift-client 35 | spring-thrift-common 36 | spring-thrift-server 37 | spring-zookeeper-invoker 38 | spring-zookeeper-register 39 | spring-grpc-common 40 | grpc-stream-client 41 | grpc-stream-server 42 | grpc-stream-double 43 | 44 | 45 | 46 | org.springframework.boot 47 | spring-boot-starter-parent 48 | 2.0.1.RELEASE 49 | 50 | 51 | 52 | 53 | 54 | sonatype-nexus-snapshots 55 | Sonatype Nexus Snapshots 56 | https://oss.sonatype.org/content/repositories/snapshots 57 | 58 | false 59 | 60 | 61 | true 62 | 63 | 64 | 65 | 66 | 67 | UTF-8 68 | UTF-8 69 | 1.8 70 | 1.1.1 71 | 72 | 73 | 74 | 75 | 80 | 81 | 82 | 83 | 84 | 85 | org.apache.maven.plugins 86 | maven-gpg-plugin 87 | 1.1 88 | 89 | 90 | sign-artifacts 91 | verify 92 | 93 | sign 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | -------------------------------------------------------------------------------- /spring-dubbo-api/.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | .sts4-cache 12 | 13 | ### IntelliJ IDEA ### 14 | .idea 15 | *.iws 16 | *.iml 17 | *.ipr 18 | 19 | ### NetBeans ### 20 | /nbproject/private/ 21 | /build/ 22 | /nbbuild/ 23 | /dist/ 24 | /nbdist/ 25 | /.nb-gradle/ -------------------------------------------------------------------------------- /spring-dubbo-api/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.hks 7 | spring-dubbo-api 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | spring-dubbo-api 12 | spring-dubbo-api project for Spring Boot 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 2.1.0.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 1.8 25 | 26 | 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter 31 | 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 | -------------------------------------------------------------------------------- /spring-dubbo-api/src/main/java/com/hks/springdubboapi/SpringDubboApiApplication.java: -------------------------------------------------------------------------------- 1 | package com.hks.springdubboapi; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class SpringDubboApiApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(SpringDubboApiApplication.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /spring-dubbo-api/src/main/java/com/hks/springdubboapi/service/HelloWorldService.java: -------------------------------------------------------------------------------- 1 | package com.hks.springdubboapi.service; 2 | 3 | /** 4 | * @Author: hekuangsheng 5 | * @Date: 2018/11/14 6 | */ 7 | public interface HelloWorldService { 8 | 9 | String sayHello(String name); 10 | 11 | } 12 | -------------------------------------------------------------------------------- /spring-dubbo-api/src/main/resources/application.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/singgel/RPC-SkillTree/67bfbc076b18bca17850c64fd2a935fdcd88d9ee/spring-dubbo-api/src/main/resources/application.properties -------------------------------------------------------------------------------- /spring-dubbo-api/src/test/java/com/hks/springdubboapi/SpringDubboApiApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.hks.springdubboapi; 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 SpringDubboApiApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /spring-dubbo-consumer/.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | .sts4-cache 12 | 13 | ### IntelliJ IDEA ### 14 | .idea 15 | *.iws 16 | *.iml 17 | *.ipr 18 | 19 | ### NetBeans ### 20 | /nbproject/private/ 21 | /build/ 22 | /nbbuild/ 23 | /dist/ 24 | /nbdist/ 25 | /.nb-gradle/ -------------------------------------------------------------------------------- /spring-dubbo-consumer/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.hks 7 | spring-dubbo-consumer 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | spring-dubbo-consumer 12 | spring-dubbo-consumer project for Spring Boot 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 2.1.0.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 1.8 25 | 26 | 2.5.6 27 | 1.2.31 28 | 3.20.0-GA 29 | 3.2.5.Final 30 | 3.4.9 31 | 0.2 32 | 2.12.0 33 | 1.2.16 34 | 35 | 1.7.25 36 | 1.2 37 | 38 | 2.1.0.RELEASE 39 | 40 | 41 | 42 | 43 | com.hks 44 | spring-dubbo-api 45 | 0.0.1-SNAPSHOT 46 | 47 | 48 | org.springframework.boot 49 | spring-boot-starter-test 50 | test 51 | ${org_springframework_boot} 52 | 53 | 54 | org.springframework.boot 55 | spring-boot-starter-web 56 | ${org_springframework_boot} 57 | 58 | 59 | 60 | com.alibaba 61 | dubbo 62 | ${com.alibaba.dubbo.version} 63 | 64 | 65 | commons-logging 66 | commons-logging 67 | 68 | 69 | org.springframework 70 | spring 71 | 72 | 73 | org.jboass.netty 74 | netty 75 | 76 | 77 | org.javassist 78 | javassist 79 | 80 | 81 | 82 | 83 | com.alibaba 84 | fastjson 85 | ${fastjson_version} 86 | 87 | 88 | 89 | org.javassist 90 | javassist 91 | ${javassist_version} 92 | 93 | 94 | org.apache.zookeeper 95 | zookeeper 96 | ${zookeeper_version} 97 | 98 | 99 | slf4j-log4j12 100 | org.slf4j 101 | 102 | 103 | log4j 104 | log4j 105 | 106 | 107 | 108 | 109 | com.101tec 110 | zkclient 111 | ${zkclient_version} 112 | 113 | 114 | zookeeper 115 | org.apache.zookeeper 116 | 117 | 118 | 119 | 120 | 121 | log4j 122 | log4j 123 | ${log4j_version} 124 | 125 | 126 | org.slf4j 127 | slf4j-api 128 | ${slf4j_version} 129 | 130 | 131 | commons-logging 132 | commons-logging 133 | ${commons-logging} 134 | 135 | 136 | 137 | 138 | 139 | 140 | org.springframework.boot 141 | spring-boot-maven-plugin 142 | 143 | 144 | 145 | 146 | 147 | 148 | -------------------------------------------------------------------------------- /spring-dubbo-consumer/src/main/java/com/hks/springdubboconsumer/SpringDubboConsumerApplication.java: -------------------------------------------------------------------------------- 1 | package com.hks.springdubboconsumer; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.context.annotation.ComponentScan; 6 | 7 | @SpringBootApplication 8 | @ComponentScan(value = {"com.hks"}) 9 | public class SpringDubboConsumerApplication { 10 | 11 | public static void main(String[] args) { 12 | SpringApplication.run(SpringDubboConsumerApplication.class, args); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /spring-dubbo-consumer/src/main/java/com/hks/springdubboconsumer/config/PropertiesConfig.java: -------------------------------------------------------------------------------- 1 | package com.hks.springdubboconsumer.config; 2 | 3 | import org.springframework.context.annotation.Configuration; 4 | import org.springframework.context.annotation.ImportResource; 5 | import org.springframework.context.annotation.PropertySource; 6 | 7 | /** 8 | * @Author: hekuangsheng 9 | * @Date: 2018/11/14 10 | * 11 | * 描述: 加载配置 12 | */ 13 | @Configuration 14 | @PropertySource("classpath:dubbo.properties") 15 | @ImportResource({"classpath:dubbo/*.xml"}) 16 | public class PropertiesConfig { 17 | } 18 | -------------------------------------------------------------------------------- /spring-dubbo-consumer/src/main/java/com/hks/springdubboconsumer/controller/HelloWoldConsumerController.java: -------------------------------------------------------------------------------- 1 | package com.hks.springdubboconsumer.controller; 2 | 3 | import com.hks.springdubboapi.service.HelloWorldService; 4 | import org.springframework.web.bind.annotation.RequestMapping; 5 | import org.springframework.web.bind.annotation.RequestMethod; 6 | import org.springframework.web.bind.annotation.RequestParam; 7 | import org.springframework.web.bind.annotation.RestController; 8 | 9 | import javax.annotation.Resource; 10 | 11 | /** 12 | * @Author: hekuangsheng 13 | * @Date: 2018/11/14 14 | */ 15 | @RestController 16 | public class HelloWoldConsumerController { 17 | 18 | @Resource 19 | private HelloWorldService helloWorldService; 20 | 21 | @RequestMapping("/sayHello") 22 | public String sayHello(@RequestParam String name) { 23 | return helloWorldService.sayHello(name); 24 | } 25 | 26 | @RequestMapping(value = "hello", method = RequestMethod.GET) 27 | public String hello(){ 28 | return "hello"; 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /spring-dubbo-consumer/src/main/java/com/hks/springdubboconsumer/service/ConsumerDemoService.java: -------------------------------------------------------------------------------- 1 | package com.hks.springdubboconsumer.service; 2 | 3 | import com.hks.springdubboapi.service.HelloWorldService; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.stereotype.Service; 6 | 7 | import java.lang.annotation.Target; 8 | 9 | /** 10 | * @Author: hekuangsheng 11 | * @Date: 2018/11/14 12 | * 13 | * 描述: 消费远程方法 14 | */ 15 | @Service("consumerDemoService") 16 | public class ConsumerDemoService { 17 | 18 | @Autowired 19 | private HelloWorldService helloWorldService; 20 | 21 | public void sayHello(String name) { 22 | String hello = helloWorldService.sayHello(name); // 执行消费远程方法 23 | System.out.println(hello); // 显示调用结果 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /spring-dubbo-consumer/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.application.name=dubbo-consumer 2 | server.port=8020 3 | server.tomcat.max-threads=1000 4 | server.tomcat.max-connections=2000 -------------------------------------------------------------------------------- /spring-dubbo-consumer/src/main/resources/dubbo.properties: -------------------------------------------------------------------------------- 1 | ######################################################### 2 | # dubbo config 3 | #暴露服务端口 4 | dubbo.protocol.port=20880 5 | #提供方超时时间 6 | dubbo.provider.timeout=10000 7 | #提供方版本 8 | dubbo.provider.version=1.0 9 | #表示该服务使用独的五条条长连 10 | dubbo.provider.connections=5 11 | # 固定大小线程池,启动时建立线程,不关闭,一直持有。(缺省) 12 | dubbo.protocol.threadpool=fixed 13 | # 线程数量 14 | dubbo.protocol.threads=500 15 | #配置重试次数,最好只用于读的重试,写操作可能会引起多次写入 默认retries="0" 16 | dubbo.provider.retries=0 17 | # dubbo缓存文件 18 | dubbo.cache=./data/dubbo/cache/dubbo-provider 19 | ######################################################### 20 | # zookeeper config 21 | zookeeper.connect=127.0.0.1:2181 -------------------------------------------------------------------------------- /spring-dubbo-consumer/src/main/resources/dubbo/dubbo-consumer.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /spring-dubbo-consumer/src/main/resources/dubbo/dubbo.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /spring-dubbo-consumer/src/main/resources/log4j.properties: -------------------------------------------------------------------------------- 1 | ###set log levels### 2 | log4j.rootLogger=debug, stdout 3 | ###输出到控制台### 4 | log4j.appender.stdout=org.apache.log4j.ConsoleAppender 5 | log4j.appender.stdout.Target=System.out 6 | log4j.appender.stdout.layout=org.apache.log4j.PatternLayout 7 | log4j.appender.stdout.layout.ConversionPattern=[%d{dd/MM/yy hh:mm:ss:sss z}] %t %5p %c{2}: %m%n -------------------------------------------------------------------------------- /spring-dubbo-consumer/src/test/java/com/hks/springdubboconsumer/SpringDubboConsumerApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.hks.springdubboconsumer; 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 SpringDubboConsumerApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /spring-dubbo-provider/.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | .sts4-cache 12 | 13 | ### IntelliJ IDEA ### 14 | .idea 15 | *.iws 16 | *.iml 17 | *.ipr 18 | 19 | ### NetBeans ### 20 | /nbproject/private/ 21 | /build/ 22 | /nbbuild/ 23 | /dist/ 24 | /nbdist/ 25 | /.nb-gradle/ -------------------------------------------------------------------------------- /spring-dubbo-provider/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.hks 7 | spring-dubbo-provider 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | spring-dubbo-provider 12 | spring-dubbo-provider project for Spring Boot 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 2.1.0.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 1.8 25 | 26 | 2.5.6 27 | 1.2.31 28 | 3.20.0-GA 29 | 3.2.5.Final 30 | 3.4.9 31 | 0.2 32 | 2.12.0 33 | 1.2.16 34 | 35 | 1.7.25 36 | 1.2 37 | 38 | 2.1.0.RELEASE 39 | 40 | 41 | 42 | 43 | com.hks 44 | spring-dubbo-api 45 | 0.0.1-SNAPSHOT 46 | 47 | 48 | org.springframework.boot 49 | spring-boot-starter-test 50 | test 51 | ${org_springframework_boot} 52 | 53 | 54 | org.springframework.boot 55 | spring-boot-starter-web 56 | ${org_springframework_boot} 57 | 58 | 59 | 60 | com.alibaba 61 | dubbo 62 | ${com.alibaba.dubbo.version} 63 | 64 | 65 | commons-logging 66 | commons-logging 67 | 68 | 69 | org.springframework 70 | spring 71 | 72 | 73 | org.jboass.netty 74 | netty 75 | 76 | 77 | org.javassist 78 | javassist 79 | 80 | 81 | 82 | 83 | com.alibaba 84 | fastjson 85 | ${fastjson_version} 86 | 87 | 88 | 89 | org.javassist 90 | javassist 91 | ${javassist_version} 92 | 93 | 94 | org.apache.zookeeper 95 | zookeeper 96 | ${zookeeper_version} 97 | 98 | 99 | slf4j-log4j12 100 | org.slf4j 101 | 102 | 103 | log4j 104 | log4j 105 | 106 | 107 | 108 | 109 | com.101tec 110 | zkclient 111 | ${zkclient_version} 112 | 113 | 114 | zookeeper 115 | org.apache.zookeeper 116 | 117 | 118 | 119 | 120 | 121 | log4j 122 | log4j 123 | ${log4j_version} 124 | 125 | 126 | org.slf4j 127 | slf4j-api 128 | ${slf4j_version} 129 | 130 | 131 | commons-logging 132 | commons-logging 133 | ${commons-logging} 134 | 135 | 136 | 137 | 138 | 139 | 140 | org.springframework.boot 141 | spring-boot-maven-plugin 142 | 143 | 144 | 145 | 146 | 147 | 148 | -------------------------------------------------------------------------------- /spring-dubbo-provider/src/main/java/com/hks/springdubboprovider/SpringDubboProviderApplication.java: -------------------------------------------------------------------------------- 1 | package com.hks.springdubboprovider; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.context.annotation.ComponentScan; 6 | 7 | @SpringBootApplication 8 | @ComponentScan(value = {"com.hks"}) 9 | public class SpringDubboProviderApplication { 10 | 11 | public static void main(String[] args) { 12 | SpringApplication.run(SpringDubboProviderApplication.class, args); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /spring-dubbo-provider/src/main/java/com/hks/springdubboprovider/config/PropertiesConfig.java: -------------------------------------------------------------------------------- 1 | package com.hks.springdubboprovider.config; 2 | 3 | import org.springframework.context.annotation.Configuration; 4 | import org.springframework.context.annotation.ImportResource; 5 | import org.springframework.context.annotation.PropertySource; 6 | 7 | /** 8 | * @Author: hekuangsheng 9 | * @Date: 2018/11/14 10 | * 11 | * 描述: 加载配置 12 | */ 13 | @Configuration 14 | @PropertySource("classpath:dubbo.properties") 15 | @ImportResource({"classpath:dubbo/*.xml"}) 16 | public class PropertiesConfig { 17 | } 18 | -------------------------------------------------------------------------------- /spring-dubbo-provider/src/main/java/com/hks/springdubboprovider/service/HelloWorldServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.hks.springdubboprovider.service; 2 | 3 | import com.alibaba.dubbo.rpc.RpcContext; 4 | import com.hks.springdubboapi.service.HelloWorldService; 5 | import org.springframework.stereotype.Service; 6 | 7 | import java.text.SimpleDateFormat; 8 | import java.util.Date; 9 | 10 | /** 11 | * @Author: hekuangsheng 12 | * @Date: 2018/11/14 13 | * 14 | * 描述: 提供方实现 15 | */ 16 | @Service("helloWorldService") 17 | public class HelloWorldServiceImpl implements HelloWorldService { 18 | 19 | @Override 20 | public String sayHello(String name) { 21 | System.out.println("[" + new SimpleDateFormat("HH:mm:ss").format(new Date()) + "] Hello " + name + ", request from consumer: " + RpcContext.getContext().getRemoteAddress()); 22 | return "Hello " + name + ", response form provider: " + RpcContext.getContext().getLocalAddress(); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /spring-dubbo-provider/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.application.name=dubbo-provider 2 | server.port=8084 3 | server.tomcat.max-threads=1000 4 | server.tomcat.max-connections=2000 -------------------------------------------------------------------------------- /spring-dubbo-provider/src/main/resources/dubbo.properties: -------------------------------------------------------------------------------- 1 | ######################################################### 2 | # dubbo config 3 | #暴露服务端口 4 | dubbo.protocol.port=20880 5 | #提供方超时时间 6 | dubbo.provider.timeout=10000 7 | #提供方版本 8 | dubbo.provider.version=1.0 9 | #表示该服务使用独的五条条长连 10 | dubbo.provider.connections=5 11 | # 固定大小线程池,启动时建立线程,不关闭,一直持有。(缺省) 12 | dubbo.protocol.threadpool=fixed 13 | # 线程数量 14 | dubbo.protocol.threads=500 15 | #配置重试次数,最好只用于读的重试,写操作可能会引起多次写入 默认retries="0" 16 | dubbo.provider.retries=0 17 | # dubbo缓存文件 18 | dubbo.cache=./data/dubbo/cache/dubbo-provider 19 | ######################################################### 20 | # zookeeper config 21 | zookeeper.connect=127.0.0.1:2181 -------------------------------------------------------------------------------- /spring-dubbo-provider/src/main/resources/dubbo/dubbo-provider.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /spring-dubbo-provider/src/main/resources/dubbo/dubbo.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /spring-dubbo-provider/src/main/resources/log4j.properties: -------------------------------------------------------------------------------- 1 | ###set log levels### 2 | log4j.rootLogger=debug, stdout 3 | ###输出到控制台### 4 | log4j.appender.stdout=org.apache.log4j.ConsoleAppender 5 | log4j.appender.stdout.Target=System.out 6 | log4j.appender.stdout.layout=org.apache.log4j.PatternLayout 7 | log4j.appender.stdout.layout.ConversionPattern=[%d{dd/MM/yy hh:mm:ss:sss z}] %t %5p %c{2}: %m%n -------------------------------------------------------------------------------- /spring-dubbo-provider/src/test/java/com/hks/springdubboprovider/SpringDubboProviderApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.hks.springdubboprovider; 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 SpringDubboProviderApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /spring-grpc-common/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | RPC-SkillTree 7 | com.hks.rpc 8 | 0.0.1-SNAPSHOT 9 | 10 | 4.0.0 11 | 12 | spring-grpc-common 13 | 14 | 15 | -------------------------------------------------------------------------------- /spring-grpc-common/src/main/resources/META-INF/spring.factories: -------------------------------------------------------------------------------- 1 | # AutoConfiguration 2 | org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ 3 | net.devh.boot.grpc.common.autoconfigure.GrpcCommonCodecAutoConfiguration,\ 4 | net.devh.boot.grpc.common.autoconfigure.GrpcCommonTraceAutoConfiguration -------------------------------------------------------------------------------- /spring-thrift-api/.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | .sts4-cache 12 | 13 | ### IntelliJ IDEA ### 14 | .idea 15 | *.iws 16 | *.iml 17 | *.ipr 18 | 19 | ### NetBeans ### 20 | /nbproject/private/ 21 | /build/ 22 | /nbbuild/ 23 | /dist/ 24 | /nbdist/ 25 | /.nb-gradle/ -------------------------------------------------------------------------------- /spring-thrift-api/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.hks 7 | spring-thrift-api 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | spring-thrift-api 12 | spring-thrift-api project for Spring Boot 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 2.1.0.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 1.8 25 | 26 | 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter 31 | 32 | 33 | org.apache.thrift 34 | libthrift 35 | 0.11.0 36 | 37 | 38 | org.springframework.boot 39 | spring-boot-starter-test 40 | test 41 | 42 | 43 | 44 | 45 | 46 | 47 | org.springframework.boot 48 | spring-boot-maven-plugin 49 | 50 | 51 | 52 | 53 | 54 | 55 | -------------------------------------------------------------------------------- /spring-thrift-api/src/main/java/com/hks/springthriftapi/SpringThriftApiApplication.java: -------------------------------------------------------------------------------- 1 | package com.hks.springthriftapi; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class SpringThriftApiApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(SpringThriftApiApplication.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /spring-thrift-api/src/main/resources/application.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/singgel/RPC-SkillTree/67bfbc076b18bca17850c64fd2a935fdcd88d9ee/spring-thrift-api/src/main/resources/application.properties -------------------------------------------------------------------------------- /spring-thrift-api/src/main/thrift/User.thrift: -------------------------------------------------------------------------------- 1 | namespace java com.hks.springthriftapi.service 2 | service HelloWorldService { 3 | string sayHello(1:string username) 4 | string getRandom() 5 | } -------------------------------------------------------------------------------- /spring-thrift-api/src/test/java/com/hks/springthriftapi/SpringThriftApiApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.hks.springthriftapi; 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 SpringThriftApiApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /spring-thrift-client/.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | .sts4-cache 12 | 13 | ### IntelliJ IDEA ### 14 | .idea 15 | *.iws 16 | *.iml 17 | *.ipr 18 | 19 | ### NetBeans ### 20 | /nbproject/private/ 21 | /build/ 22 | /nbbuild/ 23 | /dist/ 24 | /nbdist/ 25 | /.nb-gradle/ -------------------------------------------------------------------------------- /spring-thrift-client/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.hks 7 | spring-thrift-client 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | spring-thrift-client 12 | spring-thrift-client project for Spring Boot 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 2.1.0.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 1.8 25 | 26 | 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter 31 | 32 | 33 | 34 | org.springframework.boot 35 | spring-boot-starter-test 36 | test 37 | 38 | 39 | com.hks 40 | spring-thrift-api 41 | 0.0.1-SNAPSHOT 42 | 43 | 44 | com.hks 45 | spring-thrift-common 46 | 0.0.1-SNAPSHOT 47 | 48 | 49 | 50 | 51 | 52 | 53 | org.springframework.boot 54 | spring-boot-maven-plugin 55 | 56 | 57 | 58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /spring-thrift-client/src/main/java/com/hks/springthriftclient/SpringThriftClientApplication.java: -------------------------------------------------------------------------------- 1 | package com.hks.springthriftclient; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class SpringThriftClientApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(SpringThriftClientApplication.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /spring-thrift-client/src/main/java/com/hks/springthriftclient/config/ThriftClientConfig.java: -------------------------------------------------------------------------------- 1 | package com.hks.springthriftclient.config; 2 | 3 | import com.hks.springthriftcommon.thrift.ThriftServiceClientProxyFactory; 4 | import com.hks.springthriftcommon.zookeeper.ZookeeperFactory; 5 | import com.hks.springthriftcommon.zookeeper.impl.ThriftServerAddressProviderZookeeper; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.context.annotation.Configuration; 8 | 9 | /** 10 | * @Author: hekuangsheng 11 | * @Date: 2018/11/14 12 | */ 13 | @Configuration 14 | public class ThriftClientConfig { 15 | 16 | @Bean 17 | public ZookeeperFactory zookeeperFactory() { 18 | ZookeeperFactory zookeeperFactory = new ZookeeperFactory(); 19 | zookeeperFactory.setZkHosts("127.0.0.1:2181"); 20 | zookeeperFactory.setNamespace("com.thrift.api"); 21 | zookeeperFactory.setConnectionTimeout(3000); 22 | zookeeperFactory.setSessionTimeout(3000); 23 | zookeeperFactory.setSingleton(true); 24 | return zookeeperFactory; 25 | } 26 | 27 | @Bean 28 | public ThriftServerAddressProviderZookeeper thriftServerAddressProviderZookeeper() { 29 | ThriftServerAddressProviderZookeeper tsapz = new ThriftServerAddressProviderZookeeper(); 30 | tsapz.setService("com.hks.springthriftapi.service.HelloWorldService"); 31 | tsapz.setVersion("1.0.0"); 32 | try { 33 | tsapz.setZkClient(zookeeperFactory().getObject()); 34 | } catch (Exception e) { 35 | System.out.println(e.getMessage()); 36 | } 37 | return tsapz; 38 | } 39 | 40 | @Bean 41 | public ThriftServiceClientProxyFactory thriftServiceClientProxyFactory() { 42 | ThriftServiceClientProxyFactory tscpf = new ThriftServiceClientProxyFactory(); 43 | tscpf.setMaxActive(5); 44 | tscpf.setIdleTime(1800000); 45 | tscpf.setServerAddressProvider(thriftServerAddressProviderZookeeper()); 46 | return tscpf; 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /spring-thrift-client/src/main/java/com/hks/springthriftclient/controller/HelloWordController.java: -------------------------------------------------------------------------------- 1 | package com.hks.springthriftclient.controller; 2 | 3 | import com.hks.springthriftapi.service.HelloWorldService; 4 | import com.hks.springthriftclient.util.ApplicationContextUtil; 5 | import org.springframework.stereotype.Controller; 6 | import org.springframework.web.bind.annotation.RequestMapping; 7 | import org.springframework.web.bind.annotation.ResponseBody; 8 | 9 | /** 10 | * @Author: hekuangsheng 11 | * @Date: 2018/11/14 12 | */ 13 | @Controller 14 | public class HelloWordController { 15 | @ResponseBody 16 | @RequestMapping(value = "/hello") 17 | public String hello() { 18 | try { 19 | HelloWorldService.Iface userBussiness = (HelloWorldService.Iface) ApplicationContextUtil.getBean("thriftServiceClientProxyFactory"); 20 | String str = userBussiness.sayHello("hihao"); 21 | System.out.println(str); 22 | return str; 23 | } catch (Exception e) { 24 | e.printStackTrace(); 25 | } 26 | return ""; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /spring-thrift-client/src/main/java/com/hks/springthriftclient/util/ApplicationContextUtil.java: -------------------------------------------------------------------------------- 1 | package com.hks.springthriftclient.util; 2 | 3 | import org.springframework.beans.BeansException; 4 | import org.springframework.context.ApplicationContext; 5 | import org.springframework.context.ApplicationContextAware; 6 | import org.springframework.stereotype.Component; 7 | 8 | /** 9 | * @Author: hekuangsheng 10 | * @Date: 2018/11/14 11 | */ 12 | @Component 13 | public class ApplicationContextUtil implements ApplicationContextAware { 14 | 15 | private static ApplicationContext applicationContext; 16 | 17 | @Override 18 | public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { 19 | this.applicationContext = applicationContext; 20 | } 21 | 22 | public static ApplicationContext getContext() { 23 | return applicationContext; 24 | } 25 | 26 | public final static Object getBean(String beanName) { 27 | return applicationContext.getBean(beanName); 28 | } 29 | 30 | public final static Object getBean(String beanName, Class requiredType) { 31 | return applicationContext.getBean(beanName, requiredType); 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /spring-thrift-client/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | server.port=8020 -------------------------------------------------------------------------------- /spring-thrift-client/src/test/java/com/hks/springthriftclient/SpringThriftClientApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.hks.springthriftclient; 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 SpringThriftClientApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /spring-thrift-common/.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | .sts4-cache 12 | 13 | ### IntelliJ IDEA ### 14 | .idea 15 | *.iws 16 | *.iml 17 | *.ipr 18 | 19 | ### NetBeans ### 20 | /nbproject/private/ 21 | /build/ 22 | /nbbuild/ 23 | /dist/ 24 | /nbdist/ 25 | /.nb-gradle/ -------------------------------------------------------------------------------- /spring-thrift-common/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.hks 7 | spring-thrift-common 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | spring-thrift-common 12 | spring-thrift-common project for Spring Boot 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 2.1.0.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 1.8 25 | 26 | 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter 31 | 32 | 33 | 34 | org.springframework.boot 35 | spring-boot-starter-test 36 | test 37 | 38 | 39 | 40 | org.springframework.boot 41 | spring-boot-starter-web 42 | 43 | 44 | 45 | org.apache.curator 46 | curator-recipes 47 | 2.7.1 48 | 49 | 50 | 51 | commons-pool 52 | commons-pool 53 | 1.6 54 | 55 | 56 | 57 | org.apache.thrift 58 | libthrift 59 | 0.11.0 60 | 61 | 62 | 63 | 64 | 65 | 66 | org.springframework.boot 67 | spring-boot-maven-plugin 68 | 69 | 70 | 71 | 72 | 73 | 74 | -------------------------------------------------------------------------------- /spring-thrift-common/src/main/java/com/hks/springthriftcommon/SpringThriftCommonApplication.java: -------------------------------------------------------------------------------- 1 | package com.hks.springthriftcommon; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class SpringThriftCommonApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(SpringThriftCommonApplication.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /spring-thrift-common/src/main/java/com/hks/springthriftcommon/exception/ThriftException.java: -------------------------------------------------------------------------------- 1 | package com.hks.springthriftcommon.exception; 2 | 3 | /** 4 | * @Author: hekuangsheng 5 | * @Date: 2018/11/13 6 | */ 7 | public class ThriftException extends RuntimeException { 8 | public ThriftException() { 9 | super(); 10 | } 11 | 12 | public ThriftException(String msg) { 13 | super(msg); 14 | } 15 | 16 | public ThriftException(Throwable e) { 17 | super(e); 18 | } 19 | 20 | public ThriftException(String msg, Throwable e) { 21 | super(msg, e); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /spring-thrift-common/src/main/java/com/hks/springthriftcommon/thrift/PoolOperationCallBack.java: -------------------------------------------------------------------------------- 1 | package com.hks.springthriftcommon.thrift; 2 | 3 | import org.apache.thrift.TServiceClient; 4 | 5 | /** 6 | * @Author: hekuangsheng 7 | * @Date: 2018/11/13 8 | */ 9 | public interface PoolOperationCallBack { 10 | // 创建成功是执行 11 | void make(TServiceClient client); 12 | 13 | // 销毁client之前执行 14 | void destroy(TServiceClient client); 15 | } 16 | -------------------------------------------------------------------------------- /spring-thrift-common/src/main/java/com/hks/springthriftcommon/thrift/ThriftClientPoolFactory.java: -------------------------------------------------------------------------------- 1 | package com.hks.springthriftcommon.thrift; 2 | 3 | import com.hks.springthriftcommon.exception.ThriftException; 4 | import com.hks.springthriftcommon.zookeeper.ThriftServerAddressProvider; 5 | import org.apache.commons.pool.BasePoolableObjectFactory; 6 | import org.apache.thrift.TServiceClient; 7 | import org.apache.thrift.TServiceClientFactory; 8 | import org.apache.thrift.protocol.TBinaryProtocol; 9 | import org.apache.thrift.protocol.TProtocol; 10 | import org.apache.thrift.transport.TFramedTransport; 11 | import org.apache.thrift.transport.TSocket; 12 | import org.apache.thrift.transport.TTransport; 13 | import org.slf4j.Logger; 14 | import org.slf4j.LoggerFactory; 15 | 16 | import java.net.InetSocketAddress; 17 | 18 | /** 19 | * @Author: hekuangsheng 20 | * @Date: 2018/11/13 21 | * 22 | * 连接池,thrift-client for spring 23 | */ 24 | public class ThriftClientPoolFactory extends BasePoolableObjectFactory { 25 | 26 | private Logger logger = LoggerFactory.getLogger(getClass()); 27 | 28 | private final ThriftServerAddressProvider serverAddressProvider; 29 | private final TServiceClientFactory clientFactory; 30 | private PoolOperationCallBack callback; 31 | 32 | protected ThriftClientPoolFactory(ThriftServerAddressProvider addressProvider, TServiceClientFactory clientFactory) throws Exception { 33 | this.serverAddressProvider = addressProvider; 34 | this.clientFactory = clientFactory; 35 | } 36 | 37 | protected ThriftClientPoolFactory(ThriftServerAddressProvider addressProvider, TServiceClientFactory clientFactory, 38 | PoolOperationCallBack callback) throws Exception { 39 | this.serverAddressProvider = addressProvider; 40 | this.clientFactory = clientFactory; 41 | this.callback = callback; 42 | } 43 | 44 | /** 45 | * 检测对象是否有效 46 | * 47 | * @param client 48 | * @return 49 | */ 50 | @Override 51 | public boolean validateObject(TServiceClient client) { 52 | TTransport pin = client.getInputProtocol().getTransport(); 53 | logger.info("validateObject input:{}", pin.isOpen()); 54 | TTransport pout = client.getOutputProtocol().getTransport(); 55 | logger.info("validateObject output:{}", pout.isOpen()); 56 | return pin.isOpen() && pout.isOpen(); 57 | } 58 | 59 | /** 60 | * 创建一个新对象TServiceClient 61 | * 62 | * @return 63 | * @throws Exception 64 | */ 65 | @Override 66 | public TServiceClient makeObject() throws Exception { 67 | InetSocketAddress address = serverAddressProvider.selector(); 68 | if (address == null) { 69 | new ThriftException("No provider available for remote api"); 70 | } 71 | TSocket tsocket = new TSocket(address.getHostName(), address.getPort()); 72 | TTransport transport = new TFramedTransport(tsocket); 73 | TProtocol protocol = new TBinaryProtocol(transport); 74 | TServiceClient client = this.clientFactory.getClient(protocol); 75 | transport.open(); 76 | if (callback != null) { 77 | try { 78 | callback.make(client); 79 | } catch (Exception e) { 80 | logger.error("makeObject:{}", e); 81 | } 82 | } 83 | return client; 84 | } 85 | 86 | /** 87 | * 销毁对象 88 | * 89 | * @param client 90 | * @throws Exception 91 | */ 92 | @Override 93 | public void destroyObject(TServiceClient client) throws Exception { 94 | if (callback != null) { 95 | try { 96 | callback.destroy(client); 97 | } catch (Exception e) { 98 | logger.warn("destroyObject:{}", e); 99 | } 100 | } 101 | logger.info("destroyObject:{}", client); 102 | TTransport pin = client.getInputProtocol().getTransport(); 103 | pin.close(); 104 | TTransport pout = client.getOutputProtocol().getTransport(); 105 | pout.close(); 106 | } 107 | 108 | @Override 109 | public void activateObject(TServiceClient client) throws Exception { 110 | } 111 | 112 | @Override 113 | public void passivateObject(TServiceClient client) throws Exception { 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /spring-thrift-common/src/main/java/com/hks/springthriftcommon/thrift/ThriftServiceClient2Proxy.java: -------------------------------------------------------------------------------- 1 | package com.hks.springthriftcommon.thrift; 2 | 3 | import org.apache.thrift.TServiceClient; 4 | 5 | import java.lang.reflect.InvocationHandler; 6 | import java.lang.reflect.Method; 7 | 8 | /** 9 | * @Author: hekuangsheng 10 | * @Date: 2018/11/13 11 | * 12 | * 客户端代理类 13 | */ 14 | public class ThriftServiceClient2Proxy implements InvocationHandler { 15 | 16 | private TServiceClient client; 17 | 18 | public ThriftServiceClient2Proxy(TServiceClient client) { 19 | this.client = client; 20 | } 21 | 22 | @Override 23 | public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 24 | try { 25 | return method.invoke(client, args); 26 | } catch (Exception e) { 27 | throw e; 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /spring-thrift-common/src/main/java/com/hks/springthriftcommon/thrift/ThriftServiceClientProxy.java: -------------------------------------------------------------------------------- 1 | package com.hks.springthriftcommon.thrift; 2 | 3 | import org.apache.commons.pool.impl.GenericObjectPool; 4 | import org.apache.thrift.TServiceClient; 5 | 6 | import java.lang.reflect.InvocationHandler; 7 | import java.lang.reflect.Method; 8 | 9 | /** 10 | * @Author: hekuangsheng 11 | * @Date: 2018/11/13 12 | * 13 | * 客户端代理类 14 | */ 15 | public class ThriftServiceClientProxy implements InvocationHandler { 16 | 17 | private GenericObjectPool pool; 18 | 19 | private TServiceClient client; 20 | 21 | public ThriftServiceClientProxy(GenericObjectPool pool) { 22 | this.pool = pool; 23 | } 24 | 25 | public ThriftServiceClientProxy(TServiceClient client) { 26 | this.client = client; 27 | } 28 | 29 | @Override 30 | public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 31 | //获取一个对象 32 | TServiceClient client = pool.borrowObject(); 33 | boolean flag = true; 34 | try { 35 | return method.invoke(client, args); 36 | } catch (Exception e) { 37 | flag = false; 38 | throw e; 39 | } finally { 40 | if (flag) { 41 | //归还对象 42 | pool.returnObject(client); 43 | } else { 44 | //标记对象不可再用 45 | pool.invalidateObject(client); 46 | } 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /spring-thrift-common/src/main/java/com/hks/springthriftcommon/thrift/ThriftServiceClientProxyFactory.java: -------------------------------------------------------------------------------- 1 | package com.hks.springthriftcommon.thrift; 2 | 3 | import com.hks.springthriftcommon.exception.ThriftException; 4 | import com.hks.springthriftcommon.zookeeper.ThriftServerAddressProvider; 5 | import org.apache.commons.pool.impl.GenericObjectPool; 6 | import org.apache.thrift.TServiceClient; 7 | import org.apache.thrift.TServiceClientFactory; 8 | import org.slf4j.Logger; 9 | import org.slf4j.LoggerFactory; 10 | import org.springframework.beans.factory.FactoryBean; 11 | import org.springframework.beans.factory.InitializingBean; 12 | 13 | import java.io.Closeable; 14 | import java.io.IOException; 15 | import java.lang.reflect.InvocationHandler; 16 | import java.lang.reflect.Proxy; 17 | 18 | /** 19 | * @Author: hekuangsheng 20 | * @Date: 2018/11/13 21 | * 22 | * 客户端代理工厂 23 | */ 24 | public class ThriftServiceClientProxyFactory implements FactoryBean, InitializingBean, Closeable { 25 | 26 | private Logger logger = LoggerFactory.getLogger(getClass()); 27 | 28 | //最大活跃连接数 29 | private Integer maxActive = 32; 30 | 31 | //ms,default 3 min,链接空闲时间, -1,关闭空闲检测 32 | private Integer idleTime = 180000; 33 | 34 | private ThriftServerAddressProvider serverAddressProvider; 35 | 36 | private Object proxyClient; 37 | 38 | private Class objectClass; 39 | 40 | private GenericObjectPool pool; 41 | 42 | PoolOperationCallBack callback; 43 | 44 | public void setMaxActive(Integer maxActive) { 45 | this.maxActive = maxActive; 46 | } 47 | 48 | public void setIdleTime(Integer idleTime) { 49 | this.idleTime = idleTime; 50 | } 51 | 52 | public void setServerAddressProvider(ThriftServerAddressProvider serverAddressProvider) { 53 | this.serverAddressProvider = serverAddressProvider; 54 | } 55 | 56 | @Override 57 | public void close() { 58 | if (pool != null) { 59 | try { 60 | pool.close(); 61 | } catch (Exception e) { 62 | e.printStackTrace(); 63 | } 64 | } 65 | if (serverAddressProvider != null) { 66 | serverAddressProvider.close(); 67 | } 68 | } 69 | 70 | /** 71 | * 最终返回类型 72 | * 73 | * @return 74 | * @throws Exception 75 | */ 76 | @Override 77 | public Object getObject() throws Exception { 78 | return proxyClient; 79 | } 80 | 81 | /** 82 | * 返回类型的class信息 83 | * 84 | * @return 85 | */ 86 | @Override 87 | public Class getObjectType() { 88 | return objectClass; 89 | } 90 | 91 | /** 92 | * 是否为单例模式 93 | * 94 | * @return 95 | */ 96 | @Override 97 | public boolean isSingleton() { 98 | return true; 99 | } 100 | 101 | /** 102 | * 初始化方法 103 | * 104 | * @throws Exception 105 | */ 106 | @Override 107 | public void afterPropertiesSet() throws Exception { 108 | ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); 109 | // 加载Iface接口 110 | objectClass = classLoader.loadClass(serverAddressProvider.getService() + "$Iface"); 111 | // 加载Client.Factory类 112 | Class> fi = (Class>) classLoader.loadClass(serverAddressProvider.getService() + "$Client$Factory"); 113 | TServiceClientFactory clientFactory = fi.newInstance(); 114 | 115 | ThriftClientPoolFactory clientPool = new ThriftClientPoolFactory(serverAddressProvider, clientFactory, callback); 116 | pool = new GenericObjectPool<>(clientPool, makePoolConfig()); 117 | InvocationHandler handler = makeProxyHandler1();//方式1 118 | //InvocationHandler handler = makeProxyHandler2();//方式2 119 | 120 | proxyClient = Proxy.newProxyInstance(classLoader, new Class[]{objectClass}, handler); 121 | } 122 | 123 | private GenericObjectPool.Config makePoolConfig() { 124 | GenericObjectPool.Config poolConfig = new GenericObjectPool.Config(); 125 | poolConfig.maxActive = maxActive; 126 | //pool中最多能保留多少个空闲对象 127 | poolConfig.maxIdle = 1; 128 | //最少有多少个空闲对象 129 | poolConfig.minIdle = 0; 130 | poolConfig.minEvictableIdleTimeMillis = idleTime; 131 | poolConfig.timeBetweenEvictionRunsMillis = idleTime * 2L; 132 | poolConfig.testOnBorrow = true; 133 | poolConfig.testOnReturn = false; 134 | poolConfig.testWhileIdle = false; 135 | return poolConfig; 136 | } 137 | 138 | private InvocationHandler makeProxyHandler1() throws Exception { 139 | ThriftServiceClientProxy handler = new ThriftServiceClientProxy(pool); 140 | return handler; 141 | } 142 | 143 | private InvocationHandler makeProxyHandler2() throws Exception { 144 | ThriftServiceClient2Proxy handler; 145 | TServiceClient client = pool.borrowObject(); 146 | try { 147 | handler = new ThriftServiceClient2Proxy(client); 148 | pool.returnObject(client); 149 | } catch (Exception e) { 150 | pool.invalidateObject(client); 151 | throw new ThriftException("获取代理对象失败"); 152 | } 153 | return handler; 154 | } 155 | } 156 | -------------------------------------------------------------------------------- /spring-thrift-common/src/main/java/com/hks/springthriftcommon/thrift/ThriftServiceServerFactory.java: -------------------------------------------------------------------------------- 1 | package com.hks.springthriftcommon.thrift; 2 | 3 | import com.hks.springthriftcommon.exception.ThriftException; 4 | import com.hks.springthriftcommon.zookeeper.ThriftServerAddressRegister; 5 | import com.hks.springthriftcommon.zookeeper.ThriftServerIpResolve; 6 | import com.hks.springthriftcommon.zookeeper.impl.ThriftServerIpLocalNetworkResolve; 7 | import org.apache.thrift.TProcessor; 8 | import org.apache.thrift.TProcessorFactory; 9 | import org.apache.thrift.protocol.TBinaryProtocol; 10 | import org.apache.thrift.server.TServer; 11 | import org.apache.thrift.server.TThreadedSelectorServer; 12 | import org.apache.thrift.transport.TFramedTransport; 13 | import org.apache.thrift.transport.TNonblockingServerSocket; 14 | import org.springframework.beans.factory.InitializingBean; 15 | 16 | import java.lang.instrument.IllegalClassFormatException; 17 | import java.lang.reflect.Constructor; 18 | 19 | /** 20 | * @Author: hekuangsheng 21 | * @Date: 2018/11/13 22 | * 23 | * 服务端注册服务工厂 24 | */ 25 | public class ThriftServiceServerFactory implements InitializingBean { 26 | 27 | // 服务注册本机端口 28 | private Integer port = 8299; 29 | // 优先级 30 | private Integer weight = 1; 31 | // 服务实现类 32 | private Object service; 33 | // 服务版本号 34 | private String version; 35 | // 服务注册 36 | private ThriftServerAddressRegister thriftServerAddressRegister; 37 | //解析本机IP 38 | private ThriftServerIpResolve thriftServerIpResolve; 39 | 40 | private ServerThread serverThread; 41 | 42 | public void setPort(Integer port) { 43 | this.port = port; 44 | } 45 | 46 | public void setWeight(Integer weight) { 47 | this.weight = weight; 48 | } 49 | 50 | public void setService(Object service) { 51 | this.service = service; 52 | } 53 | 54 | public void setVersion(String version) { 55 | this.version = version; 56 | } 57 | 58 | public void setThriftServerAddressRegister(ThriftServerAddressRegister thriftServerAddressRegister) { 59 | this.thriftServerAddressRegister = thriftServerAddressRegister; 60 | } 61 | 62 | /** 63 | * 初始化方法 64 | * @throws Exception 65 | */ 66 | @Override 67 | public void afterPropertiesSet() throws Exception { 68 | if (thriftServerIpResolve == null) { 69 | thriftServerIpResolve = new ThriftServerIpLocalNetworkResolve(); 70 | } 71 | String serverIP = thriftServerIpResolve.getServerIp(); 72 | if (serverIP == null || serverIP.equals("")) { 73 | throw new ThriftException("cant find rpc ip..."); 74 | } 75 | String hostname = serverIP + ":" + port + ":" + weight; 76 | Class serviceClass = service.getClass(); 77 | //获取实现类接口 78 | Class[] interfaces = serviceClass.getInterfaces(); 79 | if (interfaces.length == 0) { 80 | throw new IllegalClassFormatException("api-class should implements Iface"); 81 | } 82 | //reflect,load "Processor"; 83 | TProcessor processor = null; 84 | String serviceName = null; 85 | for (Class clazz : interfaces) { 86 | String cname = clazz.getSimpleName(); 87 | if (!cname.equals("Iface")) { 88 | continue; 89 | } 90 | serviceName = clazz.getEnclosingClass().getName(); 91 | String pname = serviceName + "$Processor"; 92 | try { 93 | ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); 94 | Class pclass = classLoader.loadClass(pname); 95 | if (!TProcessor.class.isAssignableFrom(pclass)) { 96 | continue; 97 | } 98 | Constructor constructor = pclass.getConstructor(clazz); 99 | processor = (TProcessor) constructor.newInstance(service); 100 | break; 101 | } catch (Exception e) { 102 | // 103 | } 104 | } 105 | if (processor == null) { 106 | throw new IllegalClassFormatException("api-class should implements Iface"); 107 | } 108 | //需要单独的线程,因为serve方法是阻塞的. 109 | serverThread = new ServerThread(processor, port); 110 | serverThread.start(); 111 | // 注册服务 112 | if (thriftServerAddressRegister != null) { 113 | thriftServerAddressRegister.register(serviceName, version, hostname); 114 | } 115 | } 116 | 117 | class ServerThread extends Thread { 118 | private TServer server; 119 | 120 | ServerThread(TProcessor processor, int port) throws Exception { 121 | TNonblockingServerSocket serverTransport = new TNonblockingServerSocket(port); 122 | TThreadedSelectorServer.Args tArgs = new TThreadedSelectorServer.Args(serverTransport); 123 | TProcessorFactory processorFactory = new TProcessorFactory(processor); 124 | tArgs.processorFactory(processorFactory); 125 | tArgs.transportFactory(new TFramedTransport.Factory()); 126 | tArgs.protocolFactory(new TBinaryProtocol.Factory(true, true)); 127 | server = new TThreadedSelectorServer(tArgs); 128 | } 129 | 130 | @Override 131 | public void run() { 132 | try { 133 | //启动服务 134 | server.serve(); 135 | } catch (Exception e) { 136 | // 137 | } 138 | } 139 | 140 | public void stopServer() { 141 | server.stop(); 142 | } 143 | } 144 | 145 | public void close() { 146 | serverThread.stopServer(); 147 | } 148 | } 149 | -------------------------------------------------------------------------------- /spring-thrift-common/src/main/java/com/hks/springthriftcommon/thrift/impl/PoolOperationCallBackImpl.java: -------------------------------------------------------------------------------- 1 | package com.hks.springthriftcommon.thrift.impl; 2 | 3 | import com.hks.springthriftcommon.thrift.PoolOperationCallBack; 4 | import org.apache.thrift.TServiceClient; 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | 8 | /** 9 | * @Author: hekuangsheng 10 | * @Date: 2018/11/13 11 | */ 12 | public class PoolOperationCallBackImpl implements PoolOperationCallBack { 13 | 14 | private Logger logger = LoggerFactory.getLogger(getClass()); 15 | 16 | @Override 17 | public void make(TServiceClient client) { 18 | logger.info("create"); 19 | } 20 | 21 | @Override 22 | public void destroy(TServiceClient client) { 23 | logger.info("destroy"); 24 | } 25 | 26 | } -------------------------------------------------------------------------------- /spring-thrift-common/src/main/java/com/hks/springthriftcommon/zookeeper/ThriftServerAddressProvider.java: -------------------------------------------------------------------------------- 1 | package com.hks.springthriftcommon.zookeeper; 2 | 3 | import java.net.InetSocketAddress; 4 | import java.util.List; 5 | 6 | /** 7 | * @Author: hekuangsheng 8 | * @Date: 2018/11/13 9 | * 10 | * 获取服务地址接口 11 | */ 12 | public interface ThriftServerAddressProvider { 13 | 14 | /** 15 | * 获取服务名称 16 | * 17 | * @return 18 | */ 19 | String getService(); 20 | 21 | /** 22 | * 获取所有服务端地址 23 | * 24 | * @return 25 | */ 26 | List findServerAddressList(); 27 | 28 | /** 29 | * 选取一个合适的address,可以随机获取等,内部可以使用合适的算法. 30 | * 31 | * @return 32 | */ 33 | InetSocketAddress selector(); 34 | 35 | void close(); 36 | 37 | } 38 | -------------------------------------------------------------------------------- /spring-thrift-common/src/main/java/com/hks/springthriftcommon/zookeeper/ThriftServerAddressRegister.java: -------------------------------------------------------------------------------- 1 | package com.hks.springthriftcommon.zookeeper; 2 | 3 | /** 4 | * 发布服务地址及端口到服务注册中心,这里是zookeeper服务器 5 | */ 6 | public interface ThriftServerAddressRegister { 7 | /** 8 | * 发布服务接口 9 | * 10 | * @param service 服务接口名称,一个产品中不能重复 11 | * @param version 服务接口的版本号,默认1.0.0 12 | * @param address 服务发布的地址和端口 13 | */ 14 | void register(String service, String version, String address); 15 | } 16 | -------------------------------------------------------------------------------- /spring-thrift-common/src/main/java/com/hks/springthriftcommon/zookeeper/ThriftServerIpResolve.java: -------------------------------------------------------------------------------- 1 | package com.hks.springthriftcommon.zookeeper; 2 | 3 | /** 4 | * 5 | * 解析thrift-server端IP地址,用于注册服务 6 | * 1) 可以从一个物理机器或者虚机的特殊文件中解析 7 | * 2) 可以获取指定网卡序号的Ip 8 | * 3) 其他 9 | */ 10 | public interface ThriftServerIpResolve { 11 | 12 | String getServerIp() throws Exception; 13 | 14 | void reset(); 15 | 16 | //当IP变更时,将会调用reset方法 17 | interface IpRestCalllBack { 18 | void rest(String newIp); 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /spring-thrift-common/src/main/java/com/hks/springthriftcommon/zookeeper/ZookeeperFactory.java: -------------------------------------------------------------------------------- 1 | package com.hks.springthriftcommon.zookeeper; 2 | 3 | import org.apache.curator.framework.CuratorFramework; 4 | import org.apache.curator.framework.CuratorFrameworkFactory; 5 | import org.apache.curator.retry.ExponentialBackoffRetry; 6 | import org.springframework.beans.factory.FactoryBean; 7 | 8 | /** 9 | * @Author: hekuangsheng 10 | * @Date: 2018/11/13 11 | * 12 | * 获取zookeeper客户端链接 13 | */ 14 | public class ZookeeperFactory implements FactoryBean { 15 | 16 | private String zkHosts; 17 | //session超时 18 | private int sessionTimeout = 30000; 19 | //connection超时 20 | private int connectionTimeout = 30000; 21 | //共享一个zk链接 22 | private boolean singleton = true; 23 | 24 | private CuratorFramework zkClient; 25 | 26 | private final static String ROOT = "rpc"; 27 | //全局path前缀,常用来区分不同的应用 28 | private String namespace; 29 | 30 | //注意一定要实现属性的set方法,否则在spring bean注入的地方会拿不到值 31 | public void setZkHosts(String zkHosts) { 32 | this.zkHosts = zkHosts; 33 | } 34 | 35 | public void setSessionTimeout(int sessionTimeout) { 36 | this.sessionTimeout = sessionTimeout; 37 | } 38 | 39 | public void setConnectionTimeout(int connectionTimeout) { 40 | this.connectionTimeout = connectionTimeout; 41 | } 42 | 43 | public void setSingleton(boolean singleton) { 44 | this.singleton = singleton; 45 | } 46 | 47 | @Override 48 | public boolean isSingleton() { 49 | return singleton; 50 | } 51 | 52 | public void setNamespace(String namespace) { 53 | this.namespace = namespace; 54 | } 55 | 56 | public void setZkClient(CuratorFramework zkClient) { 57 | this.zkClient = zkClient; 58 | } 59 | 60 | @Override 61 | public CuratorFramework getObject() throws Exception { 62 | if (singleton) { 63 | if (zkClient == null) { 64 | zkClient = createCuratorFramework(); 65 | zkClient.start(); 66 | } 67 | return zkClient; 68 | } 69 | return createCuratorFramework(); 70 | } 71 | 72 | private CuratorFramework createCuratorFramework() throws Exception { 73 | if (namespace == null || namespace == "") { 74 | namespace = ROOT; 75 | } else { 76 | namespace = ROOT + "/" + namespace; 77 | } 78 | return createCuratorFramework(zkHosts, sessionTimeout, connectionTimeout, namespace); 79 | } 80 | 81 | public static CuratorFramework createCuratorFramework(String zkHosts, int sessionTimeout, int connectionTimeout, String namespace) { 82 | return CuratorFrameworkFactory.builder() 83 | .connectString(zkHosts) 84 | .sessionTimeoutMs(sessionTimeout) 85 | .connectionTimeoutMs(connectionTimeout) 86 | .canBeReadOnly(true) 87 | .namespace(namespace) 88 | .retryPolicy(new ExponentialBackoffRetry(1000, Integer.MAX_VALUE)) 89 | .defaultData(null) 90 | .build(); 91 | } 92 | 93 | @Override 94 | public Class getObjectType() { 95 | return null; 96 | } 97 | 98 | public void close() { 99 | if (zkClient != null) { 100 | zkClient.close(); 101 | } 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /spring-thrift-common/src/main/java/com/hks/springthriftcommon/zookeeper/impl/ThriftServerAddressRegisterZookeeper.java: -------------------------------------------------------------------------------- 1 | package com.hks.springthriftcommon.zookeeper.impl; 2 | 3 | import com.hks.springthriftcommon.exception.ThriftException; 4 | import com.hks.springthriftcommon.zookeeper.ThriftServerAddressRegister; 5 | import org.apache.curator.framework.CuratorFramework; 6 | import org.apache.curator.framework.imps.CuratorFrameworkState; 7 | import org.apache.zookeeper.CreateMode; 8 | import org.slf4j.Logger; 9 | import org.slf4j.LoggerFactory; 10 | 11 | /** 12 | * @Author: hekuangsheng 13 | * @Date: 2018/11/13 14 | * 15 | * 注册服务列表到Zookeeper 16 | */ 17 | public class ThriftServerAddressRegisterZookeeper implements ThriftServerAddressRegister { 18 | 19 | private Logger logger = LoggerFactory.getLogger(getClass()); 20 | 21 | private CuratorFramework zkClient; 22 | 23 | public ThriftServerAddressRegisterZookeeper() { 24 | } 25 | 26 | public ThriftServerAddressRegisterZookeeper(CuratorFramework zkClient) { 27 | this.zkClient = zkClient; 28 | } 29 | 30 | public void setZkClient(CuratorFramework zkClient) { 31 | this.zkClient = zkClient; 32 | } 33 | 34 | @Override 35 | public void register(String service, String version, String address) { 36 | if (zkClient.getState() == CuratorFrameworkState.LATENT) { 37 | zkClient.start(); 38 | } 39 | if (version == null || version == "") { 40 | version = "1.0.0"; 41 | } 42 | //创建临时节点 43 | try { 44 | zkClient.create() 45 | .creatingParentsIfNeeded() 46 | .withMode(CreateMode.EPHEMERAL) 47 | .forPath("/" + service + "/" + version + "/" + address); 48 | } catch (Exception e) { 49 | logger.error("register api address to zookeeper exception:{}", e); 50 | throw new ThriftException("register api address to zookeeper exception:{}", e); 51 | } 52 | } 53 | 54 | public void close() { 55 | zkClient.close(); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /spring-thrift-common/src/main/java/com/hks/springthriftcommon/zookeeper/impl/ThriftServerIpLocalNetworkResolve.java: -------------------------------------------------------------------------------- 1 | package com.hks.springthriftcommon.zookeeper.impl; 2 | 3 | import com.hks.springthriftcommon.zookeeper.ThriftServerIpResolve; 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | 7 | import java.net.Inet6Address; 8 | import java.net.InetAddress; 9 | import java.net.NetworkInterface; 10 | import java.net.SocketException; 11 | import java.util.Enumeration; 12 | 13 | /** 14 | * @Author: hekuangsheng 15 | * @Date: 2018/11/13 16 | * 17 | * 基于网卡获取IP地址 18 | */ 19 | public class ThriftServerIpLocalNetworkResolve implements ThriftServerIpResolve { 20 | private Logger logger = LoggerFactory.getLogger(getClass()); 21 | 22 | //缓存 23 | private String serverIp; 24 | 25 | @Override 26 | public String getServerIp() throws Exception { 27 | if (serverIp != null) { 28 | return serverIp; 29 | } 30 | // 一个主机有多个网络接口 31 | try { 32 | Enumeration netInterfaces = NetworkInterface.getNetworkInterfaces(); 33 | while (netInterfaces.hasMoreElements()) { 34 | NetworkInterface netInterface = netInterfaces.nextElement(); 35 | // 每个网络接口,都会有多个"网络地址",比如一定会有lookback地址,会有siteLocal地址等.以及IPV4或者IPV6 . 36 | Enumeration addresses = netInterface.getInetAddresses(); 37 | while (addresses.hasMoreElements()) { 38 | InetAddress address = addresses.nextElement(); 39 | if (address instanceof Inet6Address) { 40 | continue; 41 | } 42 | if (address.isSiteLocalAddress() && !address.isLoopbackAddress()) { 43 | serverIp = address.getHostAddress(); 44 | logger.info("resolve rpc ip :" + serverIp); 45 | continue; 46 | } 47 | } 48 | } 49 | } catch (SocketException e) { 50 | e.printStackTrace(); 51 | } 52 | return serverIp; 53 | } 54 | 55 | @Override 56 | public void reset() { 57 | serverIp = null; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /spring-thrift-common/src/main/resources/application.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/singgel/RPC-SkillTree/67bfbc076b18bca17850c64fd2a935fdcd88d9ee/spring-thrift-common/src/main/resources/application.properties -------------------------------------------------------------------------------- /spring-thrift-common/src/test/java/com/hks/springthriftcommon/SpringThriftCommonApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.hks.springthriftcommon; 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 SpringThriftCommonApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /spring-thrift-server/.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | .sts4-cache 12 | 13 | ### IntelliJ IDEA ### 14 | .idea 15 | *.iws 16 | *.iml 17 | *.ipr 18 | 19 | ### NetBeans ### 20 | /nbproject/private/ 21 | /build/ 22 | /nbbuild/ 23 | /dist/ 24 | /nbdist/ 25 | /.nb-gradle/ -------------------------------------------------------------------------------- /spring-thrift-server/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.hks 7 | spring-thrift-server 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | spring-thrift-server 12 | spring-thrift-server project for Spring Boot 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 2.1.0.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 1.8 25 | 26 | 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter-web 31 | 32 | 33 | com.hks 34 | spring-thrift-api 35 | 0.0.1-SNAPSHOT 36 | 37 | 38 | com.hks 39 | spring-thrift-common 40 | 0.0.1-SNAPSHOT 41 | 42 | 43 | org.springframework.boot 44 | spring-boot-starter-test 45 | test 46 | 47 | 48 | 49 | 50 | 51 | 52 | org.springframework.boot 53 | spring-boot-maven-plugin 54 | 55 | 56 | 57 | 58 | 59 | 60 | -------------------------------------------------------------------------------- /spring-thrift-server/src/main/java/com/hks/springthriftserver/SpringThriftServerApplication.java: -------------------------------------------------------------------------------- 1 | package com.hks.springthriftserver; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class SpringThriftServerApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(SpringThriftServerApplication.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /spring-thrift-server/src/main/java/com/hks/springthriftserver/config/ThriftServerConfig.java: -------------------------------------------------------------------------------- 1 | package com.hks.springthriftserver.config; 2 | 3 | import com.hks.springthriftcommon.thrift.ThriftServiceServerFactory; 4 | import com.hks.springthriftcommon.zookeeper.ZookeeperFactory; 5 | import com.hks.springthriftcommon.zookeeper.impl.ThriftServerAddressRegisterZookeeper; 6 | import com.hks.springthriftserver.serviceImpl.HelloWorldServiceImpl; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.context.annotation.Bean; 9 | import org.springframework.context.annotation.Configuration; 10 | 11 | /** 12 | * @Author: hekuangsheng 13 | * @Date: 2018/11/14 14 | */ 15 | @Configuration 16 | public class ThriftServerConfig { 17 | 18 | @Autowired 19 | private HelloWorldServiceImpl helloWorldServiceImpl; 20 | 21 | @Bean 22 | public ZookeeperFactory zookeeperFactory() { 23 | ZookeeperFactory zookeeperFactory = new ZookeeperFactory(); 24 | zookeeperFactory.setZkHosts("127.0.0.1:2181"); 25 | zookeeperFactory.setNamespace("com.thrift.api"); 26 | zookeeperFactory.setConnectionTimeout(3000); 27 | zookeeperFactory.setSessionTimeout(3000); 28 | zookeeperFactory.setSingleton(true); 29 | return zookeeperFactory; 30 | } 31 | 32 | @Bean 33 | public ThriftServerAddressRegisterZookeeper thriftServerAddressRegisterZookeeper() { 34 | ThriftServerAddressRegisterZookeeper tsarz = new ThriftServerAddressRegisterZookeeper(); 35 | try { 36 | tsarz.setZkClient(zookeeperFactory().getObject()); 37 | } catch (Exception e) { 38 | System.out.println(e.getMessage()); 39 | } 40 | return tsarz; 41 | } 42 | 43 | @Bean 44 | public ThriftServiceServerFactory thriftServiceServerFactory() { 45 | ThriftServiceServerFactory tssf = new ThriftServiceServerFactory(); 46 | tssf.setService(helloWorldServiceImpl); 47 | tssf.setPort(9002); 48 | tssf.setVersion("1.0.0"); 49 | tssf.setWeight(1); 50 | tssf.setThriftServerAddressRegister(thriftServerAddressRegisterZookeeper()); 51 | return tssf; 52 | } 53 | } -------------------------------------------------------------------------------- /spring-thrift-server/src/main/java/com/hks/springthriftserver/serviceImpl/HelloWorldServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.hks.springthriftserver.serviceImpl; 2 | 3 | import com.hks.springthriftapi.service.HelloWorldService; 4 | import org.apache.thrift.TException; 5 | import org.springframework.stereotype.Service; 6 | 7 | /** 8 | * @Author: hekuangsheng 9 | * @Date: 2018/11/14 10 | */ 11 | @Service 12 | public class HelloWorldServiceImpl implements HelloWorldService.Iface { 13 | 14 | @Override 15 | public String sayHello(String username) throws TException { 16 | return "hello" + username; 17 | } 18 | 19 | @Override 20 | public String getRandom() throws TException { 21 | return "random"; 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /spring-thrift-server/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | server.port=8050 -------------------------------------------------------------------------------- /spring-thrift-server/src/test/java/com/hks/springthriftserver/SpringThriftServerApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.hks.springthriftserver; 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 SpringThriftServerApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /spring-zookeeper-invoker/.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | .sts4-cache 12 | 13 | ### IntelliJ IDEA ### 14 | .idea 15 | *.iws 16 | *.iml 17 | *.ipr 18 | 19 | ### NetBeans ### 20 | /nbproject/private/ 21 | /build/ 22 | /nbbuild/ 23 | /dist/ 24 | /nbdist/ 25 | /.nb-gradle/ -------------------------------------------------------------------------------- /spring-zookeeper-invoker/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.hks 7 | spring-zookeeper-invoker 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | spring-zookeeper-invoker 12 | spring-zookeeper-invoker project for Spring Boot 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 2.1.0.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 1.8 25 | 26 | 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter-web 31 | 32 | 33 | 34 | org.apache.zookeeper 35 | zookeeper 36 | 3.4.6 37 | 38 | 39 | 40 | org.springframework.boot 41 | spring-boot-starter-test 42 | test 43 | 44 | 45 | 46 | 47 | 48 | 49 | org.springframework.boot 50 | spring-boot-maven-plugin 51 | 52 | 53 | 54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /spring-zookeeper-invoker/src/main/java/com/hks/springzookeeperweb/SpringZookeeperWebApplication.java: -------------------------------------------------------------------------------- 1 | package com.hks.springzookeeperweb; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class SpringZookeeperWebApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(SpringZookeeperWebApplication.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /spring-zookeeper-invoker/src/main/java/com/hks/springzookeeperweb/consumer/ServiceHelp.java: -------------------------------------------------------------------------------- 1 | package com.hks.springzookeeperweb.consumer; 2 | 3 | /** 4 | * @Author: hekuangsheng 5 | * @Date: 2018/10/31 6 | */ 7 | public interface ServiceHelp { 8 | String getData(String serviceName); 9 | } 10 | -------------------------------------------------------------------------------- /spring-zookeeper-invoker/src/main/java/com/hks/springzookeeperweb/consumer/impl/ServiceHelpImpl.java: -------------------------------------------------------------------------------- 1 | package com.hks.springzookeeperweb.consumer.impl; 2 | 3 | import com.hks.springzookeeperweb.consumer.ServiceHelp; 4 | import org.apache.zookeeper.WatchedEvent; 5 | import org.apache.zookeeper.Watcher; 6 | import org.apache.zookeeper.ZooKeeper; 7 | import org.slf4j.Logger; 8 | import org.slf4j.LoggerFactory; 9 | import org.springframework.stereotype.Component; 10 | 11 | import java.util.List; 12 | import java.util.concurrent.CountDownLatch; 13 | 14 | /** 15 | * @Author: hekuangsheng 16 | * @Date: 2018/10/31 17 | */ 18 | @Component 19 | public class ServiceHelpImpl implements Watcher, ServiceHelp { 20 | 21 | private static final int SESSION_TIMEOUT = 5000; 22 | private static final String REGISTRY_PATH = "/registry"; 23 | private static CountDownLatch latch = new CountDownLatch(1); 24 | private static Logger logger = LoggerFactory 25 | .getLogger(ServiceHelpImpl.class); 26 | private ZooKeeper zk; 27 | 28 | public ServiceHelpImpl() { 29 | logger.debug("初始化类"); 30 | } 31 | 32 | public ServiceHelpImpl(String zkServers) { 33 | try { 34 | zk = new ZooKeeper(zkServers, SESSION_TIMEOUT, this); 35 | latch.await(); 36 | logger.debug("connected to zookeeper"); 37 | 38 | } catch (Exception e) { 39 | logger.error("create zookeeper client failuer", e); 40 | } 41 | } 42 | 43 | @Override 44 | public String getData(String serviceName) { 45 | try { 46 | String servicePath = REGISTRY_PATH + "/" + serviceName; 47 | logger.debug("service_path is :" + servicePath); 48 | List childPath; 49 | 50 | childPath = zk.getChildren(servicePath, false); 51 | 52 | if (childPath.size() == 0) { 53 | logger.error("%s address node is not exsited", serviceName); 54 | throw (new Exception("地址未找到")); 55 | } 56 | String addressPath = servicePath + "/"; 57 | if (childPath.size() == 1) { 58 | addressPath += childPath.get(0); 59 | } 60 | if (childPath.size() > 1) { 61 | addressPath += childPath.get((int) (Math.random() * childPath.size())); 62 | } 63 | logger.debug("address node is " + addressPath); 64 | byte[] data = zk.getData(addressPath, null, null); 65 | return new String(data); 66 | } catch (Exception e) { 67 | logger.error("get data failure", e); 68 | } 69 | return ""; 70 | } 71 | 72 | @Override 73 | public void process(WatchedEvent watchedEvent) { 74 | if (watchedEvent.getState() == Event.KeeperState.SyncConnected) { 75 | if (Event.EventType.None == watchedEvent.getType() && null == watchedEvent.getPath()) { 76 | latch.countDown(); 77 | } 78 | else if(watchedEvent.getType()== Event.EventType.NodeChildrenChanged){ 79 | try{ 80 | System.out.print("reGet child:"+zk.getChildren(watchedEvent.getPath(),true)); 81 | } 82 | catch (Exception ex){ 83 | ex.printStackTrace(); 84 | } 85 | } 86 | } 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /spring-zookeeper-invoker/src/main/java/com/hks/springzookeeperweb/controller/ZookeeperRead.java: -------------------------------------------------------------------------------- 1 | package com.hks.springzookeeperweb.controller; 2 | 3 | import com.hks.springzookeeperweb.consumer.ServiceHelp; 4 | import com.hks.springzookeeperweb.consumer.impl.ServiceHelpImpl; 5 | import org.springframework.stereotype.Controller; 6 | import org.springframework.web.bind.annotation.RequestMapping; 7 | import org.springframework.web.bind.annotation.RequestMethod; 8 | import org.springframework.web.bind.annotation.ResponseBody; 9 | 10 | /** 11 | * @Author: hekuangsheng 12 | * @Date: 2018/10/31 13 | */ 14 | @Controller 15 | public class ZookeeperRead { 16 | 17 | @RequestMapping(method = RequestMethod.GET, path = "/read") 18 | @ResponseBody 19 | public String hello() { 20 | ServiceHelp serviceHelp = new ServiceHelpImpl("127.0.0.1:2181"); 21 | String data = serviceHelp.getData("HelloService"); 22 | return data; 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /spring-zookeeper-invoker/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | 2server.port=8082 2 | -------------------------------------------------------------------------------- /spring-zookeeper-invoker/src/test/java/com/hks/springzookeeperweb/SpringZookeeperWebApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.hks.springzookeeperweb; 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 SpringZookeeperWebApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /spring-zookeeper-register/.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | .sts4-cache 12 | 13 | ### IntelliJ IDEA ### 14 | .idea 15 | *.iws 16 | *.iml 17 | *.ipr 18 | 19 | ### NetBeans ### 20 | /nbproject/private/ 21 | /build/ 22 | /nbbuild/ 23 | /dist/ 24 | /nbdist/ 25 | /.nb-gradle/ -------------------------------------------------------------------------------- /spring-zookeeper-register/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.hks 7 | spring-zookeeper-register 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | spring-zookeeper-register 12 | spring-zookeeper-register project for Spring Boot 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 2.0.6.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 1.8 25 | 26 | 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter-web 31 | 32 | 33 | 34 | org.apache.zookeeper 35 | zookeeper 36 | 3.4.13 37 | 38 | 39 | 40 | 41 | org.projectlombok 42 | lombok 43 | 1.18.2 44 | provided 45 | 46 | 47 | 48 | com.google.code.gson 49 | gson 50 | 2.8.2 51 | 52 | 53 | 54 | 55 | org.apache.curator 56 | curator-recipes 57 | 4.0.1 58 | 59 | 60 | 61 | org.springframework.boot 62 | spring-boot-starter-test 63 | test 64 | 65 | 66 | 67 | 68 | 69 | 70 | org.springframework.boot 71 | spring-boot-maven-plugin 72 | 73 | 74 | 75 | 76 | 77 | 78 | -------------------------------------------------------------------------------- /spring-zookeeper-register/src/main/java/com/hks/springzookeeper/SpringZookeeperApplication.java: -------------------------------------------------------------------------------- 1 | package com.hks.springzookeeper; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class SpringZookeeperApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(SpringZookeeperApplication.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /spring-zookeeper-register/src/main/java/com/hks/springzookeeper/config/RegistryConfig.java: -------------------------------------------------------------------------------- 1 | package com.hks.springzookeeper.config; 2 | 3 | import com.hks.springzookeeper.register.ServiceRegistry; 4 | import com.hks.springzookeeper.register.impl.ServiceRegistryImpl; 5 | import org.springframework.beans.factory.annotation.Value; 6 | import org.springframework.boot.context.properties.ConfigurationProperties; 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.context.annotation.Configuration; 9 | 10 | /** 11 | * @Author: hekuangsheng 12 | * @Date: 2018/10/31 13 | * 14 | * 创建一个配置类来读取application.properties的配置 15 | */ 16 | @Configuration 17 | @ConfigurationProperties(prefix="registry") 18 | public class RegistryConfig { 19 | 20 | @Value("registry.servers") 21 | private String servers; 22 | 23 | @Bean 24 | public ServiceRegistry serviceRegistry(){ 25 | return new ServiceRegistryImpl(servers); 26 | } 27 | 28 | public String getServers() { 29 | return servers; 30 | } 31 | 32 | public void setServers(String servers) { 33 | this.servers = servers; 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /spring-zookeeper-register/src/main/java/com/hks/springzookeeper/config/WebListener.java: -------------------------------------------------------------------------------- 1 | package com.hks.springzookeeper.config; 2 | 3 | import com.hks.springzookeeper.register.ServiceRegistry; 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.beans.factory.annotation.Value; 8 | import org.springframework.context.ApplicationContext; 9 | import org.springframework.stereotype.Component; 10 | import org.springframework.web.context.support.WebApplicationContextUtils; 11 | import org.springframework.web.method.HandlerMethod; 12 | import org.springframework.web.servlet.mvc.method.RequestMappingInfo; 13 | import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; 14 | 15 | import javax.servlet.ServletContext; 16 | import javax.servlet.ServletContextEvent; 17 | import javax.servlet.ServletContextListener; 18 | import java.util.Map; 19 | 20 | /** 21 | * @Author: hekuangsheng 22 | * @Date: 2018/10/31 23 | *

24 | * 由于我们的服务是以javaweb的形式发布的。 25 | * 所以在每个应用初始化时,去完成接口的注册是一个好时机。 26 | * 因此我们新加一个类去实现ServletContextListener,并把这个类交给spring来管理。 27 | */ 28 | @Component 29 | public class WebListener implements ServletContextListener { 30 | 31 | private static Logger logger = LoggerFactory 32 | .getLogger(WebListener.class); 33 | @Value("${server.address}") 34 | private String serverAddress; 35 | @Value("${server.port}") 36 | private int serverPort; 37 | 38 | @Autowired 39 | private ServiceRegistry serviceRegistry; 40 | 41 | @Override 42 | public void contextInitialized(ServletContextEvent servletContextEvent) { 43 | //获取请求映射 44 | ServletContext servletContext = servletContextEvent.getServletContext(); 45 | ApplicationContext applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext); 46 | RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class); 47 | Map infoMap = mapping.getHandlerMethods(); 48 | for (RequestMappingInfo info : infoMap.keySet()) { 49 | String serviceName = info.getName(); 50 | logger.debug("-----------" + serviceName); 51 | if (null != serviceName) { 52 | serviceRegistry.register(serviceName, String.format("%s:%d/hello", serverAddress, serverPort)); 53 | } 54 | } 55 | } 56 | 57 | @Override 58 | public void contextDestroyed(ServletContextEvent servletContextEvent) { 59 | 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /spring-zookeeper-register/src/main/java/com/hks/springzookeeper/controller/DemoTest.java: -------------------------------------------------------------------------------- 1 | package com.hks.springzookeeper.controller; 2 | 3 | import org.springframework.stereotype.Controller; 4 | import org.springframework.web.bind.annotation.RequestMapping; 5 | import org.springframework.web.bind.annotation.RequestMethod; 6 | 7 | /** 8 | * @Author: hekuangsheng 9 | * @Date: 2018/10/31 10 | */ 11 | @Controller 12 | public class DemoTest { 13 | 14 | @RequestMapping(name = "HelloService", method = RequestMethod.GET, path = "/hello") 15 | public String hello() { 16 | return "hello word"; 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /spring-zookeeper-register/src/main/java/com/hks/springzookeeper/controller/RestBizController.java: -------------------------------------------------------------------------------- 1 | package com.hks.springzookeeper.controller; 2 | 3 | import org.apache.zookeeper.WatchedEvent; 4 | import org.apache.zookeeper.Watcher; 5 | import org.apache.zookeeper.ZooKeeper; 6 | import org.springframework.web.bind.annotation.RequestMapping; 7 | import org.springframework.web.bind.annotation.RequestMethod; 8 | import org.springframework.web.bind.annotation.RestController; 9 | 10 | /** 11 | * @Author: hekuangsheng 12 | * @Date: 2018/10/30 13 | */ 14 | @RestController 15 | public class RestBizController { 16 | 17 | @RequestMapping(value = "/zkget", method = RequestMethod.GET) 18 | public String zkget() { 19 | Watcher watcher = new Watcher() { 20 | public void process(WatchedEvent event) { 21 | System.out.println("receive event:" + event); 22 | } 23 | }; 24 | 25 | String value = null; 26 | try { 27 | final ZooKeeper zookeeper = new ZooKeeper("127.0.0.1:2181", 999999, watcher); 28 | final byte[] data = zookeeper.getData("/node_1", watcher, null); 29 | value = new String(data); 30 | zookeeper.close(); 31 | } catch (Exception e) { 32 | e.printStackTrace(); 33 | } 34 | 35 | return "get value from zookeeper [" + value + "]"; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /spring-zookeeper-register/src/main/java/com/hks/springzookeeper/register/ServiceRegistry.java: -------------------------------------------------------------------------------- 1 | package com.hks.springzookeeper.register; 2 | 3 | /** 4 | * @Author: hekuangsheng 5 | * @Date: 2018/10/31 6 | * 7 | * 定义服务注册表接口 8 | */ 9 | public interface ServiceRegistry { 10 | 11 | /** 12 | * 注册服务信息 13 | * @param serviceName 服务名称 14 | * @param serviceAddress 服务地址 15 | */ 16 | void register(String serviceName,String serviceAddress); 17 | } 18 | -------------------------------------------------------------------------------- /spring-zookeeper-register/src/main/java/com/hks/springzookeeper/register/impl/ServiceRegistryImpl.java: -------------------------------------------------------------------------------- 1 | package com.hks.springzookeeper.register.impl; 2 | 3 | import com.hks.springzookeeper.register.ServiceRegistry; 4 | import org.apache.zookeeper.*; 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | import org.springframework.stereotype.Component; 8 | 9 | import java.util.concurrent.CountDownLatch; 10 | 11 | /** 12 | * @Author: hekuangsheng 13 | * @Date: 2018/10/31 14 | *

15 | * 创建一个ServiceRegistry的实现类。实现注册接口 16 | */ 17 | @Component 18 | public class ServiceRegistryImpl implements Watcher, ServiceRegistry { 19 | 20 | private static final int SESSION_TIMEOUT = 5000; 21 | private static final String REGISTRY_PATH = "/registry"; 22 | private static CountDownLatch latch = new CountDownLatch(1); 23 | private static Logger logger = LoggerFactory 24 | .getLogger(ServiceRegistryImpl.class); 25 | private ZooKeeper zk; 26 | 27 | public ServiceRegistryImpl() { 28 | logger.debug("初始化类"); 29 | } 30 | 31 | public ServiceRegistryImpl(String zkServers) { 32 | try { 33 | zk = new ZooKeeper(zkServers, SESSION_TIMEOUT, this); 34 | latch.await(); 35 | logger.debug("connected to zookeeper"); 36 | 37 | } catch (Exception e) { 38 | logger.error("create zookeeper client failuer", e); 39 | } 40 | } 41 | 42 | @Override 43 | public void register(String serviceName, String serviceAddress) { 44 | String registryPath = REGISTRY_PATH; 45 | try { 46 | logger.debug("-zk---------" + zk); 47 | //创建根节点:持久节点 48 | if (zk.exists(registryPath, true) == null) { 49 | zk.create(registryPath, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, 50 | CreateMode.PERSISTENT); 51 | logger.debug("create registry node:{}", registryPath); 52 | } 53 | //创建服务节点:持久节点 54 | String servicePath = registryPath + "/" + serviceName; 55 | if (zk.exists(servicePath, true) == null) { 56 | zk.create(servicePath, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); 57 | logger.debug("create service node :{}" + servicePath); 58 | } 59 | //创建地址节点:临时顺序节点 60 | String addressPath = servicePath + "/address-"; 61 | String addressNode = zk.create(addressPath, serviceAddress.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); 62 | logger.debug("create node address:{}=>{}" + addressNode); 63 | } catch (Exception e) { 64 | logger.error("create node failure", e); 65 | } 66 | } 67 | 68 | @Override 69 | public void process(WatchedEvent watchedEvent) { 70 | if (watchedEvent.getState() == Event.KeeperState.SyncConnected) { 71 | latch.countDown(); 72 | } 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /spring-zookeeper-register/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | server.address=127.0.0.1 2 | server.port=8081 3 | #server.name=spring-zookeeper 4 | 5 | registry.servers=127.0.0.1:2181,127.0.0.1:2182,127.0.0.1:2183 -------------------------------------------------------------------------------- /spring-zookeeper-register/src/test/java/com/hks/springzookeeper/SpringZookeeperApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.hks.springzookeeper; 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 SpringZookeeperApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /spring-zookeeper-register/src/test/java/com/hks/springzookeeper/distributeLock/RecipesLock.java: -------------------------------------------------------------------------------- 1 | package com.hks.springzookeeper.distributeLock; 2 | 3 | import org.apache.curator.framework.CuratorFramework; 4 | import org.apache.curator.framework.CuratorFrameworkFactory; 5 | import org.apache.curator.framework.recipes.locks.InterProcessLock; 6 | import org.apache.curator.framework.recipes.locks.InterProcessMutex; 7 | import org.apache.curator.retry.ExponentialBackoffRetry; 8 | 9 | import java.text.SimpleDateFormat; 10 | import java.util.Date; 11 | import java.util.SimpleTimeZone; 12 | import java.util.concurrent.CountDownLatch; 13 | 14 | /** 15 | * @Author: hekuangsheng 16 | * @Date: 2018/11/12 17 | */ 18 | public class RecipesLock { 19 | 20 | static String lock_path = "/curator_recipes_lock_path"; 21 | static CuratorFramework client = CuratorFrameworkFactory.builder() 22 | .connectString("127.0.0.1:2181") 23 | .retryPolicy(new ExponentialBackoffRetry(1000, 3)) 24 | .build(); 25 | 26 | public static void main(String[] args) { 27 | try{ 28 | client.start(); 29 | final InterProcessMutex lock = new InterProcessMutex(client,lock_path); 30 | final CountDownLatch down = new CountDownLatch(1); 31 | for(int i=0;i<10;i++){ 32 | new Thread(new Runnable() { 33 | @Override 34 | public void run() { 35 | try{ 36 | down.await(); 37 | lock.acquire(); 38 | } 39 | catch (Exception ex){ 40 | ex.printStackTrace(); 41 | } 42 | SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss|SSS"); 43 | String orderNo = sdf.format(new Date()); 44 | System.out.print("生成的订单号是:"+orderNo); 45 | try{ 46 | lock.release(); 47 | } 48 | catch (Exception ex){ 49 | ex.printStackTrace(); 50 | } 51 | } 52 | }).start(); 53 | } 54 | down.countDown(); 55 | } 56 | catch (Exception ex){ 57 | ex.printStackTrace(); 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /spring-zookeeper-register/src/test/java/com/hks/springzookeeper/leaderSelector/Test.java: -------------------------------------------------------------------------------- 1 | package com.hks.springzookeeper.leaderSelector; 2 | 3 | import org.apache.curator.framework.CuratorFramework; 4 | import org.apache.curator.framework.CuratorFrameworkFactory; 5 | import org.apache.curator.framework.recipes.leader.LeaderSelector; 6 | import org.apache.curator.framework.recipes.leader.LeaderSelectorListenerAdapter; 7 | import org.apache.curator.retry.ExponentialBackoffRetry; 8 | import org.springframework.beans.factory.annotation.Value; 9 | 10 | /** 11 | * @Author: hekuangsheng 12 | * @Date: 2018/11/12 13 | */ 14 | public class Test { 15 | 16 | static String master_path = "/curator_recipes_master_path"; 17 | static CuratorFramework client = CuratorFrameworkFactory.builder() 18 | .connectString("127.0.0.1:2181") 19 | .retryPolicy(new ExponentialBackoffRetry(1000, 3)) 20 | .build(); 21 | 22 | @org.junit.Test 23 | public static void main(String[] args) throws Exception{ 24 | client.start(); 25 | LeaderSelector selector = new LeaderSelector(client, 26 | master_path, 27 | new LeaderSelectorListenerAdapter() { 28 | @Override 29 | public void takeLeadership(CuratorFramework curatorFramework) throws Exception { 30 | System.out.print("成为master角色"); 31 | Thread.sleep(30000); 32 | System.out.print("完成master操作,释放master权利"); 33 | } 34 | }); 35 | selector.autoRequeue(); 36 | selector.start(); 37 | Thread.sleep(Integer.MAX_VALUE); 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /thrift-api/.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | .sts4-cache 12 | 13 | ### IntelliJ IDEA ### 14 | .idea 15 | *.iws 16 | *.iml 17 | *.ipr 18 | 19 | ### NetBeans ### 20 | /nbproject/private/ 21 | /build/ 22 | /nbbuild/ 23 | /dist/ 24 | /nbdist/ 25 | /.nb-gradle/ -------------------------------------------------------------------------------- /thrift-api/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.hks 7 | thrift-api 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | thrift-api 12 | thrift-api project for Spring Boot 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 2.0.3.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 1.8 25 | 26 | 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter 31 | 32 | 33 | org.apache.thrift 34 | libthrift 35 | 0.11.0 36 | 37 | 38 | 39 | org.springframework.boot 40 | spring-boot-starter-test 41 | test 42 | 43 | 44 | 45 | 46 | 47 | 48 | org.springframework.boot 49 | spring-boot-maven-plugin 50 | 51 | 52 | 53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /thrift-api/src/main/java/com/hks/thriftapi/ThriftApiApplication.java: -------------------------------------------------------------------------------- 1 | package com.hks.thriftapi; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class ThriftApiApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(ThriftApiApplication.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /thrift-api/src/main/resources/application.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/singgel/RPC-SkillTree/67bfbc076b18bca17850c64fd2a935fdcd88d9ee/thrift-api/src/main/resources/application.properties -------------------------------------------------------------------------------- /thrift-api/src/main/thrift/Hello.thrift: -------------------------------------------------------------------------------- 1 | namespace java com.hks.thriftapi.service 2 | 3 | service Hello{ 4 | string helloString(1:string para) 5 | i32 helloInt(1:i32 para) 6 | bool helloBoolean(1:bool para) 7 | void helloVoid() 8 | string helloNull() 9 | } -------------------------------------------------------------------------------- /thrift-api/src/test/java/com/hks/thriftapi/ThriftApiApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.hks.thriftapi; 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 ThriftApiApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /thrift-client/.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | .sts4-cache 12 | 13 | ### IntelliJ IDEA ### 14 | .idea 15 | *.iws 16 | *.iml 17 | *.ipr 18 | 19 | ### NetBeans ### 20 | /nbproject/private/ 21 | /build/ 22 | /nbbuild/ 23 | /dist/ 24 | /nbdist/ 25 | /.nb-gradle/ -------------------------------------------------------------------------------- /thrift-client/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.hks 7 | thrift-client 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | thrift-client 12 | Demo project for Spring Boot 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 2.0.3.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 1.8 25 | 26 | 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter 31 | 32 | 33 | org.apache.thrift 34 | libthrift 35 | 0.11.0 36 | 37 | 38 | com.hks 39 | thrift-api 40 | 0.0.1-SNAPSHOT 41 | 42 | 43 | 44 | org.springframework.boot 45 | spring-boot-starter-test 46 | test 47 | 48 | 49 | 50 | 51 | 52 | 53 | org.springframework.boot 54 | spring-boot-maven-plugin 55 | 56 | 57 | 58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /thrift-client/src/main/java/com/hks/thriftclient/ThriftClientApplication.java: -------------------------------------------------------------------------------- 1 | package com.hks.thriftclient; 2 | 3 | import com.hks.thriftapi.service.Hello; 4 | import org.apache.thrift.protocol.TBinaryProtocol; 5 | import org.apache.thrift.protocol.TProtocol; 6 | import org.apache.thrift.transport.TFramedTransport; 7 | import org.apache.thrift.transport.TSocket; 8 | import org.apache.thrift.transport.TTransport; 9 | 10 | import org.springframework.boot.SpringApplication; 11 | import org.springframework.boot.autoconfigure.SpringBootApplication; 12 | 13 | @SpringBootApplication 14 | public class ThriftClientApplication { 15 | 16 | public static void main(String[] args) { 17 | try { 18 | TTransport tTransport = getTTransport(); 19 | TProtocol protocol = new TBinaryProtocol(tTransport); 20 | Hello.Client client = new Hello.Client(protocol); 21 | String result = client.helloString("hello"); 22 | System.out.println("The result is: " + result); 23 | }catch (Exception e) { 24 | e.printStackTrace(); 25 | } 26 | SpringApplication.run(ThriftClientApplication.class, args); 27 | } 28 | 29 | private static TTransport getTTransport() throws Exception{ 30 | try{ 31 | TTransport tTransport = getTTransport("127.0.0.1", 7911, 5000); 32 | if(!tTransport.isOpen()){ 33 | tTransport.open(); 34 | } 35 | return tTransport; 36 | }catch(Exception e){ 37 | e.printStackTrace(); 38 | } 39 | return null; 40 | } 41 | 42 | private static TTransport getTTransport(String host, int port, int timeout) { 43 | final TSocket tSocket = new TSocket(host, port, timeout); 44 | final TTransport transport = new TFramedTransport(tSocket); 45 | return transport; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /thrift-client/src/main/resources/application.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/singgel/RPC-SkillTree/67bfbc076b18bca17850c64fd2a935fdcd88d9ee/thrift-client/src/main/resources/application.properties -------------------------------------------------------------------------------- /thrift-client/src/test/java/com/hks/thriftclient/ThriftClientApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.hks.thriftclient; 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 ThriftClientApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /thrift-server/.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | .sts4-cache 12 | 13 | ### IntelliJ IDEA ### 14 | .idea 15 | *.iws 16 | *.iml 17 | *.ipr 18 | 19 | ### NetBeans ### 20 | /nbproject/private/ 21 | /build/ 22 | /nbbuild/ 23 | /dist/ 24 | /nbdist/ 25 | /.nb-gradle/ -------------------------------------------------------------------------------- /thrift-server/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.hks 7 | thrift-server 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | thrift-server 12 | thrift-server project for Spring Boot 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 2.0.3.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 1.8 25 | 26 | 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter 31 | 32 | 33 | org.apache.thrift 34 | libthrift 35 | 0.11.0 36 | 37 | 38 | com.hks 39 | thrift-api 40 | 0.0.1-SNAPSHOT 41 | 42 | 43 | 44 | org.springframework.boot 45 | spring-boot-starter-test 46 | test 47 | 48 | 49 | 50 | 51 | 52 | 53 | org.springframework.boot 54 | spring-boot-maven-plugin 55 | 56 | 57 | 58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /thrift-server/src/main/java/com/hks/thriftserver/ThriftServerApplication.java: -------------------------------------------------------------------------------- 1 | package com.hks.thriftserver; 2 | 3 | import com.hks.thriftapi.service.Hello; 4 | import com.hks.thriftserver.service.HelloServiceImpl; 5 | import org.apache.thrift.TProcessorFactory; 6 | import org.apache.thrift.protocol.TBinaryProtocol; 7 | import org.apache.thrift.server.TServer; 8 | import org.apache.thrift.server.TNonblockingServer; 9 | import org.apache.thrift.transport.TFramedTransport; 10 | import org.apache.thrift.transport.TNonblockingServerSocket; 11 | import org.apache.thrift.transport.TTransportException; 12 | 13 | import org.springframework.boot.SpringApplication; 14 | import org.springframework.boot.autoconfigure.SpringBootApplication; 15 | 16 | @SpringBootApplication 17 | public class ThriftServerApplication { 18 | 19 | public static void main(String[] args) { 20 | try { 21 | TNonblockingServerSocket socket = new TNonblockingServerSocket(7911); 22 | Hello.Processor processor = new Hello.Processor(new HelloServiceImpl()); 23 | TNonblockingServer.Args arg = new TNonblockingServer.Args(socket); 24 | arg.protocolFactory(new TBinaryProtocol.Factory()); 25 | arg.transportFactory(new TFramedTransport.Factory()); 26 | arg.processorFactory(new TProcessorFactory(processor)); 27 | TServer server = new TNonblockingServer(arg); 28 | server.serve(); 29 | SpringApplication.run(ThriftServerApplication.class, args); 30 | } catch (TTransportException e) { 31 | e.printStackTrace(); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /thrift-server/src/main/java/com/hks/thriftserver/service/HelloServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.hks.thriftserver.service; 2 | 3 | import com.hks.thriftapi.service.Hello; 4 | import org.apache.thrift.TException; 5 | 6 | public class HelloServiceImpl implements Hello.Iface { 7 | @Override 8 | public boolean helloBoolean(boolean para) throws TException { 9 | return para; 10 | } 11 | @Override 12 | public int helloInt(int para) throws TException { 13 | try { 14 | Thread.sleep(20000); 15 | } catch (InterruptedException e) { 16 | e.printStackTrace(); 17 | } 18 | return para; 19 | } 20 | @Override 21 | public String helloNull() throws TException { 22 | return null; 23 | } 24 | @Override 25 | public String helloString(String para) throws TException { 26 | return para; 27 | } 28 | @Override 29 | public void helloVoid() throws TException { 30 | System.out.println("Hello World"); 31 | } 32 | } -------------------------------------------------------------------------------- /thrift-server/src/main/resources/application.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/singgel/RPC-SkillTree/67bfbc076b18bca17850c64fd2a935fdcd88d9ee/thrift-server/src/main/resources/application.properties -------------------------------------------------------------------------------- /thrift-server/src/test/java/com/hks/thriftserver/ThriftServerApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.hks.thriftserver; 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 ThriftServerApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | --------------------------------------------------------------------------------