1gRPC Examples 2============================================== 3 4The examples require `grpc-java` to already be built. You are strongly encouraged 5to check out a git release tag, since there will already be a build of gRPC 6available. Otherwise you must follow [COMPILING](../COMPILING.md). 7 8You may want to read through the 9[Quick Start](https://grpc.io/docs/languages/java/quickstart) 10before trying out the examples. 11 12## Basic examples 13 14- [Hello world](src/main/java/io/grpc/examples/helloworld) 15 16- [Route guide](src/main/java/io/grpc/examples/routeguide) 17 18- [Metadata](src/main/java/io/grpc/examples/header) 19 20- [Error handling](src/main/java/io/grpc/examples/errorhandling) 21 22- [Compression](src/main/java/io/grpc/examples/experimental) 23 24- [Flow control](src/main/java/io/grpc/examples/manualflowcontrol) 25 26- [Wait For Ready](src/main/java/io/grpc/examples/waitforready) 27 28- [Json serialization](src/main/java/io/grpc/examples/advanced) 29 30- <details> 31 <summary>Hedging</summary> 32 33 The [hedging example](src/main/java/io/grpc/examples/hedging) demonstrates that enabling hedging 34 can reduce tail latency. (Users should note that enabling hedging may introduce other overhead; 35 and in some scenarios, such as when some server resource gets exhausted for a period of time and 36 almost every RPC during that time has high latency or fails, hedging may make things worse. 37 Setting a throttle in the service config is recommended to protect the server from too many 38 inappropriate retry or hedging requests.) 39 40 The server and the client in the example are basically the same as those in the 41 [hello world](src/main/java/io/grpc/examples/helloworld) example, except that the server mimics a 42 long tail of latency, and the client sends 2000 requests and can turn on and off hedging. 43 44 To mimic the latency, the server randomly delays the RPC handling by 2 seconds at 10% chance, 5 45 seconds at 5% chance, and 10 seconds at 1% chance. 46 47 When running the client enabling the following hedging policy 48 49 ```json 50 "hedgingPolicy": { 51 "maxAttempts": 3, 52 "hedgingDelay": "1s" 53 } 54 ``` 55 Then the latency summary in the client log is like the following 56 57 ```text 58 Total RPCs sent: 2,000. Total RPCs failed: 0 59 [Hedging enabled] 60 ======================== 61 50% latency: 0ms 62 90% latency: 6ms 63 95% latency: 1,003ms 64 99% latency: 2,002ms 65 99.9% latency: 2,011ms 66 Max latency: 5,272ms 67 ======================== 68 ``` 69 70 See [the section below](#to-build-the-examples) for how to build and run the example. The 71 executables for the server and the client are `hedging-hello-world-server` and 72 `hedging-hello-world-client`. 73 74 To disable hedging, set environment variable `DISABLE_HEDGING_IN_HEDGING_EXAMPLE=true` before 75 running the client. That produces a latency summary in the client log like the following 76 77 ```text 78 Total RPCs sent: 2,000. Total RPCs failed: 0 79 [Hedging disabled] 80 ======================== 81 50% latency: 0ms 82 90% latency: 2,002ms 83 95% latency: 5,002ms 84 99% latency: 10,004ms 85 99.9% latency: 10,007ms 86 Max latency: 10,007ms 87 ======================== 88 ``` 89 90</details> 91 92- <details> 93 <summary>Retrying</summary> 94 95 The [retrying example](src/main/java/io/grpc/examples/retrying) provides a HelloWorld gRPC client & 96 server which demos the effect of client retry policy configured on the [ManagedChannel]( 97 ../api/src/main/java/io/grpc/ManagedChannel.java) via [gRPC ServiceConfig]( 98 https://github.com/grpc/grpc/blob/master/doc/service_config.md). Retry policy implementation & 99 configuration details are outlined in the [proposal](https://github.com/grpc/proposal/blob/master/A6-client-retries.md). 100 101 This retrying example is very similar to the [hedging example](src/main/java/io/grpc/examples/hedging) in its setup. 102 The [RetryingHelloWorldServer](src/main/java/io/grpc/examples/retrying/RetryingHelloWorldServer.java) responds with 103 a status UNAVAILABLE error response to a specified percentage of requests to simulate server resource exhaustion and 104 general flakiness. The [RetryingHelloWorldClient](src/main/java/io/grpc/examples/retrying/RetryingHelloWorldClient.java) makes 105 a number of sequential requests to the server, several of which will be retried depending on the configured policy in 106 [retrying_service_config.json](src/main/resources/io/grpc/examples/retrying/retrying_service_config.json). Although 107 the requests are blocking unary calls for simplicity, these could easily be changed to future unary calls in order to 108 test the result of request concurrency with retry policy enabled. 109 110 One can experiment with the [RetryingHelloWorldServer](src/main/java/io/grpc/examples/retrying/RetryingHelloWorldServer.java) 111 failure conditions to simulate server throttling, as well as alter policy values in the [retrying_service_config.json]( 112 src/main/resources/io/grpc/examples/retrying/retrying_service_config.json) to see their effects. To disable retrying 113 entirely, set environment variable `DISABLE_RETRYING_IN_RETRYING_EXAMPLE=true` before running the client. 114 Disabling the retry policy should produce many more failed gRPC calls as seen in the output log. 115 116 See [the section below](#to-build-the-examples) for how to build and run the example. The 117 executables for the server and the client are `retrying-hello-world-server` and 118 `retrying-hello-world-client`. 119 120</details> 121 122- <details> 123 <summary>Health Service</summary> 124 125 The [health service example](src/main/java/io/grpc/examples/healthservice) 126 provides a HelloWorld gRPC server that doesn't like short names along with a 127 health service. It also provides a client application which makes HelloWorld 128 calls and checks the health status. 129 130 The client application also shows how the round robin load balancer can 131 utilize the health status to avoid making calls to a service that is 132 not actively serving. 133</details> 134 135 136- [Keep Alive](src/main/java/io/grpc/examples/keepalive) 137 138### <a name="to-build-the-examples"></a> To build the examples 139 1401. **[Install gRPC Java library SNAPSHOT locally, including code generation plugin](../COMPILING.md) (Only need this step for non-released versions, e.g. master HEAD).** 141 1422. From grpc-java/examples directory: 143``` 144$ ./gradlew installDist 145``` 146 147This creates the scripts `hello-world-server`, `hello-world-client`, 148`route-guide-server`, `route-guide-client`, etc. in the 149`build/install/examples/bin/` directory that run the examples. Each 150example requires the server to be running before starting the client. 151 152For example, to try the hello world example first run: 153 154``` 155$ ./build/install/examples/bin/hello-world-server 156``` 157 158And in a different terminal window run: 159 160``` 161$ ./build/install/examples/bin/hello-world-client 162``` 163 164That's it! 165 166For more information, refer to gRPC Java's [README](../README.md) and 167[tutorial](https://grpc.io/docs/languages/java/basics). 168 169### Maven 170 171If you prefer to use Maven: 1721. **[Install gRPC Java library SNAPSHOT locally, including code generation plugin](../COMPILING.md) (Only need this step for non-released versions, e.g. master HEAD).** 173 1742. Run in this directory: 175``` 176$ mvn verify 177$ # Run the server 178$ mvn exec:java -Dexec.mainClass=io.grpc.examples.helloworld.HelloWorldServer 179$ # In another terminal run the client 180$ mvn exec:java -Dexec.mainClass=io.grpc.examples.helloworld.HelloWorldClient 181``` 182 183### Bazel 184 185If you prefer to use Bazel: 186``` 187$ bazel build :hello-world-server :hello-world-client 188$ # Run the server 189$ bazel-bin/hello-world-server 190$ # In another terminal run the client 191$ bazel-bin/hello-world-client 192``` 193 194## Other examples 195 196- [Android examples](android) 197 198- Secure channel examples 199 200 + [TLS examples](example-tls) 201 202 + [ALTS examples](example-alts) 203 204- [Google Authentication](example-gauth) 205 206- [JWT-based Authentication](example-jwt-auth) 207 208## Unit test examples 209 210Examples for unit testing gRPC clients and servers are located in [examples/src/test](src/test). 211 212In general, we DO NOT allow overriding the client stub and we DO NOT support mocking final methods 213in gRPC-Java library. Users should be cautious that using tools like PowerMock or 214[mockito-inline](https://search.maven.org/search?q=g:org.mockito%20a:mockito-inline) can easily 215break this rule of thumb. We encourage users to leverage `InProcessTransport` as demonstrated in the 216examples to write unit tests. `InProcessTransport` is light-weight and runs the server 217and client in the same process without any socket/TCP connection. 218 219Mocking the client stub provides a false sense of security when writing tests. Mocking stubs and responses 220allows for tests that don't map to reality, causing the tests to pass, but the system-under-test to fail. 221The gRPC client library is complicated, and accurately reproducing that complexity with mocks is very hard. 222You will be better off and write less code by using `InProcessTransport` instead. 223 224Example bugs not caught by mocked stub tests include: 225 226* Calling the stub with a `null` message 227* Not calling `close()` 228* Sending invalid headers 229* Ignoring deadlines 230* Ignoring cancellation 231 232For testing a gRPC client, create the client with a real stub 233using an 234[InProcessChannel](../core/src/main/java/io/grpc/inprocess/InProcessChannelBuilder.java), 235and test it against an 236[InProcessServer](../core/src/main/java/io/grpc/inprocess/InProcessServerBuilder.java) 237with a mock/fake service implementation. 238 239For testing a gRPC server, create the server as an InProcessServer, 240and test it against a real client stub with an InProcessChannel. 241 242The gRPC-java library also provides a JUnit rule, 243[GrpcCleanupRule](../testing/src/main/java/io/grpc/testing/GrpcCleanupRule.java), to do the graceful 244shutdown boilerplate for you. 245 246## Even more examples 247 248A wide variety of third-party examples can be found [here](https://github.com/saturnism/grpc-java-by-example). 249