### grpcurl Response Example Source: https://github.com/spring-projects/spring-grpc/blob/main/spring-grpc-docs/src/main/antora/modules/ROOT/pages/getting-started.adoc Shows the expected JSON response from the `Simple.SayHello` gRPC method when a request with name 'Hi' is sent. ```shell { "message": "Hello ==> Hi" } ``` -------------------------------- ### Run Spring Boot Application with Maven Source: https://github.com/spring-projects/spring-grpc/blob/main/README.md Command to run the Spring Boot application using Maven wrapper. This starts the gRPC server. ```shell ./mvnw spring-boot:run ``` -------------------------------- ### Run Spring Boot Application with Gradle Source: https://github.com/spring-projects/spring-grpc/blob/main/README.md Command to run the Spring Boot application using Gradle wrapper. This starts the gRPC server. ```shell ./gradlew bootRun ``` -------------------------------- ### Native Image Output Log Source: https://github.com/spring-projects/spring-grpc/blob/main/samples/grpc-server-netty-shaded/README.md Example log output when running the gRPC server as a native image. It shows the application starting up, detecting Netty, and registering gRPC services. ```log . ____ _ __ _ _ /\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\[__] | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v3.5.5) 2022-12-08T05:36:54.365-08:00 INFO 554359 --- [ main] com.example.demo.DemoApplication : Starting AOT-processed DemoApplication using Java 17.0.5 with PID 554359 (/home/dsyer/dev/scratch/demo/target/demo started by dsyer in /home/dsyer/dev/scratch/demo) 2022-12-08T05:36:54.366-08:00 INFO 554359 --- [ main] com.example.demo.DemoApplication : No active profile set, falling back to 1 default profile: "default" 2022-12-08T05:36:54.377-08:00 INFO 554359 --- [ main] g.s.a.GrpcServerFactoryAutoConfiguration : Detected grpc-netty: Creating NettyGrpcServerFactory 2022-12-08T05:36:54.392-08:00 INFO 554359 --- [ main] n.d.b.g.s.s.AbstractGrpcServerFactory : Registered gRPC service: Simple, bean: grpcServerService, class: com.example.demo.GrpcServerService 2022-12-08T05:36:54.392-08:00 INFO 554359 --- [ main] n.d.b.g.s.s.AbstractGrpcServerFactory : Registered gRPC service: grpc.health.v1.Health, bean: grpcHealthService, class: io.grpc.protobuf.services.HealthServiceImpl 2022-12-08T05:36:54.392-08:00 INFO 554359 --- [ main] n.d.b.g.s.s.AbstractGrpcServerFactory : Registered gRPC service: grpc.reflection.v1alpha.ServerReflection, bean: protoReflectionService, class: io.grpc.protobuf.services.ProtoReflectionService 2022-12-08T05:36:54.396-08:00 INFO 554359 --- [ main] n.d.b.g.s.s.GrpcServerLifecycle : gRPC Server started, listening on address: *, port: 9090 2022-12-08T05:36:54.396-08:00 INFO 554359 --- [ main] com.example.demo.DemoApplication : Started DemoApplication in 0.046 seconds (process running for 0.052) ``` -------------------------------- ### Testing the gRPC Server with gRPCurl Source: https://github.com/spring-projects/spring-grpc/blob/main/samples/grpc-server-kotlin/README.md Test the gRPC server's 'SayHello' method using the gRPCurl tool. This example sends a JSON payload with a 'name' field and expects a greeting message in return. ```bash grpcurl -d '{"name":"Hi"}' -plaintext localhost:9090 Simple.SayHello ``` -------------------------------- ### Test gRPC Service with grpcurl Source: https://github.com/spring-projects/spring-grpc/blob/main/README.md Example of using `grpcurl` to send a request to the `Simple.SayHello` gRPC service endpoint. Assumes the server is running on `localhost:9090`. ```shell grpcurl -d '{"name":"Hi"}' -plaintext localhost:9090 Simple.SayHello ``` -------------------------------- ### Build Lightweight Container Image Source: https://github.com/spring-projects/spring-grpc/blob/main/samples/grpc-server/HELP-maven.md Use this Maven goal to create a lightweight container image for your Spring gRPC application. Ensure Docker is installed and configured. ```bash ./mvnw spring-boot:build-image -Pnative ``` -------------------------------- ### Run Lightweight Container Source: https://github.com/spring-projects/spring-grpc/blob/main/samples/grpc-server-kotlin/HELP-gradle.md Execute the Docker container image that was built using the `bootBuildImage` Gradle task. This command starts your Spring gRPC application. ```bash $ docker run --rm grpc-server:1.1.0-SNAPSHOT ``` -------------------------------- ### Spring Boot Application Entry Point Source: https://github.com/spring-projects/spring-grpc/blob/main/README.md Standard Spring Boot application class to start the gRPC server. Run this application to launch the server on the default port (9090). ```java @SpringBootApplication public class GrpcServerApplication { public static void main(String[] args) { SpringApplication.run(GrpcServerApplication.class, args); } } ``` -------------------------------- ### Running the Spring Boot gRPC Server Source: https://github.com/spring-projects/spring-grpc/blob/main/samples/grpc-server-kotlin/README.md Build and run the Spring Boot gRPC server application using Maven. The server starts by default on port 9090. ```bash ./mvnw spring-boot:run ``` -------------------------------- ### Obtaining OAuth2 Token and Testing gRPC Service Source: https://github.com/spring-projects/spring-grpc/blob/main/samples/grpc-oauth2/README.md This snippet demonstrates how to obtain an OAuth2 access token by interacting with an authentication server and then use that token to call a gRPC service method ('Simple.SayHello') via gRPCurl. It requires 'curl' and 'jq' to be installed. ```bash TOKEN=`curl -v spring:secret@localhost:43737/oauth2/token -d grant_type=client_credentials | jq -r .access_token` grpcurl -H "Authorization: Bearer $TOKEN" -d '{"name":"Hi"}' -plaintext localhost:9090 Simple.SayHello ``` -------------------------------- ### Customize Server Factory with Service Filter Source: https://github.com/spring-projects/spring-grpc/blob/main/spring-grpc-docs/src/main/antora/modules/ROOT/pages/server.adoc Applies a ServerServiceDefinitionFilter to a NettyGrpcServerFactory. Ensures custom service filtering logic is integrated into the server setup. ```java @Bean GrpcServerFactoryCustomizer myServerFactoryCustomizer(ServerServiceDefinitionFilter myServiceFilter) { return factory -> { if (factory instanceof NettyGrpcServerFactory nettyServerFactory) { nettyServerFactory.setServiceFilter(myServiceFilter); } }; } ``` -------------------------------- ### Build Lightweight Container Image with Gradle Source: https://github.com/spring-projects/spring-grpc/blob/main/samples/grpc-server/HELP-gradle.md Use this Gradle task to create a lightweight container image for your Spring gRPC application using Cloud Native Buildpacks. Ensure Docker is installed and configured. ```bash ./gradlew bootBuildImage ``` -------------------------------- ### Apply Server Interceptor Filter to Server Factory Source: https://github.com/spring-projects/spring-grpc/blob/main/spring-grpc-docs/src/main/antora/modules/ROOT/pages/server.adoc Provide a GrpcServerFactoryCustomizer to modify the server factory and set the interceptor filter. This example applies the filter to NettyGrpcServerFactory. ```java @Bean GrpcServerFactoryCustomizer myServerFactoryCustomizer() { return factory -> { if (factory instanceof NettyGrpcServerFactory) { ((DefaultGrpcServerFactory)factory).setInterceptorFilter(myInterceptorFilter()); } }; } ``` -------------------------------- ### Compile Native Executable with Gradle Source: https://github.com/spring-projects/spring-grpc/blob/main/samples/grpc-server/HELP-gradle.md This Gradle task compiles your Spring gRPC application into a native executable using GraalVM Native Build Tools. Ensure GraalVM 22.3+ is installed and configured. ```bash ./gradlew nativeCompile ``` -------------------------------- ### Compile Native Executable with Gradle Source: https://github.com/spring-projects/spring-grpc/blob/main/samples/grpc-server-kotlin/HELP-gradle.md This Gradle task compiles your Spring gRPC application into a native executable using GraalVM Native Image. Ensure GraalVM 22.3+ is installed and configured. ```bash $ ./gradlew nativeCompile ``` -------------------------------- ### Build Lightweight Container Image with Gradle Source: https://github.com/spring-projects/spring-grpc/blob/main/samples/grpc-server-kotlin/HELP-gradle.md Use this Gradle task to build a Docker image for your Spring gRPC application using Cloud Native Buildpacks. Ensure Docker is installed and configured. ```bash $ ./gradlew bootBuildImage ``` -------------------------------- ### Running the Spring Boot gRPC Sample Source: https://github.com/spring-projects/spring-grpc/blob/main/samples/grpc-oauth2/README.md This command executes the Spring Boot gRPC sample application using Maven wrapper. It shows the typical startup logs, including Spring Boot initialization and gRPC server registration. ```bash ./mvnw spring-boot:test-run ``` -------------------------------- ### Run Lightweight Container Source: https://github.com/spring-projects/spring-grpc/blob/main/samples/grpc-server-netty-shaded/HELP.md Execute the generated container image on your local machine, mapping the application's port. ```bash docker run --rm -p 8080:8080 demo:0.0.1-SNAPSHOT ``` -------------------------------- ### Client Interceptor Filtering Source: https://github.com/spring-projects/spring-grpc/blob/main/spring-grpc-docs/src/main/antora/modules/ROOT/pages/client.adoc Register a ClientInterceptorFilter to control which global interceptors are applied to which channel factories. This example prevents ExtraThingsInterceptor from being applied to InProcessGrpcChannelFactory. ```java @Bean ClientInterceptorFilter myInterceptorFilter() { return (interceptor, factory) -> !(interceptor instanceof ExtraThingsInterceptor && factory instanceof InProcessGrpcChannelFactory); } ``` -------------------------------- ### Run Lightweight Container Image Source: https://github.com/spring-projects/spring-grpc/blob/main/samples/grpc-server/HELP-gradle.md Execute this command to run the container image that was built using the `bootBuildImage` Gradle task. The image will be accessible via the specified port. ```bash docker run --rm grpc-server:1.1.0-SNAPSHOT ``` -------------------------------- ### Compile and Run Native Image Source: https://github.com/spring-projects/spring-grpc/blob/main/samples/grpc-server-netty-shaded/README.md Compile the application to a native image using Maven and then run the compiled executable. This is useful for deploying the gRPC server as a self-contained binary. ```bash ./mvnw -Pnative native:compile ./target/demo ``` -------------------------------- ### Build and Format Spring gRPC Project Source: https://github.com/spring-projects/spring-grpc/blob/main/CONTRIBUTING.md Run this command to apply code formatting and generate Javadoc. The `-Pjavadoc` profile is used to enable Javadoc processing, which can speed up development by avoiding a full build. ```shell ./mvnw spring-javaformat:apply javadoc:javadoc -Pjavadoc ``` -------------------------------- ### Build Antora Site Locally Source: https://github.com/spring-projects/spring-grpc/blob/main/spring-grpc-docs/README.md Command to build the Antora documentation site locally. After execution, the output can be viewed at `spring-grpc-docs/target/antora/site/index.html`. ```bash ./mvnw -pl spring-grpc-docs process-resources antora ``` -------------------------------- ### Run Native Executable Source: https://github.com/spring-projects/spring-grpc/blob/main/samples/grpc-server-netty-shaded/HELP.md Execute the compiled native application directly from the target directory. ```bash target/demo ``` -------------------------------- ### Replace Spring gRPC Server Starter - Maven Source: https://github.com/spring-projects/spring-grpc/blob/main/samples/migration.md Replace the old spring-grpc-server-web-spring-boot-starter with the new Spring Boot starters and grpc-servlet-jakarta dependency. ```xml org.springframework.grpc spring-grpc-server-web-spring-boot-starter ``` ```xml org.springframework.boot spring-boot-starter-grpc-server org.springframework.boot spring-boot-starter-web io.grpc grpc-servlet-jakarta ``` -------------------------------- ### Commit Message with DCO and Issue Resolution Source: https://github.com/spring-projects/spring-grpc/blob/main/spring-grpc-docs/src/main/antora/modules/ROOT/pages/contribution-guidelines.adoc Example of a commit message that includes the Signed-off-by line for DCO compliance and a 'resolves' tag to link to a GitHub issue. ```git This is my commit message Signed-off-by: Random J Developer [resolves #1234] ``` -------------------------------- ### Enable HTTP/2 in application.properties Source: https://github.com/spring-projects/spring-grpc/blob/main/samples/migration.md Enable HTTP/2 for the server by setting the property in application.properties. ```properties server.http2.enabled=true ``` -------------------------------- ### Filter Global Server Interceptors Source: https://github.com/spring-projects/spring-grpc/blob/main/spring-grpc-docs/src/main/antora/modules/ROOT/pages/server.adoc Register a ServerInterceptorFilter bean to control which global interceptors are applied to specific server factories. This example prevents ExtraThingsInterceptor from being applied. ```java @Bean ServerInterceptorFilter myInterceptorFilter() { return (interceptor, service) -> !(interceptor instanceof ExtraThingsInterceptor); } ``` -------------------------------- ### Compile and Run Spring gRPC as Native Image Source: https://github.com/spring-projects/spring-grpc/blob/main/samples/grpc-reactive/README.md Compile the Spring gRPC application to a native image using Maven and then execute the compiled binary. This shows the startup logs of the native image. ```bash $ ./mvnw -Pnative native:compile $ ./target/demo . ____ _ __ _ _ /\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\[__] | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v3.0.0) 2022-12-08T05:36:54.365-08:00 INFO 554359 --- [ main] com.example.demo.DemoApplication : Starting AOT-processed DemoApplication using Java 17.0.5 with PID 554359 (/home/dsyer/dev/scratch/demo/target/demo started by dsyer in /home/dsyer/dev/scratch/demo) 2022-12-08T05:36:54.366-08:00 INFO 554359 --- [ main] com.example.demo.DemoApplication : No active profile set, falling back to 1 default profile: "default" 2022-12-08T05:36:54.377-08:00 INFO 554359 --- [ main] g.s.a.GrpcServerFactoryAutoConfiguration : Detected grpc-netty: Creating NettyGrpcServerFactory 2022-12-08T05:36:54.392-08:00 INFO 554359 --- [ main] n.d.b.g.s.s.AbstractGrpcServerFactory : Registered gRPC service: Simple, bean: grpcServerService, class: com.example.demo.GrpcServerService 2022-12-08T05:36:54.392-08:00 INFO 554359 --- [ main] n.d.b.g.s.s.AbstractGrpcServerFactory : Registered gRPC service: grpc.health.v1.Health, bean: grpcHealthService, class: io.grpc.protobuf.services.HealthServiceImpl 2022-12-08T05:36:54.392-08:00 INFO 554359 --- [ main] n.d.b.g.s.s.AbstractGrpcServerFactory : Registered gRPC service: grpc.reflection.v1alpha.ServerReflection, bean: protoReflectionService, class: io.grpc.protobuf.services.ProtoReflectionService 2022-12-08T05:36:54.396-08:00 INFO 554359 --- [ main] n.d.b.g.s.s.GrpcServerLifecycle : gRPC Server started, listening on address: *, port: 9090 2022-12-08T05:36:54.396-08:00 INFO 554359 --- [ main] com.example.demo.DemoApplication : Started DemoApplication in 0.046 seconds (process running for 0.052) ``` -------------------------------- ### Test gRPC Server with grpcurl Source: https://github.com/spring-projects/spring-grpc/blob/main/samples/grpc-server/README.md This command uses grpcurl to send a request to the running gRPC server. It demonstrates how to call the Simple.SayHello method with a JSON payload and shows the expected response. ```bash grpcurl -d '{"name":"Hi"}' -plaintext localhost:9090 Simple.SayHello { "message": "Hello ==\u003e Hi" } ``` -------------------------------- ### Build Native Image Source: https://github.com/spring-projects/spring-grpc/blob/main/samples/grpc-client/README.md Compile the Spring Boot gRPC client application into a native image using GraalVM. ```bash ./mvnw -Pnative native:compile ``` -------------------------------- ### Run Native Executable Source: https://github.com/spring-projects/spring-grpc/blob/main/samples/grpc-server/HELP-maven.md Execute the compiled native binary of your Spring gRPC application. ```bash target/grpc-server-sample ``` -------------------------------- ### Implement gRPC Service Logic Source: https://github.com/spring-projects/spring-grpc/blob/main/README.md Java service implementation extending the generated `SimpleImplBase`. Handles `SayHello` requests, including basic error conditions, and `StreamHello` requests for streaming responses. ```java @Service class GrpcServerService extends SimpleGrpc.SimpleImplBase { private static Log log = LogFactory.getLog(GrpcServerService.class); @Override public void sayHello(HelloRequest req, StreamObserver responseObserver) { log.info("Hello " + req.getName()); if (req.getName().startsWith("error")) { throw new IllegalArgumentException("Bad name: " + req.getName()); } if (req.getName().startsWith("internal")) { throw new RuntimeException(); } HelloReply reply = HelloReply.newBuilder().setMessage("Hello ==> " + req.getName()).build(); responseObserver.onNext(reply); responseObserver.onCompleted(); } @Override public void streamHello(HelloRequest req, StreamObserver responseObserver) { log.info("Hello " + req.getName()); int count = 0; while (count < 10) { HelloReply reply = HelloReply.newBuilder().setMessage("Hello(" + count + ") ==> " + req.getName()).build(); responseObserver.onNext(reply); count++; try { Thread.sleep(1000L); } catch (InterruptedException e) { Thread.currentThread().interrupt(); responseObserver.onError(e); return; } } responseObserver.onCompleted(); } } ``` -------------------------------- ### Run Native Image Source: https://github.com/spring-projects/spring-grpc/blob/main/samples/grpc-client/README.md Execute the compiled native image of the Spring Boot gRPC client application. ```bash ./target/grpc-client-sample ``` -------------------------------- ### Define a gRPC Service in Proto Source: https://github.com/spring-projects/spring-grpc/blob/main/README.md Defines a simple gRPC service with SayHello and StreamHello methods, including request and reply messages. Ensure the `java_package` matches your Spring Initializr selection. ```proto syntax = "proto3"; option java_multiple_files = true; option java_package = ".proto"; option java_outer_classname = "HelloWorldProto"; // The greeting service definition. service Simple { // Sends a greeting rpc SayHello(HelloRequest) returns (HelloReply) {} rpc StreamHello(HelloRequest) returns (stream HelloReply) {} } // The request message containing the user's name. message HelloRequest { string name = 1; } // The response message containing the greetings message HelloReply { string message = 1; } ``` -------------------------------- ### Update Maven Protobuf Plugin Configuration (After) Source: https://github.com/spring-projects/spring-grpc/blob/main/samples/migration.md This is the new, simplified configuration for the protobuf-maven-plugin when using spring-boot-starter-parent. Spring Boot now manages the plugin configuration. ```xml io.github.ascopes protobuf-maven-plugin ``` -------------------------------- ### Build gRPC Stubs with Gradle Source: https://github.com/spring-projects/spring-grpc/blob/main/README.md Command to generate Java gRPC stubs from .proto files using Gradle. The generated code will be located in `build/generated/source/proto/main/grpc` and `build/generated/source/proto/main/java`. ```shell ./gradlew build ``` -------------------------------- ### Run Tests in Native Image with Gradle Source: https://github.com/spring-projects/spring-grpc/blob/main/samples/grpc-server/HELP-gradle.md Use this Gradle task to run your application's test suite within a native image. This is useful for validating compatibility and performance in a native environment. ```bash ./gradlew nativeTest ``` -------------------------------- ### Run Lightweight Container Source: https://github.com/spring-projects/spring-grpc/blob/main/samples/grpc-server/HELP-maven.md Execute the Spring gRPC application container image. The image tag may vary based on your project's version. ```bash docker run --rm grpc-server-sample:1.1.0-SNAPSHOT ``` -------------------------------- ### Build gRPC Stubs with Maven Source: https://github.com/spring-projects/spring-grpc/blob/main/README.md Command to generate Java gRPC stubs from .proto files using Maven. The generated code will be located in `target/generated-sources/protobuf/grpc-java` and `target/generated-sources/protobuf/java`. ```shell ./mvnw clean package ``` -------------------------------- ### Run Spring Boot gRPC Native Image Source: https://github.com/spring-projects/spring-grpc/blob/main/samples/grpc-secure/README.md Execute the compiled native image of your Spring Boot gRPC application. The output shows the application startup logs, confirming the gRPC server is running. ```bash ./target/demo ``` -------------------------------- ### Run Native Executable Source: https://github.com/spring-projects/spring-grpc/blob/main/samples/grpc-server/HELP-gradle.md Execute the native executable generated by the `nativeCompile` Gradle task. This allows you to run your application as a standalone native binary. ```bash build/native/nativeCompile/grpc-server ``` -------------------------------- ### Update Maven Protobuf Plugin Configuration (Before) Source: https://github.com/spring-projects/spring-grpc/blob/main/samples/migration.md This is the old configuration for the protobuf-maven-plugin. It should be removed if using spring-boot-starter-parent. ```xml io.github.ascopes protobuf-maven-plugin 4.0.3 ${protobuf-java.version} io.grpc protoc-gen-grpc-java ${grpc.version} @generated=omit generate ``` -------------------------------- ### Define gRPC Server Service Bean Source: https://github.com/spring-projects/spring-grpc/blob/main/README.md Create a Spring `@Service` that extends the gRPC generated `SimpleImplBase` to implement your gRPC service. ```java @Service public class GrpcServerService extends SimpleGrpc.SimpleImplBase { ... } ``` -------------------------------- ### Native Image Execution Output Source: https://github.com/spring-projects/spring-grpc/blob/main/samples/grpc-tomcat/README.md This is the expected console output when running the compiled native gRPC application. It shows the Spring Boot startup logs and confirms the gRPC server is listening. ```log $ ./mvnw -Pnative native:compile $ ./target/demo . ____ _ __ _ _ /\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\[__] | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v3.5.5) 2022-12-08T05:36:54.365-08:00 INFO 554359 --- [ main] com.example.demo.DemoApplication : Starting AOT-processed DemoApplication using Java 17.0.5 with PID 554359 (/home/dsyer/dev/scratch/demo/target/demo started by dsyer in /home/dsyer/dev/scratch/demo) 2022-12-08T05:36:54.366-08:00 INFO 554359 --- [ main] com.example.demo.DemoApplication : No active profile set, falling back to 1 default profile: "default" 2022-12-08T05:36:54.377-08:00 INFO 554359 --- [ main] g.s.a.GrpcServerFactoryAutoConfiguration : Detected grpc-netty: Creating NettyGrpcServerFactory 2022-12-08T05:36:54.392-08:00 INFO 554359 --- [ main] n.d.b.g.s.s.AbstractGrpcServerFactory : Registered gRPC service: Simple, bean: grpcServerService, class: com.example.demo.GrpcServerService 2022-12-08T05:36:54.392-08:00 INFO 554359 --- [ main] n.d.b.g.s.s.AbstractGrpcServerFactory : Registered gRPC service: grpc.health.v1.Health, bean: grpcHealthService, class: io.grpc.protobuf.services.HealthServiceImpl 2022-12-08T05:36:54.392-08:00 INFO 554359 --- [ main] n.d.b.g.s.s.AbstractGrpcServerFactory : Registered gRPC service: grpc.reflection.v1alpha.ServerReflection, bean: protoReflectionService, class: io.grpc.protobuf.services.ProtoReflectionService 2022-12-08T05:36:54.396-08:00 INFO 554359 --- [ main] n.d.b.g.s.s.GrpcServerLifecycle : gRPC Server started, listening on address: *, port: 9090 2022-12-08T05:36:54.396-08:00 INFO 554359 --- [ main] com.example.demo.DemoApplication : Started DemoApplication in 0.046 seconds (process running for 0.052) ``` -------------------------------- ### Testing with gRPCurl - User Header Authentication Source: https://github.com/spring-projects/spring-grpc/blob/main/samples/grpc-secure/README.md This command uses gRPCurl to test the gRPC service with a custom user header for authentication. It sends a 'SayHello' request to the 'Simple' service on localhost:9090. ```bash grpcurl -H "X-User: user" -d '{"name":"Hi"}' -plaintext localhost:9090 Simple.SayHello ``` -------------------------------- ### Add Gradle Repositories for Milestones and Snapshots Source: https://github.com/spring-projects/spring-grpc/blob/main/README.md Configure your Gradle build file with these repository definitions to use Spring Milestones and Snapshots. ```groovy repositories { mavenCentral() maven { url 'https://repo.spring.io/milestone' } maven { url 'https://repo.spring.io/snapshot' } } ``` -------------------------------- ### Testing with gRPCurl - HTTP Basic Authentication Source: https://github.com/spring-projects/spring-grpc/blob/main/samples/grpc-secure/README.md This command uses gRPCurl to test the gRPC service with HTTP Basic authentication. It encodes 'user:user' credentials in Base64 for the 'Authorization' header. ```bash grpcurl -H "Authorization: Basic $(echo -n user:user | base64)" -d '{"name":"Hi"}' -plaintext localhost:9090 Simple.SayHello ``` -------------------------------- ### Run Tests in Native Image Source: https://github.com/spring-projects/spring-grpc/blob/main/samples/grpc-server/HELP-maven.md Execute your application's test suite within a GraalVM native image to validate compatibility. This is an efficient way to test native image behavior. ```bash ./mvnw test -PnativeTest ``` -------------------------------- ### Run Native Executable Source: https://github.com/spring-projects/spring-grpc/blob/main/samples/grpc-server-kotlin/HELP-gradle.md Execute the native binary generated by the `nativeCompile` Gradle task. This command runs your Spring gRPC application as a native executable. ```bash $ build/native/nativeCompile/grpc-server ``` -------------------------------- ### Run Native Executable and gRPC Server Output Source: https://github.com/spring-projects/spring-grpc/blob/main/samples/grpc-webflux/README.md This is the output observed when running the compiled native executable of a Spring Boot application with gRPC. It shows the application startup logs, including gRPC service registration and the server listening on port 9090. ```text $ ./target/demo . ____ _ __ _ _ /\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\[__] | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v3.5.5) 2022-12-08T05:36:54.365-08:00 INFO 554359 --- [ main] com.example.demo.DemoApplication : Starting AOT-processed DemoApplication using Java 17.0.5 with PID 554359 (/home/dsyer/dev/scratch/demo/target/demo started by dsyer in /home/dsyer/dev/scratch/demo) 2022-12-08T05:36:54.366-08:00 INFO 554359 --- [ main] com.example.demo.DemoApplication : No active profile set, falling back to 1 default profile: "default" 2022-12-08T05:36:54.377-08:00 INFO 554359 --- [ main] g.s.a.GrpcServerFactoryAutoConfiguration : Detected grpc-netty: Creating NettyGrpcServerFactory 2022-12-08T05:36:54.392-08:00 INFO 554359 --- [ main] n.d.b.g.s.s.AbstractGrpcServerFactory : Registered gRPC service: Simple, bean: grpcServerService, class: com.example.demo.GrpcServerService 2022-12-08T05:36:54.392-08:00 INFO 554359 --- [ main] n.d.b.g.s.s.AbstractGrpcServerFactory : Registered gRPC service: grpc.health.v1.Health, bean: grpcHealthService, class: io.grpc.protobuf.services.HealthServiceImpl 2022-12-08T05:36:54.392-08:00 INFO 554359 --- [ main] n.d.b.g.s.s.AbstractGrpcServerFactory : Registered gRPC service: grpc.reflection.v1alpha.ServerReflection, bean: protoReflectionService, class: io.grpc.protobuf.services.ProtoReflectionService 2022-12-08T05:36:54.396-08:00 INFO 554359 --- [ main] n.d.b.g.s.s.GrpcServerLifecycle : gRPC Server started, listening on address: *, port: 9090 2022-12-08T05:36:54.396-08:00 INFO 554359 --- [ main] com.example.demo.DemoApplication : Started DemoApplication in 0.046 seconds (process running for 0.052) ``` -------------------------------- ### Create gRPC Client Blocking Stub with GrpcChannelFactory Source: https://github.com/spring-projects/spring-grpc/blob/main/README.md Inject `GrpcChannelFactory` to create a gRPC channel and then a blocking stub for the `SimpleGrpc` service connecting to a local server. ```java @Bean SimpleGrpc.SimpleBlockingStub stub(GrpcChannelFactory channels) { return SimpleGrpc.newBlockingStub(channels.createChannel("0.0.0.0:9090")); } ``` -------------------------------- ### Run Tests in Native Image with Gradle Source: https://github.com/spring-projects/spring-grpc/blob/main/samples/grpc-server-kotlin/HELP-gradle.md Use this Gradle task to run your application's test suite within a GraalVM native image. This is useful for validating compatibility. ```bash $ ./gradlew nativeTest ``` -------------------------------- ### Compile Native Executable Source: https://github.com/spring-projects/spring-grpc/blob/main/samples/grpc-server/HELP-maven.md Generate a native executable for your Spring gRPC application using GraalVM Native Tools. Requires GraalVM 22.3+. ```bash ./mvnw native:compile -Pnative ``` -------------------------------- ### Define gRPC Server Service Source: https://github.com/spring-projects/spring-grpc/blob/main/spring-grpc-docs/src/main/antora/modules/ROOT/pages/getting-started.adoc Implement a gRPC service by extending the generated SimpleImplBase and annotating it with @Service. ```java @Service public class GrpcServerService extends SimpleGrpc.SimpleImplBase { ...} ``` -------------------------------- ### Add Spring Milestones Repository (Maven) Source: https://github.com/spring-projects/spring-grpc/blob/main/spring-grpc-docs/src/main/antora/modules/ROOT/pages/getting-started.adoc Configures the Maven `pom.xml` to include the Spring Milestones repository, necessary for using milestone versions of Spring gRPC. ```xml spring-milestones Spring Milestones https://repo.spring.io/milestone false ``` -------------------------------- ### Add Maven Repositories for Milestones and Snapshots Source: https://github.com/spring-projects/spring-grpc/blob/main/README.md Include these repository definitions in your Maven build file to access Spring Milestones and Snapshots. ```xml spring-milestones Spring Milestones https://repo.spring.io/milestone false spring-snapshots Spring Snapshots https://repo.spring.io/snapshot false ``` -------------------------------- ### Manually Create a gRPC Client Bean Source: https://github.com/spring-projects/spring-grpc/blob/main/spring-grpc-docs/src/main/antora/modules/ROOT/pages/client.adoc Manually define a gRPC client bean, typically a blocking stub, by injecting a GrpcChannelFactory into the bean's constructor or method. ```java @Bean SimpleGrpc.SimpleBlockingStub stub(GrpcChannelFactory channels) { ``` -------------------------------- ### Per-Channel Customizer Source: https://github.com/spring-projects/spring-grpc/blob/main/spring-grpc-docs/src/main/antora/modules/ROOT/pages/client.adoc Customize an individual channel by specifying a GrpcChannelBuilderCustomizer on ChannelBuilderOptions during channel creation. This customizer is applied after global customizers. ```java @Bean SimpleGrpc.SimpleBlockingStub stub(GrpcChannelFactory channelFactory) { ChannelBuilderOptions options = ChannelBuilderOptions.defaults() .withCustomizer((__, b) -> b.disableRetry()); ManagedChannel channel = channelFactory.createChannel("localhost", options); return SimpleGrpc.newBlockingStub(channel); } ``` -------------------------------- ### Add Spring gRPC Maven Repository Source: https://github.com/spring-projects/spring-grpc/blob/main/spring-grpc-docs/src/main/antora/modules/ROOT/pages/getting-started.adoc Configure your Maven project to use the Spring Snapshots repository for Spring gRPC dependencies. ```xml spring-snapshots Spring Snapshots https://repo.spring.io/snapshot false ``` -------------------------------- ### Configure HTTP Basic Authentication for Servlet gRPC Server Source: https://github.com/spring-projects/spring-grpc/blob/main/spring-grpc-docs/src/main/antora/modules/ROOT/pages/server.adoc This bean configures basic HTTP authentication for a servlet-based gRPC server. It enables HTTP Basic authentication, requires all requests to be authenticated, and disables CSRF protection, which is incompatible with the gRPC protocol. ```java @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { return http.httpBasic(Customizer.withDefaults()) .authorizeHttpRequests((requests) -> requests.anyRequest().authenticated()) .csrf((csrf) -> csrf.disable()) .build(); } ``` -------------------------------- ### Enable Automatic gRPC Client Configuration Source: https://github.com/spring-projects/spring-grpc/blob/main/spring-grpc-docs/src/main/antora/modules/ROOT/pages/client.adoc Use the ImportGrpcClients annotation on your @SpringBootApplication class to enable automatic scanning and creation of gRPC stub beans. This is the default behavior in Spring Boot applications. ```java // This is the default behaviour, so not necessary to add this annotation unless you change its attributes @ImportGrpcClients(basePackageClasses = MyApplication.class) @SpringBootApplication class MyApplication { // ... } ``` -------------------------------- ### Configuring SSL/TLS Client Channels Source: https://github.com/spring-projects/spring-grpc/wiki/Spring-gRPC-Migration-from-Ecosystem-Projects Update SSL/TLS client channel properties from net.devh's grpc.client.* to Spring gRPC's spring.grpc.client.channel.*. This includes enabling SSL and optionally bypassing certificate validation or using an SSL bundle. ```properties negotiation-type=TLS secure=false ``` ```properties ssl.enabled=true bypass-certificate-validation=true ``` ```properties ssl.bundle= ``` -------------------------------- ### ImportGrpcClients Annotation for Stub Registration Source: https://github.com/spring-projects/spring-grpc/blob/main/samples/migration.md Use @ImportGrpcClients to register gRPC client stubs as beans. This is required for any class injecting stubs. ```java @SpringBootTest @ImportGrpcClients // required to register stubs as beans class MyGrpcTests { ... } ``` ```java @TestConfiguration @ImportGrpcClients(basePackageClasses = GrpcServerApplication.class) static class ExtraConfiguration { } ``` -------------------------------- ### Create gRPC Client Blocking Stub with Named Channel Source: https://github.com/spring-projects/spring-grpc/blob/main/README.md Inject `GrpcChannelFactory` to create a gRPC channel using a named configuration ('local') for the `SimpleGrpc` service. ```java @Bean SimpleGrpc.SimpleBlockingStub stub(GrpcChannelFactory channels) { return SimpleGrpc.newBlockingStub(channels.createChannel("local")); } ``` -------------------------------- ### Configure Named gRPC Client Channel in Properties Source: https://github.com/spring-projects/spring-grpc/blob/main/README.md Define the address for the named gRPC client channel ('local') in your application properties file. ```properties spring.grpc.client.channels.local.address=0.0.0.0:9090 ``` -------------------------------- ### Update Gradle Protobuf Plugin Configuration (Kotlin) Source: https://github.com/spring-projects/spring-grpc/blob/main/samples/migration.md For Kotlin projects, keep plugin declarations but remove the protoc artifact from the Gradle configuration. ```groovy protobuf { plugins { grpc { artifact = "io.grpc:protoc-gen-grpc-java:${dependencyManagement.importedProperties['grpc.version']}" } grpckt { artifact = "io.grpc:protoc-gen-grpc-kotlin:${dependencyManagement.importedProperties['grpc-kotlin.version']}:jdk8@jar" } } generateProtoTasks { ... } ``` -------------------------------- ### Create gRPC Channel with Interceptors Source: https://github.com/spring-projects/spring-grpc/blob/main/spring-grpc-docs/src/main/antora/modules/ROOT/pages/client.adoc Creates a gRPC channel with specified interceptors using ChannelBuilderOptions. Useful for applying per-channel security or custom logic. ```java @Bean @Lazy Channel basic(GrpcChannelFactory channels) { return channels.createChannel("my-channel", ChannelBuilderOptions.defaults() .withInterceptors(List.of(new BasicAuthenticationInterceptor("user", "password")))); } ``` -------------------------------- ### Configuring In-Process gRPC Transport in Tests Source: https://github.com/spring-projects/spring-grpc/wiki/Spring-gRPC-Migration-from-Ecosystem-Projects Annotate test classes with @AutoConfigureTestGrpcTransport for in-process servers. Autowire stubs directly and use @ImportGrpcClients to register them as Spring beans. ```java @AutoConfigureTestGrpcTransport ``` ```java @TestConfiguration @ImportGrpcClients(basePackageClasses = MyServiceGrpc.class) public class GrpcTestConfig { @Bean GrpcChannelFactory customGrpcChannelFactory(GrpcChannelBuilderCustomizer... customizers) { return new DefaultGrpcChannelFactory(customizers); } @Bean MyServiceGrpc.MyServiceBlockingStub myServiceStub(GrpcChannelFactory channelFactory) { return MyServiceGrpc.newBlockingStub(channelFactory.createChannel("inProcess")); } } ```