Convert Figma logo to code with AI

grpc logogrpc-java

The Java gRPC implementation. HTTP/2 based RPC

11,358
3,815
11,358
518

Top Related Projects

20,846

The Go language implementation of gRPC. HTTP/2 based RPC

10,310

Apache Thrift

65,113

Protocol Buffers - Google's data interchange format

42,958

A type-safe HTTP client for Android and the JVM

14,938

Asynchronous HTTP client/server framework for asyncio and Python

Quick Overview

gRPC-Java is the official Java implementation of gRPC, a high-performance, open-source universal RPC framework. It provides efficient, language-agnostic communication between client and server applications, utilizing Protocol Buffers for serialization and HTTP/2 for transport.

Pros

  • High performance and low latency due to HTTP/2 and binary protocol
  • Strong typing and code generation for multiple languages
  • Built-in support for authentication, load balancing, and streaming
  • Excellent for microservices architecture and cross-platform communication

Cons

  • Steeper learning curve compared to REST APIs
  • Requires additional tooling and setup
  • Limited browser support without a proxy
  • Potential compatibility issues with certain firewalls and proxies

Code Examples

  1. Defining a service in Protocol Buffers:
syntax = "proto3";

service Greeter {
  rpc SayHello (HelloRequest) returns (HelloReply) {}
}

message HelloRequest {
  string name = 1;
}

message HelloReply {
  string message = 1;
}
  1. Implementing the server:
public class GreeterImpl extends GreeterGrpc.GreeterImplBase {
  @Override
  public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) {
    HelloReply reply = HelloReply.newBuilder().setMessage("Hello " + req.getName()).build();
    responseObserver.onNext(reply);
    responseObserver.onCompleted();
  }
}
  1. Creating a client and making a call:
ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 50051)
    .usePlaintext()
    .build();
GreeterGrpc.GreeterBlockingStub blockingStub = GreeterGrpc.newBlockingStub(channel);

HelloRequest request = HelloRequest.newBuilder().setName("World").build();
HelloReply response = blockingStub.sayHello(request);
System.out.println("Greeting: " + response.getMessage());

Getting Started

  1. Add gRPC dependencies to your build.gradle:
dependencies {
    implementation 'io.grpc:grpc-netty-shaded:1.53.0'
    implementation 'io.grpc:grpc-protobuf:1.53.0'
    implementation 'io.grpc:grpc-stub:1.53.0'
}
  1. Define your service in a .proto file.
  2. Generate Java code using the protobuf compiler with gRPC plugin.
  3. Implement your service and create a gRPC server.
  4. Create a client and make RPC calls to the server.

For detailed instructions, refer to the official gRPC-Java documentation and examples in the repository.

Competitor Comparisons

20,846

The Go language implementation of gRPC. HTTP/2 based RPC

Pros of grpc-go

  • Lightweight and efficient, with lower memory footprint
  • Better integration with Go's concurrency model (goroutines)
  • Faster compilation times due to Go's simplicity

Cons of grpc-go

  • Less mature ecosystem compared to Java
  • Fewer third-party libraries and tools available
  • Limited support for some advanced gRPC features

Code Comparison

grpc-go:

import "google.golang.org/grpc"

func main() {
    conn, _ := grpc.Dial("localhost:50051", grpc.WithInsecure())
    defer conn.Close()
    client := pb.NewGreeterClient(conn)
}

grpc-java:

import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;

public class Main {
    public static void main(String[] args) {
        ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 50051).usePlaintext().build();
        GreeterGrpc.GreeterBlockingStub client = GreeterGrpc.newBlockingStub(channel);
    }
}

The code comparison shows that grpc-go has a more concise syntax for creating a client connection, while grpc-java requires more verbose code. This reflects Go's emphasis on simplicity and Java's more structured approach.

10,310

Apache Thrift

Pros of Thrift

  • Supports a wider range of programming languages
  • Simpler to set up and use for smaller projects
  • More flexible data serialization options

Cons of Thrift

  • Less active development and community support
  • Limited streaming capabilities compared to gRPC
  • Lacks built-in features like load balancing and authentication

Code Comparison

Thrift IDL:

service Calculator {
  i32 add(1: i32 num1, 2: i32 num2)
}

gRPC-Java proto:

service Calculator {
  rpc Add(AddRequest) returns (AddResponse) {}
}

message AddRequest {
  int32 num1 = 1;
  int32 num2 = 2;
}

message AddResponse {
  int32 result = 1;
}

Key Differences

  • Thrift uses a simpler IDL syntax, while gRPC uses Protocol Buffers
  • gRPC offers built-in streaming support, which Thrift lacks
  • Thrift provides more flexibility in data serialization formats
  • gRPC has better performance and scalability for large-scale systems
  • Thrift has a longer history and wider language support, but gRPC has gained more popularity recently

Both frameworks have their strengths, and the choice between them depends on specific project requirements, language ecosystem, and scalability needs.

65,113

Protocol Buffers - Google's data interchange format

Pros of protobuf

  • Language-agnostic serialization format, supporting multiple programming languages
  • More compact and efficient data representation compared to JSON or XML
  • Provides a schema definition language for clear data structure specification

Cons of protobuf

  • Limited to structured data; less flexible for dynamic or unstructured content
  • Requires compilation step to generate language-specific code
  • Steeper learning curve for developers unfamiliar with the protocol buffer syntax

Code Comparison

protobuf:

syntax = "proto3";

message Person {
  string name = 1;
  int32 age = 2;
}

grpc-java:

public final class PersonOuterClass {
  public static final class Person extends
      com.google.protobuf.GeneratedMessageV3 {
    private String name_;
    private int age_;
    // ... (methods and other generated code)
  }
}

Key Differences

  • protobuf focuses on data serialization, while grpc-java implements gRPC for Java
  • grpc-java uses protobuf for message definition but adds RPC capabilities
  • protobuf is more versatile across languages, while grpc-java is Java-specific
  • grpc-java provides additional features like streaming and bi-directional communication

Use Cases

  • Choose protobuf for efficient cross-language data serialization
  • Opt for grpc-java when building Java-based microservices with RPC requirements
42,958

A type-safe HTTP client for Android and the JVM

Pros of Retrofit

  • Simpler API and easier to use for RESTful services
  • Lightweight and has fewer dependencies
  • Better suited for mobile development, especially Android

Cons of Retrofit

  • Limited to HTTP-based APIs, less flexible for other protocols
  • Lacks built-in support for streaming and bidirectional communication
  • May require additional libraries for advanced features

Code Comparison

Retrofit:

public interface GitHubService {
  @GET("users/{user}/repos")
  Call<List<Repo>> listRepos(@Path("user") String user);
}

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.github.com/")
    .build();

GitHubService service = retrofit.create(GitHubService.class);

gRPC-Java:

public class HelloWorldClient {
  private final GreeterGrpc.GreeterBlockingStub blockingStub;

  public HelloWorldClient(Channel channel) {
    blockingStub = GreeterGrpc.newBlockingStub(channel);
  }

  public void greet(String name) {
    HelloRequest request = HelloRequest.newBuilder().setName(name).build();
    HelloReply response = blockingStub.sayHello(request);
    System.out.println("Greeting: " + response.getMessage());
  }
}

Summary

Retrofit is better suited for simple RESTful APIs and mobile development, while gRPC-Java offers more flexibility and performance for complex, high-throughput systems. The choice between the two depends on the specific requirements of your project, such as the type of API, performance needs, and target platforms.

14,938

Asynchronous HTTP client/server framework for asyncio and Python

Pros of aiohttp

  • Lightweight and flexible HTTP client/server for asyncio
  • Supports both client and server-side WebSockets
  • Easy to use with Python's async/await syntax

Cons of aiohttp

  • Limited to Python ecosystem, while gRPC-Java is cross-language
  • Less built-in support for advanced RPC features like streaming and load balancing

Code Comparison

aiohttp (Python):

async with aiohttp.ClientSession() as session:
    async with session.get('http://example.com') as response:
        html = await response.text()

gRPC-Java:

ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 50051).usePlaintext().build();
GreeterGrpc.GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(channel);
HelloReply response = stub.sayHello(HelloRequest.newBuilder().setName("World").build());

Key Differences

  • aiohttp is primarily for HTTP/WebSocket communication, while gRPC-Java focuses on RPC using Protocol Buffers
  • aiohttp is Python-specific, whereas gRPC-Java is part of a multi-language ecosystem
  • gRPC-Java offers more advanced features for distributed systems and microservices architecture

Use Cases

  • aiohttp: Web scraping, building async web applications, simple API clients
  • gRPC-Java: Microservices communication, high-performance distributed systems, cross-language service integration

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

gRPC-Java - An RPC library and framework

Homepage: grpc.io
Mailing List: grpc-io@googlegroups.com

Join the chat at https://gitter.im/grpc/grpc GitHub Actions Linux Testing Line Coverage Status Branch-adjusted Line Coverage Status

Supported Platforms

gRPC-Java supports Java 8 and later. Android minSdkVersion 21 (Lollipop) and later are supported with Java 8 language desugaring.

TLS usage on Android typically requires Play Services Dynamic Security Provider. Please see the Security Readme.

Older Java versions are not directly supported, but a branch remains available for fixes and releases. See gRFC P5 JDK Version Support Policy.

Java versiongRPC Branch
71.41.x

Getting Started

For a guided tour, take a look at the quick start guide or the more explanatory gRPC basics.

The examples and the Android example are standalone projects that showcase the usage of gRPC.

Download

Download the JARs. Or for Maven with non-Android, add to your pom.xml:

<dependency>
  <groupId>io.grpc</groupId>
  <artifactId>grpc-netty-shaded</artifactId>
  <version>1.66.0</version>
  <scope>runtime</scope>
</dependency>
<dependency>
  <groupId>io.grpc</groupId>
  <artifactId>grpc-protobuf</artifactId>
  <version>1.66.0</version>
</dependency>
<dependency>
  <groupId>io.grpc</groupId>
  <artifactId>grpc-stub</artifactId>
  <version>1.66.0</version>
</dependency>
<dependency> <!-- necessary for Java 9+ -->
  <groupId>org.apache.tomcat</groupId>
  <artifactId>annotations-api</artifactId>
  <version>6.0.53</version>
  <scope>provided</scope>
</dependency>

Or for Gradle with non-Android, add to your dependencies:

runtimeOnly 'io.grpc:grpc-netty-shaded:1.66.0'
implementation 'io.grpc:grpc-protobuf:1.66.0'
implementation 'io.grpc:grpc-stub:1.66.0'
compileOnly 'org.apache.tomcat:annotations-api:6.0.53' // necessary for Java 9+

For Android client, use grpc-okhttp instead of grpc-netty-shaded and grpc-protobuf-lite instead of grpc-protobuf:

implementation 'io.grpc:grpc-okhttp:1.66.0'
implementation 'io.grpc:grpc-protobuf-lite:1.66.0'
implementation 'io.grpc:grpc-stub:1.66.0'
compileOnly 'org.apache.tomcat:annotations-api:6.0.53' // necessary for Java 9+

For Bazel, you can either use Maven (with the GAVs from above), or use @io_grpc_grpc_java//api et al (see below).

Development snapshots are available in Sonatypes's snapshot repository.

Generated Code

For protobuf-based codegen, you can put your proto files in the src/main/proto and src/test/proto directories along with an appropriate plugin.

For protobuf-based codegen integrated with the Maven build system, you can use protobuf-maven-plugin (Eclipse and NetBeans users should also look at os-maven-plugin's IDE documentation):

<build>
  <extensions>
    <extension>
      <groupId>kr.motd.maven</groupId>
      <artifactId>os-maven-plugin</artifactId>
      <version>1.7.1</version>
    </extension>
  </extensions>
  <plugins>
    <plugin>
      <groupId>org.xolstice.maven.plugins</groupId>
      <artifactId>protobuf-maven-plugin</artifactId>
      <version>0.6.1</version>
      <configuration>
        <protocArtifact>com.google.protobuf:protoc:3.25.3:exe:${os.detected.classifier}</protocArtifact>
        <pluginId>grpc-java</pluginId>
        <pluginArtifact>io.grpc:protoc-gen-grpc-java:1.66.0:exe:${os.detected.classifier}</pluginArtifact>
      </configuration>
      <executions>
        <execution>
          <goals>
            <goal>compile</goal>
            <goal>compile-custom</goal>
          </goals>
        </execution>
      </executions>
    </plugin>
  </plugins>
</build>

For non-Android protobuf-based codegen integrated with the Gradle build system, you can use protobuf-gradle-plugin:

plugins {
    id 'com.google.protobuf' version '0.9.4'
}

protobuf {
  protoc {
    artifact = "com.google.protobuf:protoc:3.25.3"
  }
  plugins {
    grpc {
      artifact = 'io.grpc:protoc-gen-grpc-java:1.66.0'
    }
  }
  generateProtoTasks {
    all()*.plugins {
      grpc {}
    }
  }
}

The prebuilt protoc-gen-grpc-java binary uses glibc on Linux. If you are compiling on Alpine Linux, you may want to use the Alpine grpc-java package which uses musl instead.

For Android protobuf-based codegen integrated with the Gradle build system, also use protobuf-gradle-plugin but specify the 'lite' options:

plugins {
    id 'com.google.protobuf' version '0.9.4'
}

protobuf {
  protoc {
    artifact = "com.google.protobuf:protoc:3.25.3"
  }
  plugins {
    grpc {
      artifact = 'io.grpc:protoc-gen-grpc-java:1.66.0'
    }
  }
  generateProtoTasks {
    all().each { task ->
      task.builtins {
        java { option 'lite' }
      }
      task.plugins {
        grpc { option 'lite' }
      }
    }
  }
}

For Bazel, use the proto_library and the java_proto_library (no load() required) and load("@io_grpc_grpc_java//:java_grpc_library.bzl", "java_grpc_library") (from this project), as in this example BUILD.bazel.

API Stability

APIs annotated with @Internal are for internal use by the gRPC library and should not be used by gRPC users. APIs annotated with @ExperimentalApi are subject to change in future releases, and library code that other projects may depend on should not use these APIs.

We recommend using the grpc-java-api-checker (an Error Prone plugin) to check for usages of @ExperimentalApi and @Internal in any library code that depends on gRPC. It may also be used to check for @Internal usage or unintended @ExperimentalApi consumption in non-library code.

How to Build

If you are making changes to gRPC-Java, see the compiling instructions.

High-level Components

At a high level there are three distinct layers to the library: Stub, Channel, and Transport.

Stub

The Stub layer is what is exposed to most developers and provides type-safe bindings to whatever datamodel/IDL/interface you are adapting. gRPC comes with a plugin to the protocol-buffers compiler that generates Stub interfaces out of .proto files, but bindings to other datamodel/IDL are easy and encouraged.

Channel

The Channel layer is an abstraction over Transport handling that is suitable for interception/decoration and exposes more behavior to the application than the Stub layer. It is intended to be easy for application frameworks to use this layer to address cross-cutting concerns such as logging, monitoring, auth, etc.

Transport

The Transport layer does the heavy lifting of putting and taking bytes off the wire. The interfaces to it are abstract just enough to allow plugging in of different implementations. Note the transport layer API is considered internal to gRPC and has weaker API guarantees than the core API under package io.grpc.

gRPC comes with multiple Transport implementations:

  1. The Netty-based HTTP/2 transport is the main transport implementation based on Netty. It is not officially supported on Android. There is a "grpc-netty-shaded" version of this transport. It is generally preferred over using the Netty-based transport directly as it requires less dependency management and is easier to upgrade within many applications.
  2. The OkHttp-based HTTP/2 transport is a lightweight transport based on Okio and forked low-level parts of OkHttp. It is mainly for use on Android.
  3. The in-process transport is for when a server is in the same process as the client. It is used frequently for testing, while also being safe for production use.
  4. The Binder transport is for Android cross-process communication on a single device.