Lab 09: gRPC Java

Time: 60 minutes | Level: Architect | Docker: docker run -it --rm zchencow/innozverse-java:latest bash


Overview

Build production gRPC services in Java: define services, create in-process servers for testing, use blocking and async stubs, implement server-streaming, add interceptors, and propagate deadlines. All examples verified with the gRPC in-process transport.


Step 1: gRPC Architecture

gRPC Communication Models:
  Unary         — request/response (like REST)
  Server-stream — 1 request, N responses
  Client-stream — N requests, 1 response
  Bidirectional — N requests, N responses

Stack:
  Java Application

  gRPC Stub (blocking / async / future)

  Protocol Buffers serialization

  HTTP/2 framing

  TLS (optional)

  Network

Key classes:
  ServerBuilder          — configure and start gRPC server
  ManagedChannel         — client connection pool
  ServerInterceptor      — server-side middleware
  ClientInterceptor      — client-side middleware
  Metadata               — HTTP/2 headers
  Status / StatusCode    — gRPC error codes
  StreamObserver         — async response handler

Step 2: Service Definition (Manual, No Protoc)

In production you'd use .proto files and the protoc-gen-grpc-java plugin. Here we define services manually using MethodDescriptor:


Step 3: In-Process Server and Unary Call


Step 4: Server Streaming


Step 5: Interceptors


Step 6: Deadline Propagation

💡 Deadlines propagate across services automatically via gRPC context. Always set deadlines at the edge and let gRPC propagate them.


Step 7: Error Handling with Status


Step 8: Capstone — gRPC In-Process Server + Client

📸 Verified Output:


Summary

Concept
API/Class
Purpose

Service definition

ServerServiceDefinition

Bind methods to handlers

Unary handler

ServerCalls.asyncUnaryCall()

Single request/response

Server streaming

asyncServerStreamingCall()

Multiple responses

Client channel

ManagedChannel

Connection pool to server

Call options

CallOptions.withDeadlineAfter()

Timeout, credentials

Server interceptor

ServerInterceptor

Logging, auth, metrics

Status codes

Status.Code.*

gRPC error classification

In-process transport

InProcessServerBuilder

Test without network

Last updated