下面列出了io.grpc.ManagedChannelBuilder#build ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static ManagedChannel build(
String host,
int port,
@Nullable String serverHostOverride,
boolean useTls,
@Nullable InputStream testCa) {
ManagedChannelBuilder<?> channelBuilder = ManagedChannelBuilder.forAddress(host, port)
.maxInboundMessageSize(16 * 1024 * 1024);
if (serverHostOverride != null) {
// Force the hostname to match the cert the server uses.
channelBuilder.overrideAuthority(serverHostOverride);
}
if (useTls) {
try {
((OkHttpChannelBuilder) channelBuilder).useTransportSecurity();
((OkHttpChannelBuilder) channelBuilder).sslSocketFactory(getSslSocketFactory(testCa));
} catch (Exception e) {
throw new RuntimeException(e);
}
} else {
channelBuilder.usePlaintext();
}
return channelBuilder.build();
}
@Override
protected ManagedChannel createChannel() {
assertEquals(
"jdk7 required",
"1.7",
System.getProperty("java.specification.version"));
assertEquals(
"Can not run in dev servers because they lack org.conscrypt.OpenSSLProvider support",
"Production",
System.getProperty("com.google.appengine.runtime.environment"));
ManagedChannelBuilder<?> builder =
ManagedChannelBuilder.forTarget(INTEROP_TEST_ADDRESS)
.maxInboundMessageSize(AbstractInteropTest.MAX_MESSAGE_SIZE);
assertTrue(builder instanceof OkHttpChannelBuilder);
return builder.build();
}
private GRPCChannel(String host, int port, List<ChannelBuilder> channelBuilders,
List<ChannelDecorator> decorators) throws Exception {
ManagedChannelBuilder channelBuilder = NettyChannelBuilder.forAddress(host, port);
for (ChannelBuilder builder : channelBuilders) {
channelBuilder = builder.build(channelBuilder);
}
this.originChannel = channelBuilder.build();
Channel channel = originChannel;
for (ChannelDecorator decorator : decorators) {
channel = decorator.build(channel);
}
channelWithDecorators = channel;
}
/**
* Constructs a new instance of the exporter based on the builder's values.
*
* @return a new exporter's instance
*/
public OtlpGrpcSpanExporter build() {
if (endpoint != null) {
final ManagedChannelBuilder<?> managedChannelBuilder =
ManagedChannelBuilder.forTarget(endpoint);
if (useTls) {
managedChannelBuilder.useTransportSecurity();
} else {
managedChannelBuilder.usePlaintext();
}
if (metadata != null) {
managedChannelBuilder.intercept(MetadataUtils.newAttachHeadersInterceptor(metadata));
}
channel = managedChannelBuilder.build();
}
return new OtlpGrpcSpanExporter(channel, deadlineMs);
}
public void open(boolean compressedConnection) throws IOException {
ManagedChannelBuilder<?> managedChannelBuilder = ManagedChannelBuilder.forAddress(member.getServerAddress(), member.getExternalPort())
.maxInboundMessageSize(256 * 1024 * 1024).usePlaintext(true);
channel = managedChannelBuilder.build();
blockingStub = ExternalServiceGrpc.newBlockingStub(channel);
if (compressedConnection) {
blockingStub = blockingStub.withCompression("gzip");
}
asyncStub = ExternalServiceGrpc.newStub(channel);
if (compressedConnection) {
asyncStub = asyncStub.withCompression("gzip");
}
System.err.println("INFO: Connecting to <" + member.getServerAddress() + ">");
}
/**
* Constructs a managed server channel.
* @param server The server
* @param executorService The executor service
* @param clientInterceptors The client interceptors
* @return The channel
*/
@Singleton
@Named(NAME)
@Requires(beans = GrpcEmbeddedServer.class)
@Bean(preDestroy = "shutdown")
protected ManagedChannel serverChannel(
GrpcEmbeddedServer server,
@javax.inject.Named(TaskExecutors.IO) ExecutorService executorService,
List<ClientInterceptor> clientInterceptors) {
final ManagedChannelBuilder<?> builder = ManagedChannelBuilder.forAddress(
server.getHost(),
server.getPort()
).executor(executorService);
if (!server.getServerConfiguration().isSecure()) {
builder.usePlaintext();
}
if (CollectionUtils.isNotEmpty(clientInterceptors)) {
builder.intercept(clientInterceptors);
}
return builder.build();
}
private void connect() {
ManagedChannelBuilder<?> channelBuilder;
if (useInsecure) {
channelBuilder = ManagedChannelBuilder.forTarget(endPoint).usePlaintext();
} else {
channelBuilder =
NettyChannelBuilder.forTarget(endPoint)
.negotiationType(NegotiationType.TLS)
.sslContext(sslContext);
}
ManagedChannel channel = channelBuilder.build();
MetricsServiceGrpc.MetricsServiceStub stub = MetricsServiceGrpc.newStub(channel);
exportRpcHandler = OcAgentMetricsServiceExportRpcHandler.create(stub);
ExportMetricsServiceRequest.Builder builder =
ExportMetricsServiceRequest.newBuilder().setNode(OcAgentNodeUtils.getNodeInfo(serviceName));
@Nullable Resource resourceProto = OcAgentNodeUtils.getAutoDetectedResourceProto();
if (resourceProto != null) {
builder.setResource(resourceProto);
}
exportRpcHandler.onExport(builder.build());
}
@Override
protected ManagedChannel createChannel() {
assertEquals(
"jdk8 required",
"1.8",
System.getProperty("java.specification.version"));
ManagedChannelBuilder<?> builder =
ManagedChannelBuilder.forTarget(INTEROP_TEST_ADDRESS)
.maxInboundMessageSize(AbstractInteropTest.MAX_MESSAGE_SIZE);
assertTrue(builder instanceof NettyChannelBuilder);
((NettyChannelBuilder) builder).flowControlWindow(65 * 1024);
return builder.build();
}
public InternalRpcConnection(String memberAddress, int internalServicePort) {
this.memberAddress = memberAddress;
this.internalServicePort = internalServicePort;
ManagedChannelBuilder<?> managedChannelBuilder = ManagedChannelBuilder.forAddress(memberAddress, internalServicePort)
.maxInboundMessageSize(256 * 1024 * 1024).usePlaintext(true);
channel = managedChannelBuilder.build();
blockingStub = InternalServiceGrpc.newBlockingStub(channel);
log.info("Connecting to <" + memberAddress + ":" + internalServicePort + ">");
}
/**
* Create a {@link ManagedChannel} for the given parameters.
*/
public static ManagedChannel newClientChannel(Transport transport, SocketAddress address,
boolean tls, boolean testca, @Nullable String authorityOverride,
int flowControlWindow, boolean directExecutor) {
ManagedChannelBuilder<?> builder;
if (transport == Transport.OK_HTTP) {
builder = newOkHttpClientChannel(address, tls, testca);
} else {
try {
builder = newNettyClientChannel(transport, address, tls, testca, flowControlWindow);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
if (authorityOverride != null) {
builder.overrideAuthority(authorityOverride);
}
if (directExecutor) {
builder.directExecutor();
} else {
// TODO(carl-mastrangelo): This should not be necessary. I don't know where this should be
// put. Move it somewhere else, or remove it if no longer necessary.
// See: https://github.com/grpc/grpc-java/issues/2119
builder.executor(getExecutor());
}
return builder.build();
}
public static void main(String[] args) throws InterruptedException {
ManagedChannelBuilder<?> channelBuilder = NettyChannelBuilder.forAddress("127.0.0.1", 8080)
.nameResolverFactory(new DnsNameResolverProvider())
.maxInboundMessageSize(1024 * 1024 * 50)
.usePlaintext();
ManagedChannel channel = channelBuilder.build();
TraceSegmentReportServiceGrpc.TraceSegmentReportServiceStub serviceStub = TraceSegmentReportServiceGrpc.newStub(channel);
final Status[] status = {null};
StreamObserver<SegmentObject> streamObserver = serviceStub.collect(new StreamObserver<Commands>() {
@Override
public void onNext(Commands value) {
}
@Override
public void onError(Throwable t) {
status[0] = ((StatusRuntimeException) t).getStatus();
}
@Override
public void onCompleted() {
}
});
streamObserver.onNext(null);
streamObserver.onCompleted();
Thread.sleep(2 * 1000);
Assert.assertEquals(status[0].getCode(), Status.UNAVAILABLE.getCode());
}
@Override
protected ManagedChannel createChannel() {
assertEquals(
"jdk8 required",
"1.8",
System.getProperty("java.specification.version"));
ManagedChannelBuilder<?> builder =
ManagedChannelBuilder.forTarget(INTEROP_TEST_ADDRESS)
.maxInboundMessageSize(AbstractInteropTest.MAX_MESSAGE_SIZE);
assertTrue(builder instanceof NettyChannelBuilder);
((NettyChannelBuilder) builder).flowControlWindow(65 * 1024);
return builder.build();
}
/**
* Creates a new instance of the Controller client class.
* @param channelBuilder The channel builder to connect to the service instance.
* @param config The configuration for this client implementation.
* @param executor The executor service to be used internally.
*/
@VisibleForTesting
public ControllerImpl(ManagedChannelBuilder<?> channelBuilder, final ControllerImplConfig config,
final ScheduledExecutorService executor) {
Preconditions.checkNotNull(channelBuilder, "channelBuilder");
this.executor = executor;
this.retryConfig = createRetryConfig(config);
if (config.getClientConfig().isEnableTlsToController()) {
log.debug("Setting up a SSL/TLS channel builder");
SslContextBuilder sslContextBuilder;
String trustStore = config.getClientConfig().getTrustStore();
sslContextBuilder = GrpcSslContexts.forClient();
if (!Strings.isNullOrEmpty(trustStore)) {
sslContextBuilder = sslContextBuilder.trustManager(new File(trustStore));
}
try {
channelBuilder = ((NettyChannelBuilder) channelBuilder).sslContext(sslContextBuilder.build())
.negotiationType(NegotiationType.TLS);
} catch (SSLException e) {
throw new CompletionException(e);
}
} else {
log.debug("Using a plaintext channel builder");
channelBuilder = ((NettyChannelBuilder) channelBuilder).negotiationType(NegotiationType.PLAINTEXT);
}
// Trace channel.
channelBuilder = channelBuilder.intercept(RPCTracingHelpers.getClientInterceptor());
// Create Async RPC client.
this.channel = channelBuilder.build();
this.client = getClientWithCredentials(config);
this.timeoutMillis = config.getTimeoutMillis();
}
/**
* Construct client for accessing RouteGuide server using the existing channel.
*/
public JupyterKernelClient(ManagedChannelBuilder<?> channelBuilder,
Properties properties,
String kernel) {
channel = channelBuilder.build();
blockingStub = JupyterKernelGrpc.newBlockingStub(channel);
asyncStub = JupyterKernelGrpc.newStub(channel);
this.properties = properties;
this.kernel = kernel;
}
/**
* Constructs a LogdClient with the provided channel
*
* @param channelBuilder a channel to LogD server
*/
@VisibleForTesting
public LogdClient(
ManagedChannelBuilder<?> channelBuilder, StreamObserverFactory streamObserverFactory) {
channel = channelBuilder.build();
blockingStub = LogdServiceGrpc.newBlockingStub(channel);
asyncStub = LogdServiceGrpc.newStub(channel);
this.streamObserverFactory = streamObserverFactory;
}
private static TraceServiceGrpc.TraceServiceStub getTraceServiceStub(
String endPoint, Boolean useInsecure, SslContext sslContext) {
ManagedChannelBuilder<?> channelBuilder;
if (useInsecure) {
channelBuilder = ManagedChannelBuilder.forTarget(endPoint).usePlaintext();
} else {
channelBuilder =
NettyChannelBuilder.forTarget(endPoint)
.negotiationType(NegotiationType.TLS)
.sslContext(sslContext);
}
ManagedChannel channel = channelBuilder.build();
return TraceServiceGrpc.newStub(channel);
}
/** Construct client for accessing RouteGuide server using the existing channel. */
public SubmarineRpcClient(ManagedChannelBuilder<?> channelBuilder) {
channel = channelBuilder.build();
blockingStub = SubmarineServerProtocolGrpc.newBlockingStub(channel);
asyncStub = SubmarineServerProtocolGrpc.newStub(channel);
}
/** Construct client for accessing RouteGuide server using the existing channel. */
public RouteGuideClient(ManagedChannelBuilder<?> channelBuilder) {
channel = channelBuilder.build();
blockingStub = RouteGuideGrpc.newBlockingStub(channel);
asyncStub = RouteGuideGrpc.newStub(channel);
}
/** Construct client for accessing RouteGuide server using the existing channel. */
public RouteGuideClient(ManagedChannelBuilder<?> channelBuilder) {
channel = channelBuilder.build();
blockingStub = RouteGuideGrpc.newBlockingStub(channel);
asyncStub = RouteGuideGrpc.newStub(channel);
}
/**
*
* @param channelBuilder
*/
public ChaincodeSupportClient(final ManagedChannelBuilder<?> channelBuilder) {
this.channel = channelBuilder.build();
this.stub = ChaincodeSupportGrpc.newStub(channel);
}