下面列出了怎么用io.grpc.netty.NettyChannelBuilder的API类实例代码及写法,或者点击链接到github查看源代码。
@Before
public final void setupChannels() throws IOException {
if(gRpcServerProperties.isEnabled()) {
ManagedChannelBuilder<?> channelBuilder = ManagedChannelBuilder.forAddress("localhost", getPort());
Resource certChain = Optional.ofNullable(gRpcServerProperties.getSecurity())
.map(GRpcServerProperties.SecurityProperties::getCertChain)
.orElse(null);
if(null!= certChain){
((NettyChannelBuilder)channelBuilder)
.useTransportSecurity()
.sslContext(GrpcSslContexts.forClient().trustManager(certChain.getInputStream()).build());
}else{
channelBuilder.usePlaintext();
}
channel = onChannelBuild(channelBuilder).build();
}
if(StringUtils.hasText(gRpcServerProperties.getInProcessServerName())){
inProcChannel = onChannelBuild(
InProcessChannelBuilder.forName(gRpcServerProperties.getInProcessServerName())
.usePlaintext()
).build();
}
}
private ManagedChannel newClientChannel() throws CertificateException, IOException {
File clientCertChainFile = TestUtils.loadCert("client.pem");
File clientPrivateKeyFile = TestUtils.loadCert("client.key");
X509Certificate[] clientTrustedCaCerts = {
TestUtils.loadX509Cert("ca.pem")
};
SslContext sslContext =
GrpcSslContexts.forClient()
.keyManager(clientCertChainFile, clientPrivateKeyFile)
.trustManager(clientTrustedCaCerts)
.build();
return NettyChannelBuilder.forAddress("localhost", server.getPort())
.overrideAuthority(TestUtils.TEST_SERVER_HOST)
.negotiationType(NegotiationType.TLS)
.sslContext(sslContext)
.build();
}
@Override
public ManagedChannel build(String channelName, String host, int port) {
final NettyChannelBuilder channelBuilder = NettyChannelBuilder.forAddress(host, port);
channelBuilder.usePlaintext();
channelBuilder.eventLoopGroup(eventLoopGroup);
setupInternal(channelBuilder);
addHeader(channelBuilder);
addClientInterceptor(channelBuilder);
channelBuilder.executor(executorService);
if (this.nameResolverProvider != null) {
logger.info("Set nameResolverProvider {}. channelName={}, host={}, port={}", this.nameResolverProvider, channelName, host, port);
channelBuilder.nameResolverFactory(this.nameResolverProvider);
}
setupClientOption(channelBuilder);
final ManagedChannel channel = channelBuilder.build();
return channel;
}
/**
* Constructor a managed channel build for the given target name and interceptors.
* @param target The target name
* @param interceptors The interceptors
* @return The channel builder
*/
@Bean
@Prototype
protected NettyChannelBuilder managedChannelBuilder(@Parameter String target, List<ClientInterceptor> interceptors) {
GrpcManagedChannelConfiguration config = beanContext.findBean(GrpcManagedChannelConfiguration.class, Qualifiers.byName(target)).orElseGet(() -> {
final GrpcDefaultManagedChannelConfiguration mcc = new GrpcDefaultManagedChannelConfiguration(
target,
beanContext.getEnvironment(),
executorService
);
beanContext.inject(mcc);
return mcc;
}
);
final NettyChannelBuilder channelBuilder = config.getChannelBuilder();
if (CollectionUtils.isNotEmpty(interceptors)) {
channelBuilder.intercept(interceptors);
}
return channelBuilder;
}
private ManagedChannelBuilder createSecureManagedChannelBuilder(String uri,
String trustCertCollectionFilePath,
String clientCertChainFilePath,
String clientPrivateKeyFilePath) throws SSLException {
String cacheTtl = Security.getProperty("networkaddress.cache.ttl");
if (cacheTtl == null) {
cacheTtl = DEFAULT_CACHE_TTL;
}
return NettyChannelBuilder
.forTarget(uri)
.idleTimeout(Integer.valueOf(cacheTtl) * 2, TimeUnit.SECONDS)
.useTransportSecurity()
.sslContext(
buildSslContext(trustCertCollectionFilePath, clientCertChainFilePath, clientPrivateKeyFilePath)
);
}
private void startGossipService() {
String consenterAddress = NodeConfigFactory.getNodeConfig().getNode().getGossip().getConsenterAddress();
String[] split = StringUtils.split(consenterAddress, ":");
String host = split[0];
Integer port = Integer.parseInt(split[1]);
waitConnectable(host, port);
ManagedChannel managedChannel =
NettyChannelBuilder.forAddress(host, port).maxInboundMessageSize(CommConstant.MAX_GRPC_MESSAGE_SIZE)
.usePlaintext().build();
GossipClientStream gossipClientStream = new GossipClientStream(managedChannel);
GossipClientStream.setGossipClientStream(gossipClientStream);
try {
List<String> ledgerIDs = LedgerManager.getLedgerIDs();
for (String ledgerID : ledgerIDs) {
startPullFromConsenter(gossipClientStream, ledgerID);
}
} catch (LedgerException e) {
log.error(e.getMessage(), e);
}
}
public ManagedChannel newPeerClientConnection() {
final NettyChannelBuilder builder =
NettyChannelBuilder.forAddress(host, port).maxInboundMessageSize(CommConstant.MAX_GRPC_MESSAGE_SIZE);
logger.info("Configuring channel connection to peer.");
if (tlsEnabled) {
logger.info("TLS is enabled");
try {
final SslContext sslContext =
GrpcSslContexts.forClient().trustManager(new File(this.rootCertFile)).build();
builder.negotiationType(NegotiationType.TLS);
if (!hostOverrideAuthority.equals("")) {
logger.info("Host override " + hostOverrideAuthority);
builder.overrideAuthority(hostOverrideAuthority);
}
builder.sslContext(sslContext);
logger.info("TLS context built: " + sslContext);
} catch (SSLException e) {
logger.error("failed connect to peer with SSLException", e);
}
} else {
builder.usePlaintext();
}
return builder.build();
}
private ManagedChannel newClientChannel() throws CertificateException, IOException {
File clientCertChainFile = TestUtils.loadCert("client.pem");
File clientPrivateKeyFile = TestUtils.loadCert("client.key");
X509Certificate[] clientTrustedCaCerts = {
TestUtils.loadX509Cert("ca.pem")
};
SslContext sslContext =
GrpcSslContexts.forClient()
.keyManager(clientCertChainFile, clientPrivateKeyFile)
.trustManager(clientTrustedCaCerts)
.build();
return NettyChannelBuilder.forAddress("localhost", server.getPort())
.overrideAuthority(TestUtils.TEST_SERVER_HOST)
.negotiationType(NegotiationType.TLS)
.sslContext(sslContext)
.build();
}
@Before
public void init() {
NettyChannelBuilder nettyChannelBuilder = NettyChannelBuilder.forAddress(host, port).usePlaintext();
ManagedChannel managedChannel = nettyChannelBuilder.build();
SmartContractSupportGrpc.SmartContractSupportStub smartContractSupportStub = SmartContractSupportGrpc.newStub(managedChannel);
receiveObserver = new StreamObserver<SmartContractShim.SmartContractMessage>() {
@Override
public void onNext(SmartContractShim.SmartContractMessage message) {
queue.add(message);
}
@Override
public void onError(Throwable throwable) {
}
@Override
public void onCompleted() {
managedChannel.shutdown();
}
};
sendObserver = smartContractSupportStub.register(receiveObserver);
}
public static AdminGrpc.AdminBlockingStub getAdminStub() {
ManagedChannel channel = null;
if (USE_SSL) {
File certificate =
new File(configurationRepository.getServer().getSecurity().getCertificateChainFile());
try {
channel =
NettyChannelBuilder.forAddress(LOCALHOST, PORT)
.maxInboundMessageSize(100000)
.sslContext(GrpcSslContexts.forClient().trustManager(certificate).build())
.build();
} catch (SSLException e) {
fail("Unable to create SSL channel " + e.getMessage());
}
} else {
channel = ManagedChannelBuilder.forAddress(LOCALHOST, PORT).usePlaintext(true).build();
}
return AdminGrpc.newBlockingStub(channel);
}
public static void main(String[] args) throws Exception {
Flags.parseCurrentPackage(args);
SslContext sslContext =
GrpcSslContexts.forClient().trustManager(new File(certificateFile.get())).build();
ManagedChannel channel =
NettyChannelBuilder.forAddress("localhost", GRPC_PORT).sslContext(sslContext).build();
GrpcAuthTestGrpc.GrpcAuthTestBlockingStub stub =
GrpcAuthTestGrpc.newBlockingStub(channel)
.withInterceptors(new ClientAuthInterceptor(token.get()));
logger.at(Level.INFO).log("Calling server to increment %d", n.get());
Protos.Response resp =
stub.getNextNumber(Protos.Request.newBuilder().setNumber(n.get()).build());
logger.at(Level.INFO).log("Got %d in response", resp.getNumber());
}
private void setupClientOption(final NettyChannelBuilder channelBuilder) {
channelBuilder.keepAliveTime(clientOption.getKeepAliveTime(), TimeUnit.MILLISECONDS);
channelBuilder.keepAliveTimeout(clientOption.getKeepAliveTimeout(), TimeUnit.MILLISECONDS);
channelBuilder.keepAliveWithoutCalls(clientOption.isKeepAliveWithoutCalls());
channelBuilder.maxHeaderListSize(clientOption.getMaxHeaderListSize());
channelBuilder.maxInboundMessageSize(clientOption.getMaxInboundMessageSize());
channelBuilder.flowControlWindow(clientOption.getFlowControlWindow());
channelBuilder.idleTimeout(clientOption.getIdleTimeoutMillis(), TimeUnit.MILLISECONDS);
// ChannelOption
channelBuilder.withOption(ChannelOption.TCP_NODELAY, true);
channelBuilder.withOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, clientOption.getConnectTimeout());
final WriteBufferWaterMark writeBufferWaterMark = new WriteBufferWaterMark(clientOption.getWriteBufferLowWaterMark(), clientOption.getWriteBufferHighWaterMark());
channelBuilder.withOption(ChannelOption.WRITE_BUFFER_WATER_MARK, writeBufferWaterMark);
if (logger.isInfoEnabled()) {
logger.info("Set clientOption {}. name={}", clientOption, factoryName);
}
}
/**
* Constructor a managed channel build for the given target name and interceptors.
* @param target The target name
* @param interceptors The interceptors
* @return The channel builder
*/
@Bean
@Prototype
protected NettyChannelBuilder managedChannelBuilder(@Parameter String target, List<ClientInterceptor> interceptors) {
GrpcManagedChannelConfiguration config = beanContext.findBean(GrpcManagedChannelConfiguration.class, Qualifiers.byName(target)).orElseGet(() -> {
final GrpcDefaultManagedChannelConfiguration mcc = new GrpcDefaultManagedChannelConfiguration(
target,
beanContext.getEnvironment(),
executorService
);
beanContext.inject(mcc);
return mcc;
}
);
final NettyChannelBuilder channelBuilder = config.getChannelBuilder();
if (CollectionUtils.isNotEmpty(interceptors)) {
channelBuilder.intercept(interceptors);
}
return channelBuilder;
}
public KMSEncryptionProvider(final EncryptionConfiguration configuration) {
super();
setChannelInfo();
SslContext sslContext;
try {
sslContext = GrpcSslContexts.forClient()
.trustManager(new ByteArrayInputStream(configuration.getCa().getBytes(UTF_8)))
.build();
} catch (SSLException e) {
throw new RuntimeException(e);
}
blockingStub = KeyManagementServiceGrpc.newBlockingStub(
NettyChannelBuilder.forAddress(new DomainSocketAddress(configuration.getEndpoint()))
.eventLoopGroup(group)
.channelType(channelType)
.keepAliveTime(DEFAULT_KEEPALIVE_TIMEOUT_NANOS, TimeUnit.NANOSECONDS)
.useTransportSecurity()
.sslContext(sslContext)
.overrideAuthority(configuration.getHost())
.build());
}
private static NettyChannelBuilder newNettyChannelBuilder(String targetUrl, String proxy)
throws IOException {
if (Strings.isNullOrEmpty(proxy)) {
return NettyChannelBuilder.forTarget(targetUrl).defaultLoadBalancingPolicy("round_robin");
}
if (!proxy.startsWith("unix:")) {
throw new IOException("Remote proxy unsupported: " + proxy);
}
DomainSocketAddress address = new DomainSocketAddress(proxy.replaceFirst("^unix:", ""));
NettyChannelBuilder builder =
NettyChannelBuilder.forAddress(address).overrideAuthority(targetUrl);
if (KQueue.isAvailable()) {
return builder
.channelType(KQueueDomainSocketChannel.class)
.eventLoopGroup(new KQueueEventLoopGroup());
}
if (Epoll.isAvailable()) {
return builder
.channelType(EpollDomainSocketChannel.class)
.eventLoopGroup(new EpollEventLoopGroup());
}
throw new IOException("Unix domain sockets are unsupported on this platform");
}
public AgentClientMock(final String host, final int port, final boolean agentHeader) {
NettyChannelBuilder builder = NettyChannelBuilder.forAddress(host, port);
if (agentHeader) {
HeaderFactory headerFactory = new AgentHeaderFactory("mockAgentId", "mockApplicationName", System.currentTimeMillis());
final Metadata extraHeaders = headerFactory.newHeader();
final ClientInterceptor headersInterceptor = MetadataUtils.newAttachHeadersInterceptor(extraHeaders);
builder.intercept(headersInterceptor);
}
builder.usePlaintext();
channel = builder.build();
this.agentStub = AgentGrpc.newStub(channel);
this.metadataStub = MetadataGrpc.newBlockingStub(channel);
}
/**
* Construct client connecting to HelloWorld server at {@code host:port}.
*/
public HelloWorldClientTls(String host,
int port,
SslContext sslContext) throws SSLException {
this(NettyChannelBuilder.forAddress(host, port)
.negotiationType(NegotiationType.TLS)
.sslContext(sslContext)
.build());
}
private void runTest() throws Exception {
try {
controlChannel = NettyChannelBuilder.forAddress("127.0.0.1", serverControlPort)
.negotiationType(NegotiationType.PLAINTEXT).build();
controlStub = ReconnectServiceGrpc.newBlockingStub(controlChannel);
if (useOkhttp) {
retryChannel =
OkHttpChannelBuilder.forAddress("127.0.0.1", serverRetryPort)
.useTransportSecurity()
.build();
} else {
retryChannel = NettyChannelBuilder.forAddress("127.0.0.1", serverRetryPort)
.negotiationType(NegotiationType.TLS).build();
}
retryStub = ReconnectServiceGrpc.newBlockingStub(retryChannel);
controlStub.start(Empty.getDefaultInstance());
long startTimeStamp = System.currentTimeMillis();
while ((System.currentTimeMillis() - startTimeStamp) < TEST_TIME_MS) {
try {
retryStub.start(Empty.getDefaultInstance());
} catch (StatusRuntimeException expected) {
// Make CheckStyle happy.
}
Thread.sleep(50);
}
ReconnectInfo info = controlStub.stop(Empty.getDefaultInstance());
assertTrue(info.getPassed());
} finally {
controlChannel.shutdownNow();
retryChannel.shutdownNow();
}
}
private Channel getChannel(final Endpoint remote) {
// TODO: allow configuring SSL/TLS
Channel channel;
LOG.debug("Creating channel from {} to {}", address, remote);
if (settings.getUseInProcessTransport()) {
channel = InProcessChannelBuilder
.forName(remote.toString())
.executor(grpcExecutor)
.usePlaintext(true)
.idleTimeout(10, TimeUnit.SECONDS)
.build();
} else {
channel = NettyChannelBuilder
.forAddress(remote.getHostname().toStringUtf8(), remote.getPort())
.executor(grpcExecutor)
.eventLoopGroup(eventLoopGroup)
.usePlaintext(true)
.idleTimeout(10, TimeUnit.SECONDS)
.withOption(ChannelOption.SO_REUSEADDR, true)
.withOption(ChannelOption.SO_SNDBUF, DEFAULT_BUF_SIZE)
.withOption(ChannelOption.SO_RCVBUF, DEFAULT_BUF_SIZE)
.build();
}
return channel;
}
private NettyChannelBuilder makeChannelBuilder(URI channelUri) {
checkArgument(channelUri.getScheme().equals(GRPC)
|| channelUri.getScheme().equals(GRPCS),
format("Server URI scheme must be %s or %s", GRPC, GRPCS));
checkArgument(!isNullOrEmpty(channelUri.getHost()),
"Server host address should not be empty");
checkArgument(channelUri.getPort() > 0 && channelUri.getPort() <= 65535,
"Invalid server port");
final boolean useTls = channelUri.getScheme().equals(GRPCS);
final NettyChannelBuilder channelBuilder = NettyChannelBuilder
.forAddress(channelUri.getHost(), channelUri.getPort())
.nameResolverFactory(DNS_NAME_RESOLVER_PROVIDER)
.defaultLoadBalancingPolicy(
PICK_FIRST_LOAD_BALANCER_PROVIDER.getPolicyName())
.maxInboundMessageSize(
DEFAULT_MAX_INBOUND_MSG_SIZE * MEGABYTES);
if (useTls) {
try {
// Accept any server certificate; this is insecure and
// should not be used in production.
final SslContext sslContext = GrpcSslContexts.forClient().trustManager(
InsecureTrustManagerFactory.INSTANCE).build();
channelBuilder.sslContext(sslContext).useTransportSecurity();
} catch (SSLException e) {
log.error("Failed to build SSL context", e);
return null;
}
} else {
channelBuilder.usePlaintext();
}
return channelBuilder;
}
/**
* Resets client/server and their flow control windows.
*/
private void resetConnection(int clientFlowControlWindow)
throws InterruptedException {
if (channel != null) {
if (!channel.isShutdown()) {
channel.shutdown();
channel.awaitTermination(100, TimeUnit.MILLISECONDS);
}
}
channel = NettyChannelBuilder.forAddress(new InetSocketAddress("localhost", proxyPort))
.flowControlWindow(clientFlowControlWindow)
.negotiationType(NegotiationType.PLAINTEXT)
.build();
}
@Override
protected ManagedChannel createChannel() {
NettyChannelBuilder builder = NettyChannelBuilder
.forAddress(new LocalAddress("in-process-1"))
.negotiationType(NegotiationType.PLAINTEXT)
.channelType(LocalChannel.class)
.flowControlWindow(65 * 1024)
.maxInboundMessageSize(AbstractInteropTest.MAX_MESSAGE_SIZE);
io.grpc.internal.TestingAccessor.setStatsImplementation(
builder, createClientCensusStatsModule());
return builder.build();
}
@Override
protected ManagedChannel createChannel() {
NettyChannelBuilder builder = NettyChannelBuilder.forAddress(getListenAddress())
.negotiationType(NegotiationType.PLAINTEXT)
.maxInboundMessageSize(AbstractInteropTest.MAX_MESSAGE_SIZE)
.initialFlowControlWindow(NettyChannelBuilder.DEFAULT_FLOW_CONTROL_WINDOW);
// Disable the default census stats interceptor, use testing interceptor instead.
io.grpc.internal.TestingAccessor.setStatsEnabled(builder, false);
return builder.intercept(createCensusStatsClientInterceptor()).build();
}
@Before
public void setup() throws Exception {
ChannelHandler uncaughtExceptionHandler =
new ChannelDuplexHandler() {
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
caughtException = cause;
super.exceptionCaught(ctx, cause);
ctx.close();
}
};
TsiHandshakerFactory handshakerFactory =
new DelegatingTsiHandshakerFactory(FakeTsiHandshaker.clientHandshakerFactory()) {
@Override
public TsiHandshaker newHandshaker(String authority) {
return new DelegatingTsiHandshaker(super.newHandshaker(authority)) {
@Override
public TsiPeer extractPeer() throws GeneralSecurityException {
return mockedTsiPeer;
}
@Override
public Object extractPeerObject() throws GeneralSecurityException {
return mockedAltsContext;
}
};
}
};
ManagedChannel fakeChannel = NettyChannelBuilder.forTarget("localhost:8080").build();
ObjectPool<Channel> fakeChannelPool = new FixedObjectPool<Channel>(fakeChannel);
LazyChannel lazyFakeChannel = new LazyChannel(fakeChannelPool);
ChannelHandler altsServerHandler = new ServerAltsProtocolNegotiator(
handshakerFactory, lazyFakeChannel)
.newHandler(grpcHandler);
// On real server, WBAEH fires default ProtocolNegotiationEvent. KickNH provides this behavior.
ChannelHandler handler = new KickNegotiationHandler(altsServerHandler);
channel = new EmbeddedChannel(uncaughtExceptionHandler, handler);
}
private AltsChannelBuilder(String target) {
delegate =
NettyChannelBuilder.forTarget(target)
.keepAliveTime(20, TimeUnit.SECONDS)
.keepAliveTimeout(10, TimeUnit.SECONDS)
.keepAliveWithoutCalls(true);
InternalNettyChannelBuilder.setProtocolNegotiatorFactory(
delegate(), new ProtocolNegotiatorFactory());
}
private void addHeader(NettyChannelBuilder channelBuilder) {
final Metadata extraHeaders = headerFactory.newHeader();
if (logger.isDebugEnabled()) {
logger.debug("addHeader {}", extraHeaders);
}
final ClientInterceptor headersInterceptor = MetadataUtils.newAttachHeadersInterceptor(extraHeaders);
channelBuilder.intercept(headersInterceptor);
}
public StatClientMock(final String host, final int port) {
NettyChannelBuilder builder = NettyChannelBuilder.forAddress(host, port);
HeaderFactory headerFactory = new AgentHeaderFactory("mockAgentId", "mockApplicationName", System.currentTimeMillis());
final Metadata extraHeaders = headerFactory.newHeader();
final ClientInterceptor headersInterceptor = MetadataUtils.newAttachHeadersInterceptor(extraHeaders);
builder.intercept(headersInterceptor);
builder.usePlaintext();
channel = builder.build();
this.statStub = StatGrpc.newStub(channel);
}
/**
* Construct client connecting to HelloWorld server at {@code host:port}.
*/
public HelloWorldClientTls(String host,
int port,
SslContext sslContext) throws SSLException {
this(NettyChannelBuilder.forAddress(host, port)
.overrideAuthority("foo.test.google.fr") /* Only for using provided test certs. */
.sslContext(sslContext)
.build());
}
public GRPCConfigWatcherRegister(RemoteEndpointSettings settings) {
super(settings.getPeriod());
this.settings = settings;
stub = ConfigurationServiceGrpc.newBlockingStub(
NettyChannelBuilder.forAddress(settings.getHost(), settings.getPort())
.usePlaintext()
.build());
}
@Override
protected NettyChannelBuilder newChannelBuilder(final String name) {
final GrpcChannelProperties properties = getPropertiesFor(name);
URI address = properties.getAddress();
if (address == null) {
address = URI.create(name);
}
return NettyChannelBuilder.forTarget(address.toString())
.defaultLoadBalancingPolicy(properties.getDefaultLoadBalancingPolicy());
}