Netty-based HTTP/2 transport implementation for gRPC Java providing high-performance network communication
—
Client transport functionality provides comprehensive channel creation and configuration for connecting to gRPC servers using Netty's HTTP/2 implementation.
import io.grpc.ManagedChannel;
import io.grpc.netty.NettyChannelBuilder;
import io.grpc.netty.NegotiationType;
import io.grpc.ChannelCredentials;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFactory;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.handler.ssl.SslContext;
import java.net.SocketAddress;
import java.util.concurrent.TimeUnit;The primary entry point for creating gRPC channels with Netty transport.
public static NettyChannelBuilder forAddress(String host, int port);
public static NettyChannelBuilder forAddress(SocketAddress serverAddress);
public static NettyChannelBuilder forAddress(String host, int port, ChannelCredentials creds);
public static NettyChannelBuilder forAddress(SocketAddress serverAddress, ChannelCredentials creds);
public static NettyChannelBuilder forTarget(String target);
public static NettyChannelBuilder forTarget(String target, ChannelCredentials creds);Parameters:
host - The server hostname or IP addressport - The server port numberserverAddress - A SocketAddress for the servertarget - A target string (e.g., "dns:///example.com:443")creds - Channel credentials for authenticationpublic NettyChannelBuilder channelType(Class<? extends Channel> channelType);
public NettyChannelBuilder channelType(Class<? extends Channel> channelType,
Class<? extends SocketAddress> transportSocketType);
public NettyChannelBuilder channelFactory(ChannelFactory<? extends Channel> channelFactory);
public NettyChannelBuilder channelFactory(ChannelFactory<? extends Channel> channelFactory,
Class<? extends SocketAddress> transportSocketType);
public <T> NettyChannelBuilder withOption(ChannelOption<T> option, T value);
public NettyChannelBuilder eventLoopGroup(EventLoopGroup eventLoopGroup);Parameters:
channelType - Netty channel class (e.g., NioSocketChannel.class)channelFactory - Custom channel factory for advanced use casesoption - Netty ChannelOption to configurevalue - Value for the channel optioneventLoopGroup - Custom event loop group for the channelpublic NettyChannelBuilder negotiationType(NegotiationType type);
public NettyChannelBuilder sslContext(SslContext sslContext);Parameters:
type - HTTP/2 negotiation type (TLS, PLAINTEXT, PLAINTEXT_UPGRADE)sslContext - Netty SSL context for TLS connectionspublic NettyChannelBuilder initialFlowControlWindow(int initialFlowControlWindow);
public NettyChannelBuilder flowControlWindow(int flowControlWindow);
public NettyChannelBuilder maxInboundMetadataSize(int bytes);
public NettyChannelBuilder maxInboundMetadataSize(int soft, int max);
public NettyChannelBuilder maxInboundMessageSize(int max);Parameters:
initialFlowControlWindow - Initial HTTP/2 flow control window size in bytesflowControlWindow - Flow control window size in bytesbytes - Maximum size for inbound metadata headerssoft - Soft limit for metadata sizemax - Hard limit for metadata sizemax - Maximum size for inbound messages in bytesConstants:
public static final int DEFAULT_FLOW_CONTROL_WINDOW = 1048576; // 1 MiBpublic NettyChannelBuilder keepAliveTime(long keepAliveTime, TimeUnit timeUnit);
public NettyChannelBuilder keepAliveTimeout(long keepAliveTimeout, TimeUnit timeUnit);
public NettyChannelBuilder keepAliveWithoutCalls(boolean enable);Parameters:
keepAliveTime - Time between keep-alive pingskeepAliveTimeout - Timeout for keep-alive ping responsestimeUnit - Time unit for the duration valuesenable - Whether to send keep-alive pings when no calls are activepublic NettyChannelBuilder localSocketPicker(LocalSocketPicker localSocketPicker);Parameters:
localSocketPicker - Custom local socket picker implementationpublic static class LocalSocketPicker {
@Nullable
public SocketAddress createSocketAddress(SocketAddress remoteAddress,
Attributes attrs);
}import io.grpc.ManagedChannel;
import io.grpc.netty.NettyChannelBuilder;
ManagedChannel channel = NettyChannelBuilder.forAddress("localhost", 9090)
.usePlaintext()
.build();import io.grpc.netty.NettyChannelBuilder;
import io.grpc.netty.GrpcSslContexts;
import io.netty.handler.ssl.SslContext;
SslContext sslContext = GrpcSslContexts.forClient()
.trustManager(InsecureTrustManagerFactory.INSTANCE)
.build();
ManagedChannel channel = NettyChannelBuilder.forAddress("api.example.com", 443)
.sslContext(sslContext)
.keepAliveTime(30, TimeUnit.SECONDS)
.keepAliveTimeout(5, TimeUnit.SECONDS)
.keepAliveWithoutCalls(true)
.initialFlowControlWindow(1024 * 1024) // 1MB
.maxInboundMetadataSize(8192)
.build();import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
EventLoopGroup eventLoopGroup = new NioEventLoopGroup(4);
ManagedChannel channel = NettyChannelBuilder.forAddress("server.example.com", 443)
.channelType(NioSocketChannel.class)
.eventLoopGroup(eventLoopGroup)
.withOption(ChannelOption.TCP_NODELAY, true)
.withOption(ChannelOption.SO_KEEPALIVE, true)
.keepAliveTime(30, TimeUnit.SECONDS)
.build();import io.netty.channel.epoll.EpollDomainSocketChannel;
import io.netty.channel.epoll.EpollEventLoopGroup;
import io.netty.channel.unix.DomainSocketAddress;
EventLoopGroup eventLoopGroup = new EpollEventLoopGroup();
ManagedChannel channel = NettyChannelBuilder.forAddress(
new DomainSocketAddress("/tmp/grpc.sock"))
.channelType(EpollDomainSocketChannel.class)
.eventLoopGroup(eventLoopGroup)
.usePlaintext()
.build();Transport-level connection errors are propagated as StatusRuntimeException:
try {
ManagedChannel channel = NettyChannelBuilder.forAddress("unreachable.example.com", 443)
.build();
// Use channel...
} catch (StatusRuntimeException e) {
if (e.getStatus().getCode() == Status.Code.UNAVAILABLE) {
// Handle connection failure
}
}Always properly shut down channels to avoid resource leaks:
ManagedChannel channel = NettyChannelBuilder.forAddress("localhost", 9090)
.usePlaintext()
.build();
try {
// Use channel...
} finally {
channel.shutdown();
try {
if (!channel.awaitTermination(5, TimeUnit.SECONDS)) {
channel.shutdownNow();
}
} catch (InterruptedException e) {
channel.shutdownNow();
Thread.currentThread().interrupt();
}
}Install with Tessl CLI
npx tessl i tessl/maven-io-grpc--grpc-netty