├── .gitignore
├── README.md
├── grpc-contract
├── pom.xml
└── src
│ └── main
│ └── proto
│ ├── Demo.proto
│ └── Yyc.proto
├── grpc-demo-encryption
├── pom.xml
└── src
│ └── main
│ ├── java
│ └── com
│ │ └── grpc
│ │ └── demo
│ │ └── encryption
│ │ ├── SimpleClientStart.java
│ │ ├── SimpleServer.java
│ │ └── SimpleServerStart.java
│ └── resources
│ ├── cert.csr
│ ├── demo-private.pem
│ ├── demo-public.pem
│ ├── public.der
│ ├── public.pem
│ ├── public1.pem
│ ├── server1-private.key
│ └── server1-public-ca.pem
├── grpc-demo-interceptor
├── pom.xml
└── src
│ └── main
│ └── java
│ └── com
│ └── grpc
│ └── demo
│ └── interceptor
│ ├── SimpleClientStart.java
│ ├── SimpleServer.java
│ └── SimpleServerStart.java
├── grpc-demo-nameResolver
├── pom.xml
└── src
│ └── main
│ └── java
│ └── com
│ └── grpc
│ └── demo
│ └── nameResolver
│ ├── ServerNameResolver.java
│ ├── ServerNameResolverProvider.java
│ ├── SimpleClientStart.java
│ ├── SimpleServer.java
│ ├── SimpleServerStart1.java
│ └── SimpleServerStart2.java
├── grpc-demo-oneof
├── pom.xml
└── src
│ └── main
│ └── java
│ └── com
│ └── grpc
│ └── demo
│ └── oneof
│ ├── AbstractTask.java
│ ├── SimpleClientStart.java
│ ├── SimpleExecutor.java
│ ├── SimpleServer.java
│ └── SimpleServerStart.java
├── grpc-demo-proxy
├── pom.xml
└── src
│ └── main
│ ├── java
│ └── com
│ │ └── grpc
│ │ └── demo
│ │ └── proxy
│ │ ├── SimpleClientStart.java
│ │ ├── SimpleExecutor.java
│ │ ├── SimpleServer.java
│ │ ├── SimpleServerStart.java
│ │ ├── YycClientStart.java
│ │ ├── YycServer.java
│ │ ├── YycServerStart.java
│ │ ├── netty
│ │ ├── EchoClient.java
│ │ ├── EchoClientHandler.java
│ │ ├── EchoServer.java
│ │ └── EchoServerHandler.java
│ │ └── proxy1
│ │ ├── ClientToProxyChannels.java
│ │ ├── HexDumpProxy.java
│ │ ├── HexDumpProxyBackendHandler.java
│ │ ├── HexDumpProxyFrontendHandler.java
│ │ ├── HexDumpProxyInitializer.java
│ │ ├── InitChannel.java
│ │ ├── ProxyToServerChannel.java
│ │ └── Servers.java
│ └── resources
│ ├── http2-connection.puml
│ └── logback.xml
├── grpc-demo-simple
├── pom.xml
└── src
│ └── main
│ └── java
│ └── com
│ └── grpc
│ └── demo
│ └── simple
│ ├── SimpleClientStart.java
│ ├── SimpleServer.java
│ └── SimpleServerStart.java
├── grpc-demo-stream
├── pom.xml
└── src
│ └── main
│ └── java
│ └── com
│ └── grpc
│ └── demo
│ └── stream
│ ├── SimpleClientStart.java
│ ├── SimpleServer.java
│ └── SimpleServerStart.java
└── pom.xml
/.gitignore:
--------------------------------------------------------------------------------
1 | .*
2 | !.gitignore
3 | target
4 | WebContent
5 | *.log
6 | *.iml
7 | *.versionsBackup
8 | logs
9 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # grpc-demo introduces using grpc
2 |
3 | 1.Introduction grpc
4 |
5 | 2.Simple demo of grpc
6 |
7 | 3.Using OpenSSL encryption of grpc transport
8 |
9 | 4.How to using protobuf oneof
10 |
11 | 5.How to using client-stream and service-stream
12 |
13 | 6.Add client and server interceptor
14 |
15 | 7.How to using NameResovler
16 |
17 | 8.How to using RoundRobinLoadBalancer
18 |
19 | 9.Using grpc proxy
20 |
21 |
22 | ## Introduction grpc
23 |
24 | gRPC is a modern open source high performance RPC framework that can run in any environment. It can efficiently co nnect services in and across data centers with pluggable support for load balancing, tracing, health checking and authentication. It is also applicable in last mile of distributed computing to connect devices, mobile applications and browsers to backend services.
25 |
26 | 
27 |
28 | ### Learning materials
29 | [grpc-java](https://github.com/grpc/grpc-java)
30 |
31 | [grpc-home](http://www.grpc.io/)
32 |
33 | [grpc-chines](http://doc.oschina.net/grpc?t=60134/)
34 |
35 | [grpc-learning](https://skyao.gitbooks.io/leaning-grpc/content/) thanks @skyao
36 |
--------------------------------------------------------------------------------
/grpc-contract/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 4.0.0
6 |
7 |
8 | com.yyc.grpc
9 | grpc-demo
10 | 1.0.0
11 |
12 | com.yyc.grpc
13 | grpc-contract
14 |
15 |
16 | 3.0.0
17 | 0.5.0
18 | 1.10
19 | 1.5.0.Final
20 |
21 |
22 |
23 |
24 |
25 | io.grpc
26 | grpc-protobuf
27 | ${grpc.version}
28 |
29 |
30 | io.grpc
31 | grpc-stub
32 | ${grpc.version}
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 | kr.motd.maven
41 | os-maven-plugin
42 | ${kr.motd.maven.version}
43 |
44 |
45 |
46 |
47 | org.xolstice.maven.plugins
48 | protobuf-maven-plugin
49 | ${maven.protobuf.plugin.version}
50 |
51 | com.google.protobuf:protoc:${protobuf.version}:exe:${os.detected.classifier}
52 |
53 | grpc-java
54 | io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier}
55 |
56 |
57 |
58 |
59 |
60 | compile
61 | compile-custom
62 |
63 |
64 |
65 |
66 |
67 | org.codehaus.mojo
68 | build-helper-maven-plugin
69 | ${maven.build.helper.plugin.version}
70 |
71 |
72 | test
73 | generate-sources
74 |
75 | add-source
76 |
77 |
78 |
79 | ${basedir}/target/generated-sources
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
--------------------------------------------------------------------------------
/grpc-contract/src/main/proto/Demo.proto:
--------------------------------------------------------------------------------
1 | syntax = "proto3";
2 |
3 | option java_multiple_files = true;
4 | option java_outer_classname = "SimpleServiceProto";
5 |
6 |
7 | import "google/protobuf/empty.proto";
8 | import "google/protobuf/wrappers.proto";
9 |
10 | package com.yyc.grpc.contract;
11 |
12 | service SimpleService {
13 | //request or response must be message
14 | rpc SayHello(google.protobuf.StringValue) returns(SayHelloResponse);
15 |
16 | //request get all response
17 | rpc GetAll(google.protobuf.Empty)returns(stream GetAllResponse);
18 |
19 | //client and server instant messenger
20 | rpc WeChat(stream WeChatRequest)returns(stream WeChatResponse);
21 | }
22 |
23 | message SayHelloResponse{
24 | string result = 1;
25 | }
26 |
27 | message GetAllResponse{
28 | oneof index_oneof {
29 | string member1 = 1;
30 | int32 member2 = 2;
31 | string member3 = 3;
32 | }
33 | }
34 |
35 | message WeChatRequest{
36 | string request = 1;
37 | }
38 | message WeChatResponse{
39 | string response = 1;
40 | }
41 |
--------------------------------------------------------------------------------
/grpc-contract/src/main/proto/Yyc.proto:
--------------------------------------------------------------------------------
1 | syntax = "proto3";
2 |
3 | option java_multiple_files = true;
4 | option java_outer_classname = "YycServiceProto";
5 |
6 |
7 | import "google/protobuf/wrappers.proto";
8 | import "Demo.proto";
9 |
10 | package com.yyc.grpc.contract;
11 |
12 | service YycService {
13 | //request or response must be message
14 | rpc SayHello(google.protobuf.StringValue) returns(SayHelloResponse);
15 |
16 | }
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/grpc-demo-encryption/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 4.0.0
6 |
7 | com.yyc.grpc
8 | grpc-demo
9 | 1.0.0
10 |
11 | com.yyc.grpc
12 | grpc-demo-encryption
13 |
14 |
15 |
16 | com.yyc.grpc
17 | grpc-contract
18 | 1.0.0
19 |
20 |
21 | io.grpc
22 | grpc-protobuf
23 | ${grpc.version}
24 |
25 |
26 | io.grpc
27 | grpc-stub
28 | ${grpc.version}
29 |
30 |
31 | io.grpc
32 | grpc-netty
33 | ${grpc.version}
34 |
35 |
36 |
37 | io.netty
38 | netty-tcnative-boringssl-static
39 | 1.1.33.Fork17
40 |
41 |
42 | io.netty
43 | netty-tcnative
44 | 1.1.33.Fork22
45 |
46 |
47 |
--------------------------------------------------------------------------------
/grpc-demo-encryption/src/main/java/com/grpc/demo/encryption/SimpleClientStart.java:
--------------------------------------------------------------------------------
1 | package com.grpc.demo.encryption;
2 |
3 |
4 | import com.google.protobuf.StringValue;
5 | import com.yyc.grpc.contract.SayHelloResponse;
6 | import com.yyc.grpc.contract.SimpleServiceGrpc;
7 | import io.grpc.ManagedChannel;
8 | import io.grpc.netty.GrpcSslContexts;
9 | import io.grpc.netty.NegotiationType;
10 | import io.grpc.netty.NettyChannelBuilder;
11 | import io.netty.handler.ssl.SslContext;
12 | import io.netty.handler.ssl.SslProvider;
13 |
14 | import javax.net.ssl.SSLException;
15 | import java.io.File;
16 | import java.util.concurrent.TimeUnit;
17 |
18 | public class SimpleClientStart {
19 |
20 | private ManagedChannel managedChannel;
21 | private int PORT = 8888;
22 |
23 | private void createChannel(){
24 | SslContext sslContext = null;
25 | try {
26 | String filePath = SimpleServerStart.class.getClassLoader().getResource("").getPath();
27 | File certChain = new File(filePath.concat("server1-public-ca.pem"));
28 | sslContext = GrpcSslContexts.forClient()
29 | .sslProvider(SslProvider.OPENSSL)
30 | .trustManager(certChain)
31 | .build();
32 |
33 | } catch (SSLException e) {
34 | e.printStackTrace();
35 | }
36 | //Mind :this the set host=waterzooi.test.google.be ,cause CA defined,
37 | // so C:\Windows\System32\drivers\etc\hosts append 127.0.0.1 waterzooi.test.google.be
38 | managedChannel = NettyChannelBuilder.forAddress("waterzooi.test.google.be",PORT)
39 | .negotiationType(NegotiationType.TLS)
40 | .sslContext(sslContext).build();
41 | }
42 |
43 | private void shutdown(){
44 | if(managedChannel!=null){
45 | try {
46 | managedChannel.shutdown().awaitTermination(2, TimeUnit.SECONDS);
47 | } catch (InterruptedException e) {
48 | e.printStackTrace();
49 | }
50 | }
51 | }
52 |
53 | public static void main(String[] args) {
54 | SimpleClientStart simpleClientStart = new SimpleClientStart();
55 | simpleClientStart.createChannel();
56 | SimpleServiceGrpc.SimpleServiceBlockingStub simpleServiceStub = SimpleServiceGrpc.newBlockingStub(simpleClientStart.managedChannel);
57 |
58 | SayHelloResponse sayHelloResponse = simpleServiceStub.sayHello(StringValue.newBuilder().setValue("grpc-encryption-demo").build());
59 | System.out.println("response:"+sayHelloResponse.getResult());
60 | simpleClientStart.shutdown();
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/grpc-demo-encryption/src/main/java/com/grpc/demo/encryption/SimpleServer.java:
--------------------------------------------------------------------------------
1 | package com.grpc.demo.encryption;
2 |
3 | import com.yyc.grpc.contract.SayHelloResponse;
4 | import com.yyc.grpc.contract.SimpleServiceGrpc;
5 |
6 | /**
7 | * Created by yeyc on 2016/9/5.
8 | */
9 | public class SimpleServer extends SimpleServiceGrpc.SimpleServiceImplBase{
10 |
11 | @Override
12 | public void sayHello(com.google.protobuf.StringValue request,
13 | io.grpc.stub.StreamObserver responseObserver) {
14 | SayHelloResponse sayHelloResponse = SayHelloResponse.newBuilder().setResult(request.getValue().concat("hello world")).build();
15 | responseObserver.onNext(sayHelloResponse);
16 | responseObserver.onCompleted();
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/grpc-demo-encryption/src/main/java/com/grpc/demo/encryption/SimpleServerStart.java:
--------------------------------------------------------------------------------
1 | package com.grpc.demo.encryption;
2 |
3 |
4 | import io.grpc.Server;
5 | import io.grpc.netty.GrpcSslContexts;
6 | import io.grpc.netty.NettyServerBuilder;
7 | import io.netty.handler.ssl.SslContext;
8 | import io.netty.handler.ssl.SslContextBuilder;
9 | import io.netty.handler.ssl.SslProvider;
10 |
11 | import java.io.File;
12 | import java.net.InetSocketAddress;
13 | import java.net.SocketAddress;
14 | import java.util.concurrent.TimeUnit;
15 |
16 | public class SimpleServerStart {
17 |
18 | private int PORT=8888;
19 | private Server server;
20 |
21 | private void start() throws Exception{
22 | String filePath = SimpleServerStart.class.getClassLoader().getResource("").getPath();
23 | File certChain = new File(filePath.concat("server1-public-ca.pem"));
24 | File privateKey = new File(filePath.concat("server1-private.key"));
25 |
26 | SslContextBuilder scb = SslContextBuilder.forServer(certChain,privateKey);
27 | SslProvider sp = SslProvider.OPENSSL;
28 | GrpcSslContexts.configure(scb, sp);
29 | SslContext sslContext1 = scb.build();
30 |
31 | SocketAddress socketAddress = new InetSocketAddress("127.0.0.1",PORT);
32 | server = NettyServerBuilder.forAddress(socketAddress)
33 | .sslContext(sslContext1)
34 | .addService(new SimpleServer().bindService()).build();
35 | server.start();
36 |
37 | Runtime.getRuntime().addShutdownHook(new Thread(){
38 | @Override
39 | public void run(){
40 | System.err.println("*** shutting down gRPC server since JVM is shutting down");
41 | SimpleServerStart.this.stop();
42 | System.err.println("*** server shut down");
43 | }
44 | });
45 | }
46 |
47 | private void stop(){
48 | try {
49 | server.awaitTermination(2, TimeUnit.SECONDS);
50 | } catch (InterruptedException e) {
51 | e.printStackTrace();
52 | }
53 | }
54 |
55 | public static void main(String[] args) throws Exception {
56 | final SimpleServerStart simpleServerStart = new SimpleServerStart();
57 | simpleServerStart.start();
58 | TimeUnit.SECONDS.sleep(300);
59 |
60 | }
61 |
62 | }
63 |
64 |
--------------------------------------------------------------------------------
/grpc-demo-encryption/src/main/resources/cert.csr:
--------------------------------------------------------------------------------
1 | -----BEGIN CERTIFICATE REQUEST-----
2 | MIIB5DCCAU0CAQAweTELMAkGA1UEBhMCZ3oxDDAKBgNVBAgMA3l5YzELMAkGA1UE
3 | BwwCZ3oxDDAKBgNVBAoMA3l5YzEMMAoGA1UECwwDeXljMRIwEAYDVQQDDAkxMjcu
4 | MC4wLjExHzAdBgkqhkiG9w0BCQEWEDM3MzI2MDg2NUBxcS5jb20wgZ8wDQYJKoZI
5 | hvcNAQEBBQADgY0AMIGJAoGBAMCUp4Tq3oUPhG212E0SY4tnM6pCDZ+7zdOnTVnG
6 | 3T/z7e4gcrCKLDP/gk1/2C4jEdyBHJ/KMM5Pt3n21VXwkyLk+lfwSI8Nj6UrzylU
7 | u2jFO3XFaJr85eDzuOkgoxZ6G8bBiKcGffV6HrCnyzxRIRwlJVNCuKAzYumqYKFe
8 | qrUTAgMBAAGgKzASBgkqhkiG9w0BCQIxBQwDeXljMBUGCSqGSIb3DQEJBzEIDAYx
9 | MjM0NTYwDQYJKoZIhvcNAQEFBQADgYEAI7z4Z7HPQVp0sRE8UX916n+OuODQSf+Y
10 | klD7jfZbOOSHz+TRudAaXSpqd0gmRJBZwfwuoEC5wVpgaZZLONKTd0txYxf8kmqF
11 | vgYm335YXpI8xFG4obkuEWyCrndZKYsvDPhvFrVzPcRA2YcXmpzGdwDGmnkdMNZq
12 | /LL/+1TqI/s=
13 | -----END CERTIFICATE REQUEST-----
14 |
--------------------------------------------------------------------------------
/grpc-demo-encryption/src/main/resources/demo-private.pem:
--------------------------------------------------------------------------------
1 | -----BEGIN PRIVATE KEY-----
2 | MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAMCUp4Tq3oUPhG21
3 | 2E0SY4tnM6pCDZ+7zdOnTVnG3T/z7e4gcrCKLDP/gk1/2C4jEdyBHJ/KMM5Pt3n2
4 | 1VXwkyLk+lfwSI8Nj6UrzylUu2jFO3XFaJr85eDzuOkgoxZ6G8bBiKcGffV6HrCn
5 | yzxRIRwlJVNCuKAzYumqYKFeqrUTAgMBAAECgYAeVkydb7JmG6+s6LyOR5tO1o8Y
6 | /xbOVvNxqCVTQzSPYonUvV/T17Bm8JVCSCVx/yxNJDmyIlPV7FDm8a9hvmgvDNRI
7 | 64l2NlGXf3yMnohVcS4LVfgX5eQKaySmj9HRL7qDFE8DzOhMv55TGQYSDRrZL9iu
8 | SdsQodFX04o1/NE6gQJBAPH3tpjJpk0D/yOjvCzVgmjdD1G7awd0QFW7CpNEl40x
9 | MLV1hGvkh76iDcfmips/jEUaK8dHHQ1HEgAeAbgGaeMCQQDLv7w5x6spsBql+VWr
10 | 5Dbc0+xaZezcDb0z/AqtscmTD5y4zjKsjLEU+ddcPnsUSMIYiJJw/sqKiRrkO9dR
11 | jy8RAkEAxFKObs0+B0L04j/ZUC80Dk0+PrxoDLY/9M87t11x8Xc15CUjej8D/KKT
12 | t9vQHkKjVvXzC08hvUIq0rmF/4AErQJAKXN/gq3Jd7i5Iy0frdHHC5Qd0KJN1tMA
13 | vBO5xG6YGNAjTUG983bIDAFsO/sGJTFMM5uNV2muoRKVovs9qf0cUQJAZvL6BTQU
14 | pREMRImlQ42Ja/P9Q21p2wS7GmvaaF47WYGCXYEOPpI0VNirNTCt/hbiWXAV8ZJy
15 | HIch189xLB77bA==
16 | -----END PRIVATE KEY-----
17 |
--------------------------------------------------------------------------------
/grpc-demo-encryption/src/main/resources/demo-public.pem:
--------------------------------------------------------------------------------
1 | -----BEGIN PUBLIC KEY-----
2 | MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDAlKeE6t6FD4RttdhNEmOLZzOq
3 | Qg2fu83Tp01Zxt0/8+3uIHKwiiwz/4JNf9guIxHcgRyfyjDOT7d59tVV8JMi5PpX
4 | 8EiPDY+lK88pVLtoxTt1xWia/OXg87jpIKMWehvGwYinBn31eh6wp8s8USEcJSVT
5 | QrigM2LpqmChXqq1EwIDAQAB
6 | -----END PUBLIC KEY-----
7 |
--------------------------------------------------------------------------------
/grpc-demo-encryption/src/main/resources/public.der:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yeyincai/grpc-demo/ad9b126bf3e0e8268534ef093c8021a4ca30ef29/grpc-demo-encryption/src/main/resources/public.der
--------------------------------------------------------------------------------
/grpc-demo-encryption/src/main/resources/public.pem:
--------------------------------------------------------------------------------
1 | -----BEGIN CERTIFICATE-----
2 | MIICaTCCAdICCQCXS62Q+Hzl9jANBgkqhkiG9w0BAQUFADB5MQswCQYDVQQGEwJn
3 | ejEMMAoGA1UECAwDeXljMQswCQYDVQQHDAJnejEMMAoGA1UECgwDeXljMQwwCgYD
4 | VQQLDAN5eWMxEjAQBgNVBAMMCTEyNy4wLjAuMTEfMB0GCSqGSIb3DQEJARYQMzcz
5 | MjYwODY1QHFxLmNvbTAeFw0xNjA5MDcwNjIxNDZaFw0yNjA5MDUwNjIxNDZaMHkx
6 | CzAJBgNVBAYTAmd6MQwwCgYDVQQIDAN5eWMxCzAJBgNVBAcMAmd6MQwwCgYDVQQK
7 | DAN5eWMxDDAKBgNVBAsMA3l5YzESMBAGA1UEAwwJMTI3LjAuMC4xMR8wHQYJKoZI
8 | hvcNAQkBFhAzNzMyNjA4NjVAcXEuY29tMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCB
9 | iQKBgQDAlKeE6t6FD4RttdhNEmOLZzOqQg2fu83Tp01Zxt0/8+3uIHKwiiwz/4JN
10 | f9guIxHcgRyfyjDOT7d59tVV8JMi5PpX8EiPDY+lK88pVLtoxTt1xWia/OXg87jp
11 | IKMWehvGwYinBn31eh6wp8s8USEcJSVTQrigM2LpqmChXqq1EwIDAQABMA0GCSqG
12 | SIb3DQEBBQUAA4GBALgejoArXcyTvGLlOillAjGMsmjCg51EcSvOJYqMU9FkQ5mm
13 | 1WzieYnN+73+mGN9DWVcnMNttVDTwGGVJRfZBhtulhoqJHj2Ve4OnnmY0ypo8mjP
14 | 5qz3XIIDOZ2MWIx01tbmFCT/qm7Rcel6TkQ5fvSMbMZMX86F1aHlojm42qXV
15 | -----END CERTIFICATE-----
16 |
--------------------------------------------------------------------------------
/grpc-demo-encryption/src/main/resources/public1.pem:
--------------------------------------------------------------------------------
1 | -----BEGIN CERTIFICATE-----
2 | MIIB+zCCAWQCCQDU8BL+7JM7ozANBgkqhkiG9w0BAQUFADBCMQswCQYDVQQGEwJY
3 | WDEVMBMGA1UEBwwMRGVmYXVsdCBDaXR5MRwwGgYDVQQKDBNEZWZhdWx0IENvbXBh
4 | bnkgTHRkMB4XDTE2MDkwNzExMzQyNloXDTI2MDkwNTExMzQyNlowQjELMAkGA1UE
5 | BhMCWFgxFTATBgNVBAcMDERlZmF1bHQgQ2l0eTEcMBoGA1UECgwTRGVmYXVsdCBD
6 | b21wYW55IEx0ZDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAwJSnhOrehQ+E
7 | bbXYTRJji2czqkINn7vN06dNWcbdP/Pt7iBysIosM/+CTX/YLiMR3IEcn8owzk+3
8 | efbVVfCTIuT6V/BIjw2PpSvPKVS7aMU7dcVomvzl4PO46SCjFnobxsGIpwZ99Xoe
9 | sKfLPFEhHCUlU0K4oDNi6apgoV6qtRMCAwEAATANBgkqhkiG9w0BAQUFAAOBgQBH
10 | U1h6v06eiElUWz8mn6Ku+xTLEwCSxz4HqiCmKJckXPGdgHj51PCnYQ0AJxaqq1e9
11 | SgrS9ihtfgf30Sv/Mi1FjKkjDnJryeb57OPpyXDBnbUU7JpOnXzPtKkzuyHHFRBC
12 | 5BEwuIHtQCIyXeWivFggU2ye8cAgfOU0IraL+2i6QA==
13 | -----END CERTIFICATE-----
14 |
--------------------------------------------------------------------------------
/grpc-demo-encryption/src/main/resources/server1-private.key:
--------------------------------------------------------------------------------
1 | -----BEGIN PRIVATE KEY-----
2 | MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAOHDFScoLCVJpYDD
3 | M4HYtIdV6Ake/sMNaaKdODjDMsux/4tDydlumN+fm+AjPEK5GHhGn1BgzkWF+slf
4 | 3BxhrA/8dNsnunstVA7ZBgA/5qQxMfGAq4wHNVX77fBZOgp9VlSMVfyd9N8YwbBY
5 | AckOeUQadTi2X1S6OgJXgQ0m3MWhAgMBAAECgYAn7qGnM2vbjJNBm0VZCkOkTIWm
6 | V10okw7EPJrdL2mkre9NasghNXbE1y5zDshx5Nt3KsazKOxTT8d0Jwh/3KbaN+YY
7 | tTCbKGW0pXDRBhwUHRcuRzScjli8Rih5UOCiZkhefUTcRb6xIhZJuQy71tjaSy0p
8 | dHZRmYyBYO2YEQ8xoQJBAPrJPhMBkzmEYFtyIEqAxQ/o/A6E+E4w8i+KM7nQCK7q
9 | K4JXzyXVAjLfyBZWHGM2uro/fjqPggGD6QH1qXCkI4MCQQDmdKeb2TrKRh5BY1LR
10 | 81aJGKcJ2XbcDu6wMZK4oqWbTX2KiYn9GB0woM6nSr/Y6iy1u145YzYxEV/iMwff
11 | DJULAkB8B2MnyzOg0pNFJqBJuH29bKCcHa8gHJzqXhNO5lAlEbMK95p/P2Wi+4Hd
12 | aiEIAF1BF326QJcvYKmwSmrORp85AkAlSNxRJ50OWrfMZnBgzVjDx3xG6KsFQVk2
13 | ol6VhqL6dFgKUORFUWBvnKSyhjJxurlPEahV6oo6+A+mPhFY8eUvAkAZQyTdupP3
14 | XEFQKctGz+9+gKkemDp7LBBMEMBXrGTLPhpEfcjv/7KPdnFHYmhYeBTBnuVmTVWe
15 | F98XJ7tIFfJq
16 | -----END PRIVATE KEY-----
--------------------------------------------------------------------------------
/grpc-demo-encryption/src/main/resources/server1-public-ca.pem:
--------------------------------------------------------------------------------
1 | -----BEGIN CERTIFICATE-----
2 | MIICnDCCAgWgAwIBAgIBBzANBgkqhkiG9w0BAQsFADBWMQswCQYDVQQGEwJBVTET
3 | MBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50ZXJuZXQgV2lkZ2l0cyBQ
4 | dHkgTHRkMQ8wDQYDVQQDEwZ0ZXN0Y2EwHhcNMTUxMTA0MDIyMDI0WhcNMjUxMTAx
5 | MDIyMDI0WjBlMQswCQYDVQQGEwJVUzERMA8GA1UECBMISWxsaW5vaXMxEDAOBgNV
6 | BAcTB0NoaWNhZ28xFTATBgNVBAoTDEV4YW1wbGUsIENvLjEaMBgGA1UEAxQRKi50
7 | ZXN0Lmdvb2dsZS5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAOHDFSco
8 | LCVJpYDDM4HYtIdV6Ake/sMNaaKdODjDMsux/4tDydlumN+fm+AjPEK5GHhGn1Bg
9 | zkWF+slf3BxhrA/8dNsnunstVA7ZBgA/5qQxMfGAq4wHNVX77fBZOgp9VlSMVfyd
10 | 9N8YwbBYAckOeUQadTi2X1S6OgJXgQ0m3MWhAgMBAAGjazBpMAkGA1UdEwQCMAAw
11 | CwYDVR0PBAQDAgXgME8GA1UdEQRIMEaCECoudGVzdC5nb29nbGUuZnKCGHdhdGVy
12 | em9vaS50ZXN0Lmdvb2dsZS5iZYISKi50ZXN0LnlvdXR1YmUuY29thwTAqAEDMA0G
13 | CSqGSIb3DQEBCwUAA4GBAJFXVifQNub1LUP4JlnX5lXNlo8FxZ2a12AFQs+bzoJ6
14 | hM044EDjqyxUqSbVePK0ni3w1fHQB5rY9yYC5f8G7aqqTY1QOhoUk8ZTSTRpnkTh
15 | y4jjdvTZeLDVBlueZUTDRmy2feY5aZIU18vFDK08dTG0A87pppuv1LNIR3loveU8
16 | -----END CERTIFICATE-----
--------------------------------------------------------------------------------
/grpc-demo-interceptor/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 4.0.0
6 |
7 | com.yyc.grpc
8 | grpc-demo
9 | 1.0.0
10 |
11 | com.yyc.grpc
12 | grpc-demo-interceptor
13 |
14 |
15 |
16 | com.yyc.grpc
17 | grpc-contract
18 | 1.0.0
19 |
20 |
21 | io.grpc
22 | grpc-protobuf
23 | ${grpc.version}
24 |
25 |
26 | io.grpc
27 | grpc-stub
28 | ${grpc.version}
29 |
30 |
31 | io.grpc
32 | grpc-netty
33 | ${grpc.version}
34 |
35 |
36 |
37 |
--------------------------------------------------------------------------------
/grpc-demo-interceptor/src/main/java/com/grpc/demo/interceptor/SimpleClientStart.java:
--------------------------------------------------------------------------------
1 | package com.grpc.demo.interceptor;
2 |
3 |
4 | import com.google.protobuf.StringValue;
5 | import com.yyc.grpc.contract.SayHelloResponse;
6 | import com.yyc.grpc.contract.SimpleServiceGrpc;
7 | import io.grpc.*;
8 | import io.grpc.netty.NettyChannelBuilder;
9 | import io.grpc.stub.MetadataUtils;
10 |
11 | import java.util.concurrent.TimeUnit;
12 |
13 | public class SimpleClientStart {
14 |
15 | private ManagedChannel managedChannel;
16 | private int PORT = 8888;
17 |
18 | private void createChannel(){
19 | managedChannel = NettyChannelBuilder.forAddress("localhost",PORT).usePlaintext(true)
20 | .intercept(new ClientRequestInterceptor(),new ClientResponseInterceptor() )
21 | .build();
22 | }
23 |
24 | private void shutdown(){
25 | if(managedChannel!=null){
26 | try {
27 | managedChannel.shutdown().awaitTermination(2, TimeUnit.SECONDS);
28 | } catch (InterruptedException e) {
29 | e.printStackTrace();
30 | }
31 | }
32 | }
33 |
34 | public static void main(String[] args) {
35 | SimpleClientStart simpleClientStart = new SimpleClientStart();
36 | simpleClientStart.createChannel();
37 | SimpleServiceGrpc.SimpleServiceBlockingStub simpleServiceStub = SimpleServiceGrpc.newBlockingStub(simpleClientStart.managedChannel);
38 |
39 | //add metadata
40 | Metadata metadata = new Metadata();
41 | metadata.put(Metadata.Key.of("extendKey", Metadata.ASCII_STRING_MARSHALLER), "extendValue");
42 | MetadataUtils.attachHeaders(simpleServiceStub,metadata);
43 | SayHelloResponse sayHelloResponse = simpleServiceStub.sayHello(StringValue.newBuilder().setValue("grpc-interceptor-demo").build());
44 | System.out.println("response:"+sayHelloResponse.getResult());
45 | simpleClientStart.shutdown();
46 | }
47 |
48 | class ClientRequestInterceptor implements ClientInterceptor {
49 | @Override
50 | public ClientCall interceptCall(MethodDescriptor method,
51 | CallOptions callOptions, Channel next) {
52 | return new ForwardingClientCall.SimpleForwardingClientCall(next.newCall(method, callOptions)) {
53 | @Override
54 | public void start(ClientCall.Listener responseListener, Metadata headers) {
55 | Metadata.Key metaDataKey = Metadata.Key.of("Client-request", Metadata.ASCII_STRING_MARSHALLER);
56 | headers.put(metaDataKey, "Client-request-extend-value");
57 | super.start(responseListener, headers);
58 | }
59 | };
60 | }
61 | }
62 |
63 | class ClientResponseInterceptor implements ClientInterceptor {
64 |
65 | @Override
66 | public ClientCall interceptCall(MethodDescriptor method,
67 | CallOptions callOptions, Channel next) {
68 | return new ForwardingClientCall.SimpleForwardingClientCall(next.newCall(method, callOptions)) {
69 | @Override
70 | public void start(Listener responseListener, Metadata headers) {
71 | super.start(new ForwardingClientCallListener.SimpleForwardingClientCallListener(
72 | responseListener) {
73 | @Override
74 | public void onHeaders(Metadata headers) {
75 | Metadata.Key metaDataKey = Metadata.Key.of("Server-Request",Metadata.ASCII_STRING_MARSHALLER);
76 | System.out.println(headers.get(metaDataKey));
77 | super.onHeaders(headers);
78 | }
79 | }, headers);
80 | }
81 | };
82 | }
83 | }
84 | }
85 |
--------------------------------------------------------------------------------
/grpc-demo-interceptor/src/main/java/com/grpc/demo/interceptor/SimpleServer.java:
--------------------------------------------------------------------------------
1 | package com.grpc.demo.interceptor;
2 |
3 | import com.yyc.grpc.contract.SayHelloResponse;
4 | import com.yyc.grpc.contract.SimpleServiceGrpc;
5 |
6 | /**
7 | * Created by yeyc on 2016/9/5.
8 | */
9 | public class SimpleServer extends SimpleServiceGrpc.SimpleServiceImplBase{
10 |
11 | @Override
12 | public void sayHello(com.google.protobuf.StringValue request,
13 | io.grpc.stub.StreamObserver responseObserver) {
14 | SayHelloResponse sayHelloResponse = SayHelloResponse.newBuilder().setResult(request.getValue().concat("hello world")).build();
15 | responseObserver.onNext(sayHelloResponse);
16 | responseObserver.onCompleted();
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/grpc-demo-interceptor/src/main/java/com/grpc/demo/interceptor/SimpleServerStart.java:
--------------------------------------------------------------------------------
1 | package com.grpc.demo.interceptor;
2 |
3 |
4 | import io.grpc.*;
5 | import io.grpc.netty.NettyServerBuilder;
6 |
7 | import java.util.concurrent.TimeUnit;
8 |
9 | public class SimpleServerStart {
10 |
11 | private int PORT=8888;
12 | private Server server;
13 |
14 | private void start() throws Exception{
15 | server = NettyServerBuilder.forPort(PORT).addService(ServerInterceptors.intercept(new SimpleServer().bindService(),new ServerRequestInterceptor(),new ServerResponseInterceptor()))
16 | .build();
17 | server.start();
18 |
19 | Runtime.getRuntime().addShutdownHook(new Thread(){
20 | @Override
21 | public void run(){
22 | System.err.println("*** shutting down gRPC server since JVM is shutting down");
23 | SimpleServerStart.this.stop();
24 | System.err.println("*** server shut down");
25 | }
26 | });
27 | }
28 |
29 | private void stop(){
30 | try {
31 | server.awaitTermination(2, TimeUnit.SECONDS);
32 | } catch (InterruptedException e) {
33 | e.printStackTrace();
34 | }
35 | }
36 |
37 | public static void main(String[] args) throws Exception {
38 | final SimpleServerStart simpleServerStart = new SimpleServerStart();
39 | simpleServerStart.start();
40 | TimeUnit.SECONDS.sleep(120);
41 | }
42 |
43 |
44 | class ServerResponseInterceptor implements ServerInterceptor {
45 | @Override
46 | public ServerCall.Listener interceptCall(ServerCall call, Metadata headers, ServerCallHandler next) {
47 | Metadata.Key metaDataKey = Metadata.Key.of("Client-request",
48 | Metadata.ASCII_STRING_MARSHALLER);
49 | System.out.println("Client-request:"+headers.get(metaDataKey));
50 | return next.startCall(call, headers);
51 | }
52 | }
53 |
54 | class ServerRequestInterceptor implements ServerInterceptor{
55 | @Override
56 | public ServerCall.Listener interceptCall(ServerCall call, Metadata headers, ServerCallHandler next) {
57 | return next.startCall(new ForwardingServerCall.SimpleForwardingServerCall(call) {
58 | @Override
59 | public void sendHeaders(Metadata responseHeaders) {
60 | responseHeaders.put(Metadata.Key.of("Server-Request", Metadata.ASCII_STRING_MARSHALLER), "ServerRequest-extendValue");
61 | super.sendHeaders(responseHeaders);
62 | }
63 | }, headers);
64 | }
65 | }
66 |
67 | }
68 |
69 |
--------------------------------------------------------------------------------
/grpc-demo-nameResolver/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 4.0.0
6 |
7 | com.yyc.grpc
8 | grpc-demo
9 | 1.0.0
10 |
11 | com.yyc.grpc
12 | grpc-demo-nameResolver
13 |
14 |
15 |
16 | com.yyc.grpc
17 | grpc-contract
18 | 1.0.0
19 |
20 |
21 | io.grpc
22 | grpc-protobuf
23 | ${grpc.version}
24 |
25 |
26 | io.grpc
27 | grpc-stub
28 | ${grpc.version}
29 |
30 |
31 | io.grpc
32 | grpc-netty
33 | ${grpc.version}
34 |
35 |
36 |
37 |
--------------------------------------------------------------------------------
/grpc-demo-nameResolver/src/main/java/com/grpc/demo/nameResolver/ServerNameResolver.java:
--------------------------------------------------------------------------------
1 | package com.grpc.demo.nameResolver;
2 |
3 | import com.google.common.annotations.VisibleForTesting;
4 | import com.google.common.base.Preconditions;
5 | import io.grpc.Attributes;
6 | import io.grpc.NameResolver;
7 | import io.grpc.ResolvedServerInfo;
8 | import io.grpc.Status;
9 | import io.grpc.internal.GrpcUtil;
10 | import io.grpc.internal.SharedResourceHolder;
11 |
12 | import javax.annotation.concurrent.GuardedBy;
13 | import java.net.InetSocketAddress;
14 | import java.net.URI;
15 | import java.util.ArrayList;
16 | import java.util.List;
17 | import java.util.concurrent.ExecutorService;
18 |
19 | /**
20 | * Created by yeyc on 2016/9/17.
21 | */
22 | public class ServerNameResolver extends NameResolver {
23 |
24 | private final String authority;
25 | private final String host;
26 | private final SharedResourceHolder.Resource executorResource;
27 | @GuardedBy("this")
28 | private boolean shutdown;
29 | @GuardedBy("this")
30 | private boolean resolving;
31 | @GuardedBy("this")
32 | private Listener listener;
33 | @GuardedBy("this")
34 | private ExecutorService executor;
35 |
36 | ServerNameResolver(String target) {
37 | URI nameUri = URI.create("//" + target);
38 | this.authority = nameUri.getAuthority();
39 | this.host = target;
40 | this.executorResource = GrpcUtil.SHARED_CHANNEL_EXECUTOR;
41 | this.executor = SharedResourceHolder.get(this.executorResource);
42 | }
43 |
44 | @Override
45 | public String getServiceAuthority() {
46 | return this.authority;
47 | }
48 |
49 | @Override
50 | public void start(Listener listener) {
51 | Preconditions.checkState(this.listener == null, "started");
52 | this.listener = Preconditions.checkNotNull(listener, "listener");
53 | resolve();
54 | }
55 |
56 | @Override
57 | public void shutdown() {
58 | if (!this.shutdown) {
59 | this.shutdown = true;
60 | if (this.executor != null) {
61 | this.executor = SharedResourceHolder.release(this.executorResource, this.executor);
62 | }
63 | }
64 | }
65 |
66 | @GuardedBy("this")
67 | private void resolve() {
68 | if (!this.resolving && !this.shutdown) {
69 | this.executor.execute(this.resolutionRunnable);
70 | }
71 | }
72 |
73 | public final synchronized void refresh() {
74 | Preconditions.checkState(this.listener != null, "not started");
75 | resolve();
76 | }
77 |
78 |
79 | private final Runnable resolutionRunnable = new Runnable() {
80 | public void run() {
81 | Listener savedListener;
82 | synchronized (ServerNameResolver.this) {
83 | if (ServerNameResolver.this.shutdown) {
84 | return;
85 | }
86 | savedListener = ServerNameResolver.this.listener;
87 | ServerNameResolver.this.resolving = true;
88 | }
89 |
90 | try {
91 | label142:
92 | {
93 | InetSocketAddress[] inetSocketAddresses;
94 | try {
95 | inetSocketAddresses = ServerNameResolver.this.getAllByName(ServerNameResolver.this.host);
96 | } catch (Exception var22) {
97 | savedListener.onError(Status.UNAVAILABLE.withCause(var22));
98 | break label142;
99 | }
100 |
101 | List> serversList = new ArrayList<>();
102 |
103 | List var25 = new ArrayList(inetSocketAddresses.length);
104 | for (int var6 = 0; var6 < inetSocketAddresses.length; ++var6) {
105 | InetSocketAddress inetSocketAddress = inetSocketAddresses[var6];
106 | var25.add(new ResolvedServerInfo(new InetSocketAddress(inetSocketAddress.getHostName(), inetSocketAddress.getPort()), Attributes.EMPTY));
107 |
108 | }
109 | serversList.add(var25);
110 | List var26 =var25;
111 | serversList.add(var26);
112 | savedListener.onUpdate(serversList, Attributes.EMPTY);
113 | }
114 | } finally {
115 | synchronized (ServerNameResolver.this) {
116 | ServerNameResolver.this.resolving = false;
117 | }
118 | }
119 | }
120 | };
121 |
122 | @VisibleForTesting
123 | InetSocketAddress[] getAllByName(String host) {
124 | String[] hostArray = host.split(",");
125 | InetSocketAddress[] inetAddresses = new InetSocketAddress[hostArray.length];
126 |
127 | for (int i = 0; i < inetAddresses.length; ++i) {
128 | String[] temp = hostArray[i].split(":");
129 | if (temp.length < 2) {
130 | throw new RuntimeException("fail to format host for curr host " + hostArray[i]);
131 | }
132 |
133 | try {
134 | int e = Integer.parseInt(temp[1].trim());
135 | inetAddresses[i] = InetSocketAddress.createUnresolved(temp[0].trim(), e);
136 | } catch (NumberFormatException var7) {
137 | throw new RuntimeException("fail to format port for curr host " + hostArray[i]);
138 | }
139 | }
140 |
141 | return inetAddresses;
142 | }
143 |
144 |
145 | }
146 |
--------------------------------------------------------------------------------
/grpc-demo-nameResolver/src/main/java/com/grpc/demo/nameResolver/ServerNameResolverProvider.java:
--------------------------------------------------------------------------------
1 | package com.grpc.demo.nameResolver;
2 |
3 |
4 | import com.google.common.base.Preconditions;
5 | import io.grpc.Attributes;
6 | import io.grpc.NameResolver;
7 | import io.grpc.NameResolverProvider;
8 |
9 | import javax.annotation.Nullable;
10 | import java.net.URI;
11 |
12 | public class ServerNameResolverProvider extends NameResolverProvider{
13 |
14 | private static final String SCHEME="server";
15 |
16 | @Override
17 | protected boolean isAvailable() {
18 | return true;
19 | }
20 |
21 | @Override
22 | protected int priority() {
23 | return 5;
24 | }
25 |
26 | @Nullable
27 | @Override
28 | public NameResolver newNameResolver(URI targetUri, Attributes params) {
29 | if(targetUri.getScheme().equals(SCHEME)){
30 | String targetPath = Preconditions.checkNotNull(targetUri.getAuthority(), "authority is not null");
31 | return new ServerNameResolver(targetPath);
32 | }else {
33 | throw new RuntimeException("the targetUri scheme must be server");
34 | }
35 | }
36 |
37 | @Override
38 | public String getDefaultScheme() {
39 | return SCHEME;
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/grpc-demo-nameResolver/src/main/java/com/grpc/demo/nameResolver/SimpleClientStart.java:
--------------------------------------------------------------------------------
1 | package com.grpc.demo.nameResolver;
2 |
3 |
4 | import com.google.protobuf.StringValue;
5 | import com.yyc.grpc.contract.SayHelloResponse;
6 | import com.yyc.grpc.contract.SimpleServiceGrpc;
7 | import io.grpc.ManagedChannel;
8 | import io.grpc.netty.NettyChannelBuilder;
9 | import io.grpc.util.RoundRobinLoadBalancerFactory;
10 |
11 | import java.util.concurrent.TimeUnit;
12 |
13 | public class SimpleClientStart {
14 |
15 | private ManagedChannel managedChannel;
16 |
17 | private void createChannel(){
18 | managedChannel = NettyChannelBuilder
19 | .forTarget("server://127.0.0.1:9999,127.0.0.1:8888")
20 | .nameResolverFactory(new ServerNameResolverProvider())
21 | .loadBalancerFactory(RoundRobinLoadBalancerFactory.getInstance())
22 | .usePlaintext(true).build();
23 | }
24 |
25 | private void shutdown(){
26 | if(managedChannel!=null){
27 | try {
28 | managedChannel.shutdown().awaitTermination(2, TimeUnit.SECONDS);
29 | } catch (InterruptedException e) {
30 | e.printStackTrace();
31 | }
32 | }
33 | }
34 |
35 | public static void main(String[] args) {
36 | SimpleClientStart simpleClientStart = new SimpleClientStart();
37 | simpleClientStart.createChannel();
38 | SimpleServiceGrpc.SimpleServiceBlockingStub simpleServiceStub = SimpleServiceGrpc.newBlockingStub(simpleClientStart.managedChannel);
39 |
40 | for (int i=0;i<100;i++) {
41 |
42 | SayHelloResponse sayHelloResponse = simpleServiceStub.sayHello(StringValue.newBuilder().setValue("grpc-nameResolver-demo").build());
43 | System.out.println("response:" + sayHelloResponse.getResult());
44 | try {
45 | TimeUnit.SECONDS.sleep(1);
46 | } catch (InterruptedException e){
47 |
48 |
49 | }
50 |
51 | }
52 | simpleClientStart.shutdown();
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/grpc-demo-nameResolver/src/main/java/com/grpc/demo/nameResolver/SimpleServer.java:
--------------------------------------------------------------------------------
1 | package com.grpc.demo.nameResolver;
2 |
3 | import com.yyc.grpc.contract.SayHelloResponse;
4 | import com.yyc.grpc.contract.SimpleServiceGrpc;
5 |
6 | /**
7 | * Created by yeyc on 2016/9/5.
8 | */
9 | public class SimpleServer extends SimpleServiceGrpc.SimpleServiceImplBase{
10 |
11 | @Override
12 | public void sayHello(com.google.protobuf.StringValue request,
13 | io.grpc.stub.StreamObserver responseObserver) {
14 | System.out.println("11111111111111");
15 | SayHelloResponse sayHelloResponse = SayHelloResponse.newBuilder().setResult(request.getValue().concat("hello world")).build();
16 | responseObserver.onNext(sayHelloResponse);
17 | responseObserver.onCompleted();
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/grpc-demo-nameResolver/src/main/java/com/grpc/demo/nameResolver/SimpleServerStart1.java:
--------------------------------------------------------------------------------
1 | package com.grpc.demo.nameResolver;
2 |
3 |
4 | import io.grpc.Server;
5 | import io.grpc.netty.NettyServerBuilder;
6 |
7 | import java.util.concurrent.TimeUnit;
8 |
9 | public class SimpleServerStart1 {
10 |
11 | private int PORT=8888;
12 | private Server server;
13 |
14 | private void start() throws Exception{
15 | server = NettyServerBuilder.forPort(PORT).addService(new SimpleServer().bindService()).build();
16 | server.start();
17 |
18 | Runtime.getRuntime().addShutdownHook(new Thread(){
19 | @Override
20 | public void run(){
21 | System.err.println("*** shutting down gRPC server since JVM is shutting down");
22 | SimpleServerStart1.this.stop();
23 | System.err.println("*** server shut down");
24 | }
25 | });
26 | }
27 |
28 | private void stop(){
29 | try {
30 | server.awaitTermination(2, TimeUnit.SECONDS);
31 | } catch (InterruptedException e) {
32 | e.printStackTrace();
33 | }
34 | }
35 |
36 | public static void main(String[] args) throws Exception {
37 | final SimpleServerStart1 simpleServerStart = new SimpleServerStart1();
38 | simpleServerStart.start();
39 | TimeUnit.SECONDS.sleep(3000);
40 | }
41 |
42 | }
43 |
44 |
--------------------------------------------------------------------------------
/grpc-demo-nameResolver/src/main/java/com/grpc/demo/nameResolver/SimpleServerStart2.java:
--------------------------------------------------------------------------------
1 | package com.grpc.demo.nameResolver;
2 |
3 |
4 | import io.grpc.Server;
5 | import io.grpc.netty.NettyServerBuilder;
6 |
7 | import java.net.InetAddress;
8 | import java.net.UnknownHostException;
9 | import java.util.concurrent.TimeUnit;
10 |
11 | public class SimpleServerStart2 {
12 |
13 | private int PORT=9999;
14 | private Server server;
15 |
16 | private void start() throws Exception{
17 | server = NettyServerBuilder.forPort(PORT).addService(new SimpleServer().bindService()).build();
18 | server.start();
19 |
20 | Runtime.getRuntime().addShutdownHook(new Thread(){
21 | @Override
22 | public void run(){
23 | System.err.println("*** shutting down gRPC server since JVM is shutting down");
24 | SimpleServerStart2.this.stop();
25 | System.err.println("*** server shut down");
26 | }
27 | });
28 | }
29 |
30 | private void stop(){
31 | try {
32 | server.awaitTermination(2, TimeUnit.SECONDS);
33 | } catch (InterruptedException e) {
34 | e.printStackTrace();
35 | }
36 | }
37 |
38 | public static void main(String[] args) throws Exception {
39 | final SimpleServerStart2 simpleServerStart = new SimpleServerStart2();
40 | simpleServerStart.start();
41 | TimeUnit.SECONDS.sleep(3000);
42 | }
43 |
44 | public static void main1(String[] args) throws UnknownHostException {
45 | InetAddress[] allByName = InetAddress.getAllByName("www.ppmoney.com");
46 |
47 | for(int i=0;i
2 |
5 | 4.0.0
6 |
7 | com.yyc.grpc
8 | grpc-demo
9 | 1.0.0
10 |
11 | com.yyc.grpc
12 | grpc-demo-oneof
13 |
14 |
15 |
16 | com.yyc.grpc
17 | grpc-contract
18 | 1.0.0
19 |
20 |
21 | io.grpc
22 | grpc-protobuf
23 | ${grpc.version}
24 |
25 |
26 | io.grpc
27 | grpc-stub
28 | ${grpc.version}
29 |
30 |
31 | io.grpc
32 | grpc-netty
33 | ${grpc.version}
34 |
35 |
36 |
37 | com.linkedin.parseq
38 | parseq
39 | 2.6.3
40 |
41 |
42 |
43 |
--------------------------------------------------------------------------------
/grpc-demo-oneof/src/main/java/com/grpc/demo/oneof/AbstractTask.java:
--------------------------------------------------------------------------------
1 | package com.grpc.demo.oneof;
2 |
3 |
4 | import io.grpc.stub.StreamObserver;
5 |
6 | import java.util.concurrent.CountDownLatch;
7 |
8 | abstract class AbstractTask implements Runnable {
9 |
10 |
11 | private CountDownLatch counter;
12 |
13 | private StreamObserver so;
14 |
15 | public AbstractTask(CountDownLatch counter, StreamObserver so) {
16 | this.counter = counter;
17 | this.so = so;
18 | }
19 |
20 | @Override
21 | public void run() {
22 | try {
23 | Object result = invoke();
24 | synchronized (so) {
25 |
26 | so.onNext(result);
27 | }
28 | } catch (Exception e) {
29 | } finally {
30 | counter.countDown();
31 |
32 | }
33 | }
34 |
35 | abstract com.yyc.grpc.contract.GetAllResponse invoke();
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/grpc-demo-oneof/src/main/java/com/grpc/demo/oneof/SimpleClientStart.java:
--------------------------------------------------------------------------------
1 | package com.grpc.demo.oneof;
2 |
3 |
4 | import com.google.protobuf.Empty;
5 | import com.yyc.grpc.contract.GetAllResponse;
6 | import com.yyc.grpc.contract.SimpleServiceGrpc;
7 | import io.grpc.ManagedChannel;
8 | import io.grpc.netty.NettyChannelBuilder;
9 |
10 | import java.util.Iterator;
11 | import java.util.concurrent.TimeUnit;
12 |
13 | public class SimpleClientStart {
14 |
15 | private ManagedChannel managedChannel;
16 | private int PORT = 8888;
17 |
18 | private void createChannel(){
19 | managedChannel = NettyChannelBuilder.forAddress("localhost",PORT).usePlaintext(true).build();
20 | }
21 |
22 | private void shutdown(){
23 | if(managedChannel!=null){
24 | try {
25 | managedChannel.shutdown().awaitTermination(2, TimeUnit.SECONDS);
26 | } catch (InterruptedException e) {
27 | e.printStackTrace();
28 | }
29 | }
30 | }
31 |
32 | public static void main(String[] args) {
33 | SimpleClientStart simpleClientStart = new SimpleClientStart();
34 | simpleClientStart.createChannel();
35 | SimpleServiceGrpc.SimpleServiceBlockingStub simpleServiceStub = SimpleServiceGrpc.newBlockingStub(simpleClientStart.managedChannel);
36 |
37 | Long start = System.currentTimeMillis();
38 |
39 | SimpleExecutor simpleExecutor = new SimpleExecutor(()->{
40 | Iterator all = simpleServiceStub.getAll(Empty.getDefaultInstance());
41 | while (all.hasNext()) {
42 | GetAllResponse response = all.next();
43 | //System.out.println("response:"+response);
44 | }
45 | });
46 |
47 | simpleExecutor.execute(100,30);
48 |
49 | //this time <3 second
50 | System.out.println("spend time :"+(System.currentTimeMillis()-start));
51 |
52 | simpleClientStart.shutdown();
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/grpc-demo-oneof/src/main/java/com/grpc/demo/oneof/SimpleExecutor.java:
--------------------------------------------------------------------------------
1 | package com.grpc.demo.oneof;
2 |
3 | import com.google.common.base.Preconditions;
4 |
5 |
6 | import java.util.concurrent.atomic.AtomicBoolean;
7 | import java.util.concurrent.atomic.AtomicLong;
8 |
9 | public class SimpleExecutor {
10 | private final Runnable task;
11 | private final AtomicLong counter = new AtomicLong(0L);
12 | private final AtomicBoolean stopFlag = new AtomicBoolean(false);
13 | final int threadCount = 100;
14 |
15 | public SimpleExecutor(Runnable task) {
16 | Preconditions.checkNotNull(task, "task should not be null");
17 | this.task = task;
18 | }
19 |
20 | public void execute(int threadCount, int durationInSeconds) {
21 | Preconditions.checkArgument(threadCount > 0, "threadCount must bigger than 0");
22 | Preconditions.checkArgument(durationInSeconds > 0, "durationInSeconds must bigger than 0");
23 |
24 | for(int firstStartTime = 0; firstStartTime < threadCount; ++firstStartTime) {
25 | int threadNumber = firstStartTime + 1;
26 | Thread startTime = new Thread(() -> {
27 | while(!this.stopFlag.get()) {
28 | try {
29 | this.task.run();
30 | this.counter.incrementAndGet();
31 | } catch (Exception var3) {
32 | var3.printStackTrace();
33 | }
34 | }
35 |
36 | System.err.println("*** work thread " + threadNumber + " quit ***");
37 | });
38 | startTime.setDaemon(true);
39 | startTime.start();
40 | }
41 |
42 | Runtime.getRuntime().addShutdownHook(new Thread() {
43 | public void run() {
44 | System.err.println("*** stop client ***");
45 | SimpleExecutor.this.stopFlag.set(true);
46 | }
47 | });
48 | long var14 = System.currentTimeMillis();
49 |
50 | for(long var15 = System.currentTimeMillis(); !this.stopFlag.get(); var15 = System.currentTimeMillis()) {
51 | if(System.currentTimeMillis() - var14 >= (long)(durationInSeconds * 1000)) {
52 | System.out.println("durationInSeconds timeout, begin to stop work thread");
53 | this.stopFlag.set(true);
54 | break;
55 | }
56 |
57 | try {
58 | Thread.sleep(1000L);
59 | } catch (InterruptedException var13) {
60 | ;
61 | }
62 |
63 | long count = this.counter.get();
64 | long currentTime = System.currentTimeMillis();
65 | long qps = count * 1000L / (currentTime - var15);
66 | System.out.println("qps=" + qps);
67 | this.counter.set(0L);
68 | }
69 |
70 | System.out.println("task executed success");
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/grpc-demo-oneof/src/main/java/com/grpc/demo/oneof/SimpleServer.java:
--------------------------------------------------------------------------------
1 | package com.grpc.demo.oneof;
2 |
3 | import com.yyc.grpc.contract.GetAllResponse;
4 | import com.yyc.grpc.contract.SimpleServiceGrpc;
5 |
6 | import java.util.concurrent.CountDownLatch;
7 | import java.util.concurrent.ExecutorService;
8 | import java.util.concurrent.Executors;
9 | import java.util.concurrent.TimeUnit;
10 |
11 |
12 | public class SimpleServer extends SimpleServiceGrpc.SimpleServiceImplBase{
13 |
14 | private final static ExecutorService executors = Executors.newCachedThreadPool();
15 |
16 | public void getAll(com.google.protobuf.Empty request,
17 | io.grpc.stub.StreamObserver responseObserver) {
18 | CountDownLatch counter = new CountDownLatch(3);
19 |
20 | executors.submit(new AbstractTask(counter,responseObserver){
21 | @Override
22 | GetAllResponse invoke() {
23 | try {
24 | TimeUnit.MILLISECONDS.sleep(10);
25 | } catch (InterruptedException e) {
26 | e.printStackTrace();
27 | }
28 | return GetAllResponse.newBuilder().setMember1("11111").build();
29 | }
30 | });
31 |
32 | executors.submit(new AbstractTask(counter,responseObserver){
33 | @Override
34 | GetAllResponse invoke() {
35 | try {
36 | TimeUnit.MILLISECONDS.sleep(10);
37 | } catch (InterruptedException e) {
38 | e.printStackTrace();
39 | }
40 | return GetAllResponse.newBuilder().setMember2(222222).build();
41 | }
42 | });
43 |
44 | executors.submit(new AbstractTask(counter,responseObserver){
45 | @Override
46 | GetAllResponse invoke() {
47 | try {
48 | TimeUnit.MILLISECONDS.sleep(10);
49 | } catch (InterruptedException e) {
50 | e.printStackTrace();
51 | }
52 | return GetAllResponse.newBuilder().setMember3("333333").build();
53 | }
54 | });
55 |
56 | try {
57 | counter.await();
58 | } catch (InterruptedException e) {
59 | e.printStackTrace();
60 | }
61 | responseObserver.onCompleted();
62 | //System.out.println("---------------------onCompleted ");
63 | }
64 |
65 | }
66 |
--------------------------------------------------------------------------------
/grpc-demo-oneof/src/main/java/com/grpc/demo/oneof/SimpleServerStart.java:
--------------------------------------------------------------------------------
1 | package com.grpc.demo.oneof;
2 |
3 |
4 | import io.grpc.Server;
5 | import io.grpc.netty.NettyServerBuilder;
6 |
7 | import java.util.concurrent.TimeUnit;
8 |
9 | public class SimpleServerStart {
10 |
11 | private int PORT=8888;
12 | private Server server;
13 |
14 | private void start() throws Exception{
15 | // server = NettyServerBuilder.forPort(PORT).addService(new SimpleServer().bindService()).build();
16 | //server = NettyServerBuilder.forPort(PORT).addService(new FutureSimpleServer().bindService()).build();
17 | //server = NettyServerBuilder.forPort(PORT).addService(new FutureThreadPoolSimpleServer().bindService()).build();
18 |
19 | server.start();
20 |
21 | Runtime.getRuntime().addShutdownHook(new Thread(){
22 | @Override
23 | public void run(){
24 | System.err.println("*** shutting down gRPC server since JVM is shutting down");
25 | SimpleServerStart.this.stop();
26 | System.err.println("*** server shut down");
27 | }
28 | });
29 | }
30 |
31 | private void stop(){
32 | try {
33 | server.awaitTermination(2, TimeUnit.SECONDS);
34 | } catch (InterruptedException e) {
35 | e.printStackTrace();
36 | }
37 | }
38 |
39 | public static void main(String[] args) throws Exception {
40 | final SimpleServerStart simpleServerStart = new SimpleServerStart();
41 | simpleServerStart.start();
42 | TimeUnit.SECONDS.sleep(300);
43 | }
44 |
45 | }
46 |
47 |
--------------------------------------------------------------------------------
/grpc-demo-proxy/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 4.0.0
6 |
7 | com.yyc.grpc
8 | grpc-demo
9 | 1.0.0
10 |
11 | com.yyc.grpc
12 | grpc-demo-proxy
13 |
14 |
15 |
16 | com.yyc.grpc
17 | grpc-contract
18 | 1.0.0
19 |
20 |
21 | io.grpc
22 | grpc-protobuf
23 | ${grpc.version}
24 |
25 |
26 | io.grpc
27 | grpc-stub
28 | ${grpc.version}
29 |
30 |
31 | io.grpc
32 | grpc-netty
33 | ${grpc.version}
34 |
35 |
36 | io.netty
37 | netty-buffer
38 | ${netty.version}
39 |
40 |
41 |
42 | ch.qos.logback
43 | logback-classic
44 | 1.1.7
45 |
46 |
47 |
48 |
--------------------------------------------------------------------------------
/grpc-demo-proxy/src/main/java/com/grpc/demo/proxy/SimpleClientStart.java:
--------------------------------------------------------------------------------
1 | package com.grpc.demo.proxy;
2 |
3 |
4 | import com.google.protobuf.StringValue;
5 | import com.yyc.grpc.contract.SayHelloResponse;
6 | import com.yyc.grpc.contract.SimpleServiceGrpc;
7 | import io.grpc.*;
8 | import io.grpc.netty.NettyChannelBuilder;
9 |
10 | import java.util.concurrent.atomic.AtomicInteger;
11 |
12 | public class SimpleClientStart {
13 |
14 | private int PORT = 8080;
15 | private ManagedChannel managedChannel;
16 | private ManagedChannel createChannel() {
17 | managedChannel = NettyChannelBuilder.forAddress("localhost", PORT)
18 | .intercept(new ClientRequestInterceptor()).usePlaintext(true).build();
19 | return managedChannel;
20 | }
21 |
22 | class ClientRequestInterceptor implements ClientInterceptor {
23 | @Override
24 | public ClientCall interceptCall(MethodDescriptor method,
25 | CallOptions callOptions, Channel next) {
26 | return new ForwardingClientCall.SimpleForwardingClientCall(next.newCall(method, callOptions)) {
27 | @Override
28 | public void start(ClientCall.Listener responseListener, Metadata headers) {
29 | Metadata.Key metaDataKey = Metadata.Key.of("Client-request", Metadata.ASCII_STRING_MARSHALLER);
30 | headers.put(metaDataKey, "Client-request-extend-value");
31 | super.start(responseListener, headers);
32 | }
33 | };
34 | }
35 | }
36 |
37 |
38 | public static void main(String[] args) throws InterruptedException {
39 | AtomicInteger integer = new AtomicInteger(0);
40 | SimpleClientStart simpleClientStart = new SimpleClientStart();
41 | SimpleServiceGrpc.SimpleServiceBlockingStub simpleServiceStub = SimpleServiceGrpc.newBlockingStub(simpleClientStart.createChannel());
42 | String request = "grpc-simple-demo"+integer.incrementAndGet();
43 | SayHelloResponse sayHelloResponse = simpleServiceStub.sayHello(StringValue.newBuilder().setValue(request).build());
44 | assert request.equalsIgnoreCase(sayHelloResponse.getResult());
45 | simpleClientStart.managedChannel.shutdown();
46 |
47 | if(true) {
48 | SimpleExecutor simpleExecutor = new SimpleExecutor(() -> {
49 | SimpleClientStart simpleClientStart1 = new SimpleClientStart();
50 | SimpleServiceGrpc.SimpleServiceBlockingStub simpleServiceStub1 = SimpleServiceGrpc.newBlockingStub(simpleClientStart1.createChannel());
51 | String request1 = "grpc-simple-demo"+integer.incrementAndGet();
52 | SayHelloResponse sayHelloResponse1 = simpleServiceStub1.sayHello(StringValue.newBuilder().setValue(request1).build());
53 | assert request1.equalsIgnoreCase(sayHelloResponse1.getResult());
54 | simpleClientStart1.managedChannel.shutdown();
55 | });
56 | simpleExecutor.execute(5, 100);
57 | }
58 |
59 |
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/grpc-demo-proxy/src/main/java/com/grpc/demo/proxy/SimpleExecutor.java:
--------------------------------------------------------------------------------
1 | package com.grpc.demo.proxy;
2 |
3 | import com.google.common.base.Preconditions;
4 | import org.slf4j.Logger;
5 | import org.slf4j.LoggerFactory;
6 |
7 | import java.util.concurrent.atomic.AtomicBoolean;
8 | import java.util.concurrent.atomic.AtomicLong;
9 |
10 | public class SimpleExecutor {
11 | private static Logger logger = LoggerFactory.getLogger(SimpleExecutor.class);
12 | private final Runnable task;
13 | private final AtomicLong counter = new AtomicLong(0L);
14 | private final AtomicBoolean stopFlag = new AtomicBoolean(false);
15 | final int threadCount = 100;
16 |
17 | public SimpleExecutor(Runnable task) {
18 | Preconditions.checkNotNull(task, "task should not be null");
19 | this.task = task;
20 | }
21 |
22 | public void execute(int threadCount, int durationInSeconds) {
23 | Preconditions.checkArgument(threadCount > 0, "threadCount must bigger than 0");
24 | Preconditions.checkArgument(durationInSeconds > 0, "durationInSeconds must bigger than 0");
25 |
26 | for(int firstStartTime = 0; firstStartTime < threadCount; ++firstStartTime) {
27 | int threadNumber = firstStartTime + 1;
28 | Thread startTime = new Thread(() -> {
29 | while(!this.stopFlag.get()) {
30 | try {
31 | this.task.run();
32 | this.counter.incrementAndGet();
33 | } catch (Exception var3) {
34 | var3.printStackTrace();
35 | }
36 | }
37 |
38 | System.err.println("*** work thread " + threadNumber + " quit ***");
39 | });
40 | startTime.setDaemon(true);
41 | startTime.start();
42 | }
43 |
44 | Runtime.getRuntime().addShutdownHook(new Thread() {
45 | public void run() {
46 | System.err.println("*** stop client ***");
47 | SimpleExecutor.this.stopFlag.set(true);
48 | }
49 | });
50 | long var14 = System.currentTimeMillis();
51 |
52 | for(long var15 = System.currentTimeMillis(); !this.stopFlag.get(); var15 = System.currentTimeMillis()) {
53 | if(System.currentTimeMillis() - var14 >= (long)(durationInSeconds * 1000)) {
54 | System.out.println("durationInSeconds timeout, begin to stop work thread");
55 | this.stopFlag.set(true);
56 | break;
57 | }
58 |
59 | try {
60 | Thread.sleep(1000L);
61 | } catch (InterruptedException var13) {
62 | ;
63 | }
64 |
65 | long count = this.counter.get();
66 | long currentTime = System.currentTimeMillis();
67 | long qps = count * 1000L / (currentTime - var15);
68 | System.out.println("qps=" + qps);
69 | this.counter.set(0L);
70 | }
71 |
72 | System.out.println("task executed success");
73 | }
74 | }
75 |
--------------------------------------------------------------------------------
/grpc-demo-proxy/src/main/java/com/grpc/demo/proxy/SimpleServer.java:
--------------------------------------------------------------------------------
1 | package com.grpc.demo.proxy;
2 |
3 | import com.yyc.grpc.contract.SayHelloResponse;
4 | import com.yyc.grpc.contract.SimpleServiceGrpc;
5 |
6 | /**
7 | * Created by yeyc on 2016/9/5.
8 | */
9 | public class SimpleServer extends SimpleServiceGrpc.SimpleServiceImplBase{
10 |
11 | @Override
12 | public void sayHello(com.google.protobuf.StringValue request,
13 | io.grpc.stub.StreamObserver responseObserver) {
14 |
15 | System.out.println(request.getValue());
16 | SayHelloResponse sayHelloResponse = SayHelloResponse.newBuilder().setResult(request.getValue()).build();
17 | responseObserver.onNext(sayHelloResponse);
18 | responseObserver.onCompleted();
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/grpc-demo-proxy/src/main/java/com/grpc/demo/proxy/SimpleServerStart.java:
--------------------------------------------------------------------------------
1 | package com.grpc.demo.proxy;
2 |
3 |
4 | import io.grpc.Server;
5 | import io.grpc.netty.NettyServerBuilder;
6 |
7 | import java.util.concurrent.TimeUnit;
8 |
9 | public class SimpleServerStart {
10 |
11 | public SimpleServerStart (int port){
12 | this.port = port;
13 | }
14 |
15 | private int port;
16 | private Server server;
17 |
18 | private void start() throws Exception{
19 | server = NettyServerBuilder.forPort(port).addService(new SimpleServer().bindService()).build();
20 | server.start();
21 |
22 | Runtime.getRuntime().addShutdownHook(new Thread(){
23 | @Override
24 | public void run(){
25 | System.err.println("*** shutting down gRPC server since JVM is shutting down");
26 | SimpleServerStart.this.stop();
27 | System.err.println("*** server shut down");
28 | }
29 | });
30 | }
31 |
32 | private void stop(){
33 | try {
34 | server.awaitTermination(2, TimeUnit.SECONDS);
35 | } catch (InterruptedException e) {
36 | e.printStackTrace();
37 | }
38 | }
39 |
40 | public static void main(String[] args) throws Exception {
41 | final SimpleServerStart simpleServerStart = new SimpleServerStart(8888);
42 | simpleServerStart.start();
43 |
44 | /* final SimpleServerStart simpleServerStart1 = new SimpleServerStart(8889);
45 | simpleServerStart1.start();*/
46 | TimeUnit.SECONDS.sleep(3000);
47 | }
48 |
49 | }
50 |
51 |
--------------------------------------------------------------------------------
/grpc-demo-proxy/src/main/java/com/grpc/demo/proxy/YycClientStart.java:
--------------------------------------------------------------------------------
1 | package com.grpc.demo.proxy;
2 |
3 |
4 | import com.google.protobuf.StringValue;
5 | import com.yyc.grpc.contract.SayHelloResponse;
6 | import com.yyc.grpc.contract.YycServiceGrpc;
7 | import io.grpc.ManagedChannel;
8 | import io.grpc.netty.NettyChannelBuilder;
9 |
10 | import java.util.concurrent.TimeUnit;
11 |
12 | public class YycClientStart {
13 |
14 | private ManagedChannel managedChannel;
15 | private int PORT = 8080;
16 |
17 | private void createChannel() {
18 | managedChannel = NettyChannelBuilder.forAddress("localhost", PORT).usePlaintext(true).build();
19 | }
20 |
21 | private void shutdown() {
22 | if (managedChannel != null) {
23 | try {
24 | managedChannel.shutdown().awaitTermination(2, TimeUnit.SECONDS);
25 | } catch (InterruptedException e) {
26 | e.printStackTrace();
27 | }
28 | }
29 | }
30 |
31 | public static void main(String[] args) throws InterruptedException {
32 | YycClientStart simpleClientStart = new YycClientStart();
33 | simpleClientStart.createChannel();
34 | /*************************/
35 | YycServiceGrpc.YycServiceBlockingStub yycServiceBlockingStub = YycServiceGrpc.newBlockingStub(simpleClientStart.managedChannel);
36 |
37 | SayHelloResponse sayHelloResponse1 = yycServiceBlockingStub.sayHello(StringValue.newBuilder().setValue("yyc hello").build());
38 | System.out.println("response1:" + sayHelloResponse1.getResult());
39 |
40 |
41 |
42 | SayHelloResponse sayHelloResponse2 = yycServiceBlockingStub.sayHello(StringValue.newBuilder().setValue("yyc hello").build());
43 | System.out.println("response2:" + sayHelloResponse2.getResult());
44 |
45 |
46 | SayHelloResponse sayHelloResponse3 = yycServiceBlockingStub.sayHello(StringValue.newBuilder().setValue("yyc hello").build());
47 | System.out.println("response3:" + sayHelloResponse3.getResult());
48 |
49 | simpleClientStart.managedChannel.shutdown();
50 |
51 |
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/grpc-demo-proxy/src/main/java/com/grpc/demo/proxy/YycServer.java:
--------------------------------------------------------------------------------
1 | package com.grpc.demo.proxy;
2 |
3 | import com.yyc.grpc.contract.SayHelloResponse;
4 | import com.yyc.grpc.contract.YycServiceGrpc;
5 |
6 | /**
7 | * Created by yeyc on 2016/9/5.
8 | */
9 | public class YycServer extends YycServiceGrpc.YycServiceImplBase{
10 |
11 | @Override
12 | public void sayHello(com.google.protobuf.StringValue request,
13 | io.grpc.stub.StreamObserver responseObserver) {
14 | String result =request.getValue().concat("hello world");
15 | System.out.println(result);
16 | SayHelloResponse sayHelloResponse = SayHelloResponse.newBuilder().setResult(result).build();
17 | responseObserver.onNext(sayHelloResponse);
18 | responseObserver.onCompleted();
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/grpc-demo-proxy/src/main/java/com/grpc/demo/proxy/YycServerStart.java:
--------------------------------------------------------------------------------
1 | package com.grpc.demo.proxy;
2 |
3 |
4 | import io.grpc.Server;
5 | import io.grpc.netty.NettyServerBuilder;
6 |
7 | import java.util.concurrent.TimeUnit;
8 |
9 | public class YycServerStart {
10 |
11 | public YycServerStart(int port){
12 | this.port = port;
13 | }
14 |
15 | private int port;
16 | private Server server;
17 |
18 | private void start() throws Exception{
19 | server = NettyServerBuilder.forPort(port).addService(new YycServer().bindService()).build();
20 | server.start();
21 |
22 | Runtime.getRuntime().addShutdownHook(new Thread(){
23 | @Override
24 | public void run(){
25 | System.err.println("*** shutting down gRPC server since JVM is shutting down");
26 | YycServerStart.this.stop();
27 | System.err.println("*** server shut down");
28 | }
29 | });
30 | }
31 |
32 | private void stop(){
33 | try {
34 | server.awaitTermination(2, TimeUnit.SECONDS);
35 | } catch (InterruptedException e) {
36 | e.printStackTrace();
37 | }
38 | }
39 |
40 | public static void main(String[] args) throws Exception {
41 | final YycServerStart simpleServerStart = new YycServerStart(9999);
42 | simpleServerStart.start();
43 |
44 | final YycServerStart simpleServerStart1 = new YycServerStart(9998);
45 | simpleServerStart1.start();
46 | TimeUnit.SECONDS.sleep(3000);
47 | }
48 |
49 | }
50 |
51 |
--------------------------------------------------------------------------------
/grpc-demo-proxy/src/main/java/com/grpc/demo/proxy/netty/EchoClient.java:
--------------------------------------------------------------------------------
1 | package com.grpc.demo.proxy.netty;
2 |
3 | import io.netty.bootstrap.Bootstrap;
4 | import io.netty.channel.*;
5 | import io.netty.channel.nio.NioEventLoopGroup;
6 | import io.netty.channel.socket.SocketChannel;
7 | import io.netty.channel.socket.nio.NioSocketChannel;
8 |
9 | /**
10 | * Sends one message when a connection is open and echoes back any received
11 | * data to the server. Simply put, the echo client initiates the ping-pong
12 | * traffic between the echo client and server by sending the first message to
13 | * the server.
14 | */
15 | public final class EchoClient {
16 |
17 | static final boolean SSL = System.getProperty("ssl") != null;
18 | static final String HOST = System.getProperty("host", "127.0.0.1");
19 | static final int PORT = Integer.parseInt(System.getProperty("port", "8007"));
20 | static final int SIZE = Integer.parseInt(System.getProperty("size", "256"));
21 |
22 | public static void main(String[] args) throws Exception {
23 |
24 | //SimpleExecutor simpleExecutor = new SimpleExecutor(() -> {
25 |
26 | EventLoopGroup group = new NioEventLoopGroup(1);
27 | ChannelFuture f = null;
28 | Bootstrap b = new Bootstrap();
29 | try {
30 | b.group(group)
31 | .channel(NioSocketChannel.class)
32 | .option(ChannelOption.SO_REUSEADDR, true)
33 | .handler(new ChannelInitializer() {
34 | @Override
35 | public void initChannel(SocketChannel ch) throws Exception {
36 | ChannelPipeline p = ch.pipeline();
37 | p.addLast(new EchoClientHandler());
38 | }
39 | });
40 | try {
41 | f = b.connect(HOST, PORT).sync();
42 | f.channel().closeFuture().sync();
43 | } catch (InterruptedException e) {
44 | e.printStackTrace();
45 | }
46 |
47 | } finally {
48 | group.shutdownGracefully();
49 | }
50 | //});
51 | //simpleExecutor.execute(20, 100);
52 |
53 | }
54 | }
--------------------------------------------------------------------------------
/grpc-demo-proxy/src/main/java/com/grpc/demo/proxy/netty/EchoClientHandler.java:
--------------------------------------------------------------------------------
1 | package com.grpc.demo.proxy.netty;
2 |
3 | import io.netty.buffer.ByteBuf;
4 | import io.netty.buffer.Unpooled;
5 | import io.netty.channel.ChannelHandlerContext;
6 | import io.netty.channel.ChannelInboundHandlerAdapter;
7 |
8 | /**
9 | * Handler implementation for the echo client. It initiates the ping-pong
10 | * traffic between the echo client and server by sending the first message to
11 | * the server.
12 | */
13 | public class EchoClientHandler extends ChannelInboundHandlerAdapter {
14 |
15 | private final ByteBuf firstMessage;
16 |
17 | /**
18 | * Creates a client-side handler.
19 | */
20 | public EchoClientHandler() {
21 | firstMessage = Unpooled.buffer(EchoClient.SIZE);
22 | for (int i = 0; i < firstMessage.capacity(); i ++) {
23 | firstMessage.writeByte((byte) i);
24 | }
25 | }
26 |
27 | @Override
28 | public void channelActive(ChannelHandlerContext ctx) {
29 | ctx.writeAndFlush(firstMessage);
30 | }
31 |
32 | @Override
33 | public void channelRead(ChannelHandlerContext ctx, Object msg) {
34 |
35 | ctx.writeAndFlush(msg);
36 | ctx.close();
37 | }
38 |
39 | @Override
40 | public void channelReadComplete(ChannelHandlerContext ctx) {
41 | ctx.flush();
42 | }
43 |
44 | @Override
45 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
46 | // Close the connection when an exception is raised.
47 | cause.printStackTrace();
48 | ctx.close();
49 | }
50 | }
--------------------------------------------------------------------------------
/grpc-demo-proxy/src/main/java/com/grpc/demo/proxy/netty/EchoServer.java:
--------------------------------------------------------------------------------
1 | package com.grpc.demo.proxy.netty;
2 |
3 | import io.netty.bootstrap.ServerBootstrap;
4 | import io.netty.channel.*;
5 | import io.netty.channel.nio.NioEventLoopGroup;
6 | import io.netty.channel.socket.SocketChannel;
7 | import io.netty.channel.socket.nio.NioServerSocketChannel;
8 | import io.netty.handler.logging.LogLevel;
9 | import io.netty.handler.logging.LoggingHandler;
10 |
11 | /**
12 | * Echoes back any received data from a client.
13 | */
14 | public final class EchoServer {
15 |
16 | static final boolean SSL = System.getProperty("ssl") != null;
17 | static final int PORT = Integer.parseInt(System.getProperty("port", "8007"));
18 |
19 | public static void main(String[] args) throws Exception {
20 | // Configure the server.
21 | EventLoopGroup bossGroup = new NioEventLoopGroup(1);
22 | EventLoopGroup workerGroup = new NioEventLoopGroup();
23 | try {
24 | ServerBootstrap b = new ServerBootstrap();
25 | b.group(bossGroup, workerGroup)
26 | .channel(NioServerSocketChannel.class)
27 | .option(ChannelOption.SO_REUSEADDR,true)
28 | //.option(ChannelOption.SO_BACKLOG, 100)
29 | .handler(new LoggingHandler(LogLevel.INFO))
30 | .childHandler(new ChannelInitializer() {
31 | @Override
32 | public void initChannel(SocketChannel ch) throws Exception {
33 | ChannelPipeline p = ch.pipeline();
34 | p.addLast(new EchoServerHandler());
35 | }
36 | });
37 |
38 | // Start the server.
39 | ChannelFuture f = b.bind(PORT).sync();
40 |
41 | // Wait until the server socket is closed.
42 | f.channel().closeFuture().sync();
43 | } finally {
44 | // Shut down all event loops to terminate all threads.
45 | bossGroup.shutdownGracefully();
46 | workerGroup.shutdownGracefully();
47 | }
48 | }
49 | }
--------------------------------------------------------------------------------
/grpc-demo-proxy/src/main/java/com/grpc/demo/proxy/netty/EchoServerHandler.java:
--------------------------------------------------------------------------------
1 | package com.grpc.demo.proxy.netty;
2 |
3 | import io.netty.channel.ChannelHandler.Sharable;
4 | import io.netty.channel.ChannelHandlerContext;
5 | import io.netty.channel.ChannelInboundHandlerAdapter;
6 |
7 | /**
8 | * Handler implementation for the echo server.
9 | */
10 | @Sharable
11 | public class EchoServerHandler extends ChannelInboundHandlerAdapter {
12 |
13 | @Override
14 | public void channelRead(ChannelHandlerContext ctx, Object msg) {
15 | ctx.write(msg);
16 | }
17 |
18 | @Override
19 | public void channelReadComplete(ChannelHandlerContext ctx) {
20 | ctx.flush();
21 | }
22 |
23 | @Override
24 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
25 | // Close the connection when an exception is raised.
26 | cause.printStackTrace();
27 | ctx.close();
28 | }
29 | }
--------------------------------------------------------------------------------
/grpc-demo-proxy/src/main/java/com/grpc/demo/proxy/proxy1/ClientToProxyChannels.java:
--------------------------------------------------------------------------------
1 | package com.grpc.demo.proxy.proxy1;
2 |
3 | import com.google.common.collect.Maps;
4 | import io.netty.channel.Channel;
5 |
6 | import java.util.Map;
7 |
8 | /**
9 | * Created by yeyc on 2016/12/12.
10 | */
11 | public class ClientToProxyChannels {
12 | public static final Map clientToProxyChannelMap = Maps.newConcurrentMap();
13 |
14 | public static final Map clientToProxyStreamIdMap = Maps.newConcurrentMap();
15 | }
16 |
--------------------------------------------------------------------------------
/grpc-demo-proxy/src/main/java/com/grpc/demo/proxy/proxy1/HexDumpProxy.java:
--------------------------------------------------------------------------------
1 | package com.grpc.demo.proxy.proxy1;
2 |
3 | import io.netty.bootstrap.ServerBootstrap;
4 | import io.netty.channel.ChannelOption;
5 | import io.netty.channel.EventLoopGroup;
6 | import io.netty.channel.nio.NioEventLoopGroup;
7 | import io.netty.channel.socket.nio.NioServerSocketChannel;
8 | import org.slf4j.Logger;
9 | import org.slf4j.LoggerFactory;
10 |
11 | /**
12 | * Created by yeyc on 2016/11/21.
13 | */
14 | public class HexDumpProxy {
15 |
16 | private static final int LOCAL_PORT = 8080;
17 |
18 | private static final int nThreads = Runtime.getRuntime().availableProcessors() + 1;
19 |
20 | private static final Logger logger = LoggerFactory.getLogger(HexDumpProxy.class);
21 |
22 | public static void main(String[] args) throws Exception {
23 |
24 | InitChannel.InitChannel();
25 |
26 | // Configure the bootstrap.
27 | EventLoopGroup bossGroup = new NioEventLoopGroup(nThreads);
28 | EventLoopGroup workerGroup = new NioEventLoopGroup(nThreads);
29 | try {
30 | ServerBootstrap b = new ServerBootstrap();
31 | b.group(bossGroup, workerGroup)
32 | .channel(NioServerSocketChannel.class)
33 | .childHandler(new HexDumpProxyInitializer())
34 | .childOption(ChannelOption.AUTO_READ, false)
35 | .bind(LOCAL_PORT).sync().channel().closeFuture().sync();
36 | } finally {
37 | bossGroup.shutdownGracefully();
38 | workerGroup.shutdownGracefully();
39 | }
40 | logger.info("Proxying start *:{}",LOCAL_PORT);
41 |
42 | }
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/grpc-demo-proxy/src/main/java/com/grpc/demo/proxy/proxy1/HexDumpProxyBackendHandler.java:
--------------------------------------------------------------------------------
1 | package com.grpc.demo.proxy.proxy1;
2 |
3 | import io.netty.channel.*;
4 | import io.netty.handler.codec.http2.DefaultHttp2DataFrame;
5 | import io.netty.handler.codec.http2.DefaultHttp2HeadersFrame;
6 | import io.netty.util.ReferenceCountUtil;
7 |
8 | public class HexDumpProxyBackendHandler extends ChannelInboundHandlerAdapter {
9 |
10 |
11 | public HexDumpProxyBackendHandler() {
12 |
13 | }
14 |
15 | @Override
16 | public void channelActive(ChannelHandlerContext ctx) {
17 | System.out.println("HexDumpProxyBackendHandler channelActive ");
18 | ctx.read();
19 | }
20 |
21 | @Override
22 | public void channelRead(final ChannelHandlerContext ctx, Object msg) {
23 | final Channel inboundChannel;
24 | if(msg instanceof DefaultHttp2HeadersFrame){
25 | final DefaultHttp2HeadersFrame headersFrame = (DefaultHttp2HeadersFrame)msg;
26 | final int streamId = ClientToProxyChannels.clientToProxyStreamIdMap.get(headersFrame.streamId());
27 | inboundChannel = ClientToProxyChannels.clientToProxyChannelMap.get(headersFrame.streamId());
28 |
29 | msg = new DefaultHttp2HeadersFrame(headersFrame.headers(),headersFrame.isEndStream(), headersFrame.padding())
30 | .streamId(streamId);
31 |
32 | if(headersFrame.isEndStream()){
33 | ClientToProxyChannels.clientToProxyStreamIdMap.remove(headersFrame.streamId());
34 | ClientToProxyChannels.clientToProxyChannelMap.remove(headersFrame.streamId());
35 | }
36 |
37 | } else if(msg instanceof DefaultHttp2DataFrame){
38 | final DefaultHttp2DataFrame dataFrame = (DefaultHttp2DataFrame)msg;
39 |
40 | final int streamId = ClientToProxyChannels.clientToProxyStreamIdMap.get(dataFrame.streamId());
41 | inboundChannel = ClientToProxyChannels.clientToProxyChannelMap.get(dataFrame.streamId());
42 |
43 | msg = new DefaultHttp2DataFrame(dataFrame.content(), dataFrame.isEndStream(), dataFrame.padding()).streamId
44 | (streamId);
45 |
46 | if(dataFrame.isEndStream()){
47 | ClientToProxyChannels.clientToProxyStreamIdMap.remove(dataFrame.streamId());
48 | ClientToProxyChannels.clientToProxyChannelMap.remove(dataFrame.streamId());
49 | }
50 |
51 | } else {
52 | ReferenceCountUtil.release(msg);
53 | return;
54 | }
55 |
56 |
57 | inboundChannel.writeAndFlush(msg).addListener(new ChannelFutureListener() {
58 | @Override
59 | public void operationComplete(ChannelFuture future) {
60 | if (future.isSuccess()) {
61 | ctx.channel().read();
62 | } else {
63 | future.channel().close();
64 | }
65 | }
66 | });
67 | }
68 |
69 |
70 | @Override
71 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
72 | cause.printStackTrace();
73 | HexDumpProxyFrontendHandler.closeOnFlush(ctx.channel());
74 | }
75 |
76 |
77 |
78 | }
79 |
--------------------------------------------------------------------------------
/grpc-demo-proxy/src/main/java/com/grpc/demo/proxy/proxy1/HexDumpProxyFrontendHandler.java:
--------------------------------------------------------------------------------
1 | package com.grpc.demo.proxy.proxy1;
2 |
3 | import io.netty.buffer.Unpooled;
4 | import io.netty.channel.*;
5 | import io.netty.handler.codec.http2.DefaultHttp2DataFrame;
6 | import io.netty.handler.codec.http2.DefaultHttp2HeadersFrame;
7 | import io.netty.handler.codec.http2.Http2Exception;
8 | import io.netty.util.ReferenceCountUtil;
9 |
10 | import static com.grpc.demo.proxy.proxy1.ClientToProxyChannels.clientToProxyChannelMap;
11 | import static com.grpc.demo.proxy.proxy1.ClientToProxyChannels.clientToProxyStreamIdMap;
12 |
13 |
14 | /**
15 | * Created by yeyc on 2016/11/21.
16 | */
17 | public class HexDumpProxyFrontendHandler extends ChannelInboundHandlerAdapter {
18 |
19 | private ProxyToServerChannel outboundChannel;
20 | private Integer streamId;
21 |
22 | @Override
23 | public void channelActive(ChannelHandlerContext ctx) {
24 | outboundChannel = InitChannel.proxyChannel;
25 | ctx.read();
26 | }
27 |
28 | @Override
29 | public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Http2Exception {
30 | synchronized (HexDumpProxyFrontendHandler.class) {
31 | final Channel inboundChannel = ctx.channel();
32 |
33 | if (msg instanceof DefaultHttp2HeadersFrame) {
34 | streamId = outboundChannel.getCount() * 2 + 1;
35 | DefaultHttp2HeadersFrame headersFrame = (DefaultHttp2HeadersFrame) msg;
36 | msg = new DefaultHttp2HeadersFrame(headersFrame.headers(), headersFrame.isEndStream(), headersFrame.padding())
37 | .streamId(streamId);
38 |
39 | //设置后端channel的值
40 | clientToProxyChannelMap.putIfAbsent(streamId, inboundChannel);
41 | clientToProxyStreamIdMap.putIfAbsent(streamId, headersFrame.streamId());
42 | } else if (msg instanceof DefaultHttp2DataFrame) {
43 | DefaultHttp2DataFrame dataFrame = (DefaultHttp2DataFrame) msg;
44 | msg = new DefaultHttp2DataFrame(dataFrame.content(), dataFrame.isEndStream(), dataFrame.padding()).streamId
45 | (streamId);
46 | } else {
47 | ReferenceCountUtil.release(msg);
48 | return;
49 | }
50 |
51 |
52 | outboundChannel.getChannel().writeAndFlush(msg).addListener(new ChannelFutureListener() {
53 | @Override
54 | public void operationComplete(ChannelFuture future) {
55 | if (future.isSuccess()) {
56 | ctx.channel().read();
57 | } else {
58 | future.channel().close();
59 | }
60 | }
61 | });
62 | }
63 | }
64 |
65 | @Override
66 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
67 | cause.printStackTrace();
68 | closeOnFlush(ctx.channel());
69 | }
70 |
71 | /**
72 | * Closes the specified channel after all queued write requests are flushed.
73 | */
74 | static void closeOnFlush(Channel ch) {
75 | if (ch.isActive()) {
76 | ch.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
77 | }
78 | }
79 |
80 | }
81 |
--------------------------------------------------------------------------------
/grpc-demo-proxy/src/main/java/com/grpc/demo/proxy/proxy1/HexDumpProxyInitializer.java:
--------------------------------------------------------------------------------
1 | package com.grpc.demo.proxy.proxy1;
2 |
3 | import io.netty.channel.ChannelInitializer;
4 | import io.netty.channel.ChannelPipeline;
5 | import io.netty.channel.socket.SocketChannel;
6 | import io.netty.handler.codec.http2.Http2FrameCodec;
7 |
8 | /**
9 | * Created by yeyc on 2016/11/21.
10 | */
11 | public class HexDumpProxyInitializer extends ChannelInitializer{
12 |
13 | @Override
14 | protected void initChannel(SocketChannel ch) throws Exception {
15 | ChannelPipeline pipeline = ch.pipeline();
16 | pipeline.addLast(new Http2FrameCodec(true));
17 | pipeline.addLast(new HexDumpProxyFrontendHandler());
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/grpc-demo-proxy/src/main/java/com/grpc/demo/proxy/proxy1/InitChannel.java:
--------------------------------------------------------------------------------
1 | package com.grpc.demo.proxy.proxy1;
2 |
3 | import io.netty.bootstrap.Bootstrap;
4 | import io.netty.channel.*;
5 | import io.netty.channel.nio.NioEventLoopGroup;
6 | import io.netty.channel.socket.SocketChannel;
7 | import io.netty.channel.socket.nio.NioSocketChannel;
8 | import io.netty.handler.codec.http2.Http2CodecUtil;
9 | import io.netty.handler.codec.http2.Http2FrameCodec;
10 |
11 | import java.util.concurrent.TimeUnit;
12 |
13 | /**
14 | * Created by yeyc on 2016/12/12.
15 | */
16 | public class InitChannel {
17 |
18 | public static ProxyToServerChannel proxyChannel ;
19 |
20 | public static void InitChannel() {
21 | Bootstrap b1 = new Bootstrap();
22 | EventLoopGroup workerGroup = new NioEventLoopGroup();
23 | Channel channel = b1.group(workerGroup)
24 | .channel(NioSocketChannel.class)
25 | .handler(new ChannelInitializer() {
26 | @Override
27 | protected void initChannel(SocketChannel ch) throws Exception {
28 | ChannelPipeline pipeline = ch.pipeline();
29 | pipeline.addLast("proxy-serverHttp2FrameCodec", new Http2FrameCodec(false));
30 | pipeline.addLast("HexDumpProxyBackendHandler", new HexDumpProxyBackendHandler());
31 | }
32 | }).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 100).connect("127.0.0.1",8888).channel();
33 |
34 | ChannelHandlerContext channelHandlerContext = channel.pipeline().lastContext();
35 | channelHandlerContext.writeAndFlush(Http2CodecUtil.connectionPrefaceBuf().retainedDuplicate());
36 |
37 | try {
38 | TimeUnit.SECONDS.sleep(1);
39 | } catch (InterruptedException e) {
40 | e.printStackTrace();
41 | }
42 | System.out.println("初始化服务"+8888);
43 |
44 | proxyChannel = new ProxyToServerChannel(channel);
45 |
46 | }
47 |
48 | }
49 |
--------------------------------------------------------------------------------
/grpc-demo-proxy/src/main/java/com/grpc/demo/proxy/proxy1/ProxyToServerChannel.java:
--------------------------------------------------------------------------------
1 | package com.grpc.demo.proxy.proxy1;
2 |
3 | import io.netty.channel.Channel;
4 |
5 | import java.util.concurrent.atomic.AtomicInteger;
6 |
7 | /**
8 | * Created by yeyc on 2016/12/12.
9 | */
10 | public class ProxyToServerChannel {
11 |
12 | private Channel channel;
13 |
14 | private AtomicInteger count;
15 |
16 | public ProxyToServerChannel(Channel channel){
17 | this.channel =channel;
18 | count = new AtomicInteger(0);
19 | }
20 |
21 | public synchronized int getCount(){
22 | return count.incrementAndGet();
23 | }
24 |
25 | public Channel getChannel() {
26 | return channel;
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/grpc-demo-proxy/src/main/java/com/grpc/demo/proxy/proxy1/Servers.java:
--------------------------------------------------------------------------------
1 | package com.grpc.demo.proxy.proxy1;
2 |
3 | import com.google.common.collect.Lists;
4 | import com.google.common.collect.Maps;
5 |
6 | import java.net.InetSocketAddress;
7 | import java.util.List;
8 | import java.util.Map;
9 |
10 | /**
11 | * Created by yeyc on 2016/12/5.
12 | */
13 | public class Servers {
14 | public static final Map> servers = init();
15 |
16 |
17 | private static Map init(){
18 | Map> result = Maps.newConcurrentMap();
19 | List s1 = Lists.newArrayList();
20 | s1.add(new InetSocketAddress("127.0.0.1",8888));
21 | // s1.add(new InetSocketAddress("127.0.0.1",8889));
22 | result.put("SimpleService",s1);
23 |
24 | List s2 = Lists.newArrayList();
25 | s2.add(new InetSocketAddress("127.0.0.1",9998));
26 | s2.add(new InetSocketAddress("127.0.0.1",9999));
27 | result.put("YycService",s2);
28 | return result;
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/grpc-demo-proxy/src/main/resources/http2-connection.puml:
--------------------------------------------------------------------------------
1 | @startuml
2 | title : http2交互过程
3 |
4 | alt 握手
5 | client -> proxy: outBound(SETTINGS: ack=false, settings={ENABLE_PUSH=0, MAX_CONCURRENT_STREAMS=0, INITIAL_WINDOW_SIZE=1048576})
6 | client --> proxy: outBound(WINDOW_UPDATE: streamId=0, windowSizeIncrement=983041)
7 |
8 | client <-- proxy: inBound (SETTINGS: ack=false, settings={MAX_CONCURRENT_STREAMS=2147483647, INITIAL_WINDOW_SIZE=1048576})
9 | client --> proxy: outBound (SETTINGS: ack=true)
10 |
11 | client <-- proxy: inBound ( WINDOW_UPDATE: streamId=0, windowSizeIncrement=983041)
12 | client <-- proxy: inBound (SETTINGS: ack=true)
13 | end
14 |
15 | client -> proxy: outBound(HEADERS: streamId=3, headers=GrpcHttp2Headers[])
16 | client --> proxy: outBound(DATA: streamId=3, padding=0, endStream=true, length=23, bytes=00000000120a10677270632d73696d706c652d64656d6f)
17 | client <-- proxy: inBound (HEADERS: streamId=3, headers=GrpcHttp2Headers[])
18 | client <-- proxy: inBound (DATA: streamId=3, padding=0, endStream=true, length=23, bytes=00000000120a10677270632d73696d706c652d64656d6f)
19 |
20 | @enduml
--------------------------------------------------------------------------------
/grpc-demo-proxy/src/main/resources/logback.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/grpc-demo-simple/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 4.0.0
6 |
7 | com.yyc.grpc
8 | grpc-demo
9 | 1.0.0
10 |
11 | com.yyc.grpc
12 | grpc-demo-simple
13 |
14 |
15 |
16 | com.yyc.grpc
17 | grpc-contract
18 | 1.0.0
19 |
20 |
21 | io.grpc
22 | grpc-protobuf
23 | ${grpc.version}
24 |
25 |
26 | io.grpc
27 | grpc-stub
28 | ${grpc.version}
29 |
30 |
31 | io.grpc
32 | grpc-netty
33 | ${grpc.version}
34 |
35 |
36 |
37 |
--------------------------------------------------------------------------------
/grpc-demo-simple/src/main/java/com/grpc/demo/simple/SimpleClientStart.java:
--------------------------------------------------------------------------------
1 | package com.grpc.demo.simple;
2 |
3 |
4 | import com.google.protobuf.StringValue;
5 | import com.yyc.grpc.contract.SayHelloResponse;
6 | import com.yyc.grpc.contract.SimpleServiceGrpc;
7 | import io.grpc.ManagedChannel;
8 | import io.grpc.netty.NettyChannelBuilder;
9 |
10 | import java.util.concurrent.TimeUnit;
11 |
12 | public class SimpleClientStart {
13 |
14 | private ManagedChannel managedChannel;
15 | private int PORT = 8888;
16 |
17 | private void createChannel(){
18 | managedChannel = NettyChannelBuilder.forAddress("localhost",PORT).usePlaintext(true).build();
19 | }
20 |
21 | private void shutdown(){
22 | if(managedChannel!=null){
23 | try {
24 | managedChannel.shutdown().awaitTermination(2, TimeUnit.SECONDS);
25 | } catch (InterruptedException e) {
26 | e.printStackTrace();
27 | }
28 | }
29 | }
30 |
31 | public static void main(String[] args) {
32 | SimpleClientStart simpleClientStart = new SimpleClientStart();
33 | simpleClientStart.createChannel();
34 | SimpleServiceGrpc.SimpleServiceBlockingStub simpleServiceStub = SimpleServiceGrpc.newBlockingStub(simpleClientStart.managedChannel);
35 |
36 | SayHelloResponse sayHelloResponse = simpleServiceStub.sayHello(StringValue.newBuilder().setValue("grpc-simple-demo").build());
37 | System.out.println("response:"+sayHelloResponse.getResult());
38 | simpleClientStart.managedChannel.shutdownNow();
39 | //simpleClientStart.shutdown();
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/grpc-demo-simple/src/main/java/com/grpc/demo/simple/SimpleServer.java:
--------------------------------------------------------------------------------
1 | package com.grpc.demo.simple;
2 |
3 | import com.yyc.grpc.contract.SayHelloResponse;
4 | import com.yyc.grpc.contract.SimpleServiceGrpc;
5 |
6 | /**
7 | * Created by yeyc on 2016/9/5.
8 | */
9 | public class SimpleServer extends SimpleServiceGrpc.SimpleServiceImplBase{
10 |
11 | @Override
12 | public void sayHello(com.google.protobuf.StringValue request,
13 | io.grpc.stub.StreamObserver responseObserver) {
14 | SayHelloResponse sayHelloResponse = SayHelloResponse.newBuilder().setResult(request.getValue().concat("hello world")).build();
15 | responseObserver.onNext(sayHelloResponse);
16 | responseObserver.onCompleted();
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/grpc-demo-simple/src/main/java/com/grpc/demo/simple/SimpleServerStart.java:
--------------------------------------------------------------------------------
1 | package com.grpc.demo.simple;
2 |
3 |
4 | import io.grpc.Server;
5 | import io.grpc.netty.NettyServerBuilder;
6 |
7 | import java.util.concurrent.TimeUnit;
8 |
9 | public class SimpleServerStart {
10 |
11 | private int PORT=8888;
12 | private Server server;
13 |
14 | private void start() throws Exception{
15 | server = NettyServerBuilder.forPort(PORT).addService(new SimpleServer().bindService()).build();
16 | server.start();
17 |
18 | Runtime.getRuntime().addShutdownHook(new Thread(){
19 | @Override
20 | public void run(){
21 | System.err.println("*** shutting down gRPC server since JVM is shutting down");
22 | SimpleServerStart.this.stop();
23 | System.err.println("*** server shut down");
24 | }
25 | });
26 | }
27 |
28 | private void stop(){
29 | try {
30 | server.awaitTermination(2, TimeUnit.SECONDS);
31 | } catch (InterruptedException e) {
32 | e.printStackTrace();
33 | }
34 | }
35 |
36 | public static void main(String[] args) throws Exception {
37 | final SimpleServerStart simpleServerStart = new SimpleServerStart();
38 | simpleServerStart.start();
39 | TimeUnit.SECONDS.sleep(3000);
40 | }
41 |
42 | }
43 |
44 |
--------------------------------------------------------------------------------
/grpc-demo-stream/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 4.0.0
6 |
7 | com.yyc.grpc
8 | grpc-demo
9 | 1.0.0
10 |
11 | com.yyc.grpc
12 | grpc-demo-stream
13 |
14 |
15 |
16 | com.yyc.grpc
17 | grpc-contract
18 | 1.0.0
19 |
20 |
21 | io.grpc
22 | grpc-protobuf
23 | ${grpc.version}
24 |
25 |
26 | io.grpc
27 | grpc-stub
28 | ${grpc.version}
29 |
30 |
31 | io.grpc
32 | grpc-netty
33 | ${grpc.version}
34 |
35 |
36 |
37 |
--------------------------------------------------------------------------------
/grpc-demo-stream/src/main/java/com/grpc/demo/stream/SimpleClientStart.java:
--------------------------------------------------------------------------------
1 | package com.grpc.demo.stream;
2 |
3 |
4 | import com.yyc.grpc.contract.SimpleServiceGrpc;
5 | import com.yyc.grpc.contract.WeChatRequest;
6 | import com.yyc.grpc.contract.WeChatResponse;
7 | import io.grpc.ManagedChannel;
8 | import io.grpc.netty.NettyChannelBuilder;
9 | import io.grpc.stub.StreamObserver;
10 |
11 | import java.util.concurrent.TimeUnit;
12 |
13 | public class SimpleClientStart {
14 |
15 | private ManagedChannel managedChannel;
16 | private int PORT = 8888;
17 |
18 | private void createChannel(){
19 | managedChannel = NettyChannelBuilder.forAddress("localhost",PORT).usePlaintext(true).build();
20 | }
21 |
22 | private void shutdown(){
23 | if(managedChannel!=null){
24 | try {
25 | managedChannel.shutdown().awaitTermination(2, TimeUnit.SECONDS);
26 | } catch (InterruptedException e) {
27 | e.printStackTrace();
28 | }
29 | }
30 | }
31 |
32 | public static void main(String[] args) throws InterruptedException {
33 | SimpleClientStart simpleClientStart = new SimpleClientStart();
34 | simpleClientStart.createChannel();
35 | //This stub is not blockingStub
36 | SimpleServiceGrpc.SimpleServiceStub simpleServiceStub = SimpleServiceGrpc.newStub(simpleClientStart.managedChannel);
37 |
38 | StreamObserver requestStreamObserver = simpleServiceStub.weChat(new StreamObserver() {
39 | @Override
40 | public void onNext(WeChatResponse value) {
41 | System.out.println("server send:"+value.getResponse());
42 | }
43 |
44 | @Override
45 | public void onError(Throwable t) {
46 | t.printStackTrace();
47 | }
48 |
49 | @Override
50 | public void onCompleted() {
51 | System.out.println("server onCompleted!!!");
52 | }
53 | });
54 |
55 | WeChatRequest weChatRequest = WeChatRequest.newBuilder().setRequest("client request"+System.currentTimeMillis()).build();
56 | requestStreamObserver.onNext(weChatRequest);
57 |
58 | TimeUnit.SECONDS.sleep(1);
59 | WeChatRequest weChatRequest1 = WeChatRequest.newBuilder().setRequest("client request"+System.currentTimeMillis()).build();
60 | requestStreamObserver.onNext(weChatRequest1);
61 |
62 | TimeUnit.SECONDS.sleep(1);
63 | WeChatRequest weChatRequest2 = WeChatRequest.newBuilder().setRequest("client request"+System.currentTimeMillis()).build();
64 | requestStreamObserver.onNext(weChatRequest2);
65 |
66 | TimeUnit.SECONDS.sleep(1);
67 | WeChatRequest weChatRequest3 = WeChatRequest.newBuilder().setRequest("client request"+System.currentTimeMillis()).build();
68 | requestStreamObserver.onNext(weChatRequest3);
69 |
70 | requestStreamObserver.onCompleted();
71 |
72 |
73 | simpleClientStart.shutdown();
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/grpc-demo-stream/src/main/java/com/grpc/demo/stream/SimpleServer.java:
--------------------------------------------------------------------------------
1 | package com.grpc.demo.stream;
2 |
3 | import com.yyc.grpc.contract.SimpleServiceGrpc;
4 | import com.yyc.grpc.contract.WeChatRequest;
5 | import com.yyc.grpc.contract.WeChatResponse;
6 | import io.grpc.stub.StreamObserver;
7 |
8 | /**
9 | * Created by yeyc on 2016/9/5.
10 | */
11 | public class SimpleServer extends SimpleServiceGrpc.SimpleServiceImplBase{
12 |
13 | @Override
14 | public io.grpc.stub.StreamObserver weChat(
15 | io.grpc.stub.StreamObserver responseObserver) {
16 |
17 | StreamObserver requestStreamObserver = new StreamObserver(){
18 | @Override
19 | public void onNext(WeChatRequest value) {
20 | System.out.println("client value:"+value.getRequest());
21 | responseObserver.onNext(WeChatResponse.newBuilder().setResponse("I m server response client request value="+value.getRequest()).build());
22 | }
23 |
24 | @Override
25 | public void onError(Throwable t) {
26 | t.printStackTrace();
27 | }
28 |
29 | @Override
30 | public void onCompleted() {
31 | System.out.println("client onCompleted!!");
32 | //this client onCompleted then server onCompleted
33 | responseObserver.onCompleted();
34 | }
35 | };
36 |
37 | return requestStreamObserver;
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/grpc-demo-stream/src/main/java/com/grpc/demo/stream/SimpleServerStart.java:
--------------------------------------------------------------------------------
1 | package com.grpc.demo.stream;
2 |
3 |
4 | import io.grpc.Server;
5 | import io.grpc.netty.NettyServerBuilder;
6 |
7 | import java.util.concurrent.TimeUnit;
8 |
9 | public class SimpleServerStart {
10 |
11 | private int PORT=8888;
12 | private Server server;
13 |
14 | private void start() throws Exception{
15 | server = NettyServerBuilder.forPort(PORT).addService(new SimpleServer().bindService()).build();
16 | server.start();
17 |
18 | Runtime.getRuntime().addShutdownHook(new Thread(){
19 | @Override
20 | public void run(){
21 | System.err.println("*** shutting down gRPC server since JVM is shutting down");
22 | SimpleServerStart.this.stop();
23 | System.err.println("*** server shut down");
24 | }
25 | });
26 | }
27 |
28 | private void stop(){
29 | try {
30 | server.awaitTermination(2, TimeUnit.SECONDS);
31 | } catch (InterruptedException e) {
32 | e.printStackTrace();
33 | }
34 | }
35 |
36 | public static void main(String[] args) throws Exception {
37 | final SimpleServerStart simpleServerStart = new SimpleServerStart();
38 | simpleServerStart.start();
39 | TimeUnit.SECONDS.sleep(30);
40 | }
41 |
42 | }
43 |
44 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | com.yyc.grpc
7 | grpc-demo
8 | 1.0.0
9 | pom
10 |
11 |
12 | 4.1.6.Final
13 | 1.0.2
14 |
15 |
16 |
17 |
18 |
19 |
20 | io.grpc
21 | grpc-protobuf
22 | ${grpc.version}
23 |
24 |
25 | io.grpc
26 | grpc-stub
27 | ${grpc.version}
28 |
29 |
30 |
31 |
32 |
33 | grpc-contract
34 | grpc-demo-simple
35 | grpc-demo-encryption
36 | grpc-demo-oneof
37 | grpc-demo-stream
38 | grpc-demo-interceptor
39 | grpc-demo-nameResolver
40 | grpc-demo-proxy
41 |
42 |
43 |
44 |
45 |
46 | org.apache.maven.plugins
47 | maven-compiler-plugin
48 |
49 | 1.8
50 | 1.8
51 |
52 |
53 |
54 |
55 |
56 |
--------------------------------------------------------------------------------