下面列出了怎么用io.grpc.netty.NegotiationType的API类实例代码及写法,或者点击链接到github查看源代码。
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();
}
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();
}
@SuppressWarnings("deprecation")
final ManagedChannelBuilder<?> newChannelBuilder() throws IOException {
// Consider moving this to be pure GRPC
// This is being reworked in master so leaving this 'as-is'
final NettyChannelBuilder builder = NettyChannelBuilder.forAddress(host, port);
LOGGER.info("Configuring channel connection to peer.");
if (tlsEnabled) {
builder.negotiationType(NegotiationType.TLS);
builder.sslContext(createSSLContext());
} else {
builder.usePlaintext();
}
// there is a optional in GRPC to use 'directExecutor' rather than the inbuilt
// gRPC thread management
// not seen to make a marked difference in performance.
// However if it ever does, then this is where it should be enabled
return builder;
}
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());
}
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();
}
/**
* 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 ManagedChannel createChannel() {
InetAddress address;
try {
address = InetAddress.getByName(serverHost);
} catch (UnknownHostException ex) {
throw new RuntimeException(ex);
}
return NettyChannelBuilder.forAddress(new InetSocketAddress(address, serverPort))
.negotiationType(NegotiationType.PLAINTEXT)
.build();
}
private ManagedChannel createChannel(InetSocketAddress address) {
SslContext sslContext = null;
if (useTestCa) {
try {
sslContext = GrpcSslContexts.forClient().trustManager(
TestUtils.loadCert("ca.pem")).build();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
return NettyChannelBuilder.forAddress(address)
.negotiationType(useTls ? NegotiationType.TLS : NegotiationType.PLAINTEXT)
.sslContext(sslContext)
.build();
}
@Override
protected ManagedChannel createChannel() {
NettyChannelBuilder builder = NettyChannelBuilder.forAddress("localhost", getPort())
.negotiationType(NegotiationType.PLAINTEXT)
.maxInboundMessageSize(AbstractInteropTest.MAX_MESSAGE_SIZE);
io.grpc.internal.TestingAccessor.setStatsImplementation(
builder, createClientCensusStatsModule());
return builder.build();
}
/**
* 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();
}
@BeforeClass
public static void setupClientChannel() {
clientChannel = NettyChannelBuilder.forAddress("localhost", port)
.negotiationType(NegotiationType.TLS)
.sslContext(getSslContext())
.build();
}
private ManagedChannel buildChannel(String address, Optional<SslContext> sslContext) {
if (sslContext.isPresent()) {
return NettyChannelBuilder.forTarget(address)
.negotiationType(NegotiationType.TLS)
.sslContext(sslContext.get())
.build();
} else {
return ManagedChannelBuilder
.forTarget(address).usePlaintext()
.build();
}
}
@BeforeClass
public static void setupClientChannel() {
clientChannel = NettyChannelBuilder.forAddress("localhost", port)
.negotiationType(NegotiationType.TLS)
.sslContext(getSslContext())
.build();
}
/**
* Create a new gRPC {@link ManagedChannel}.
*
* @throws IOException in case the channel can't be constructed.
*/
public static ManagedChannel newChannel(
String target, AuthAndTLSOptions options, ClientInterceptor... interceptors)
throws IOException {
Preconditions.checkNotNull(target);
Preconditions.checkNotNull(options);
Preconditions.checkNotNull(interceptors);
final SslContext sslContext =
options.tlsEnabled ? createSSlContext(options.tlsCertificate) : null;
try {
NettyChannelBuilder builder =
NettyChannelBuilder.forTarget(target)
.negotiationType(options.tlsEnabled ? NegotiationType.TLS : NegotiationType.PLAINTEXT)
.defaultLoadBalancingPolicy("round_robin")
.intercept(interceptors);
if (sslContext != null) {
builder.sslContext(sslContext);
if (options.tlsAuthorityOverride != null) {
builder.overrideAuthority(options.tlsAuthorityOverride);
}
}
return builder.build();
} catch (RuntimeException e) {
// gRPC might throw all kinds of RuntimeExceptions: StatusRuntimeException,
// IllegalStateException, NullPointerException, ...
String message = "Failed to connect to '%s': %s";
throw new IOException(String.format(message, target, e.getMessage()));
}
}
public GRPCClient(String host, int port, int observerPort) {
log.debug("Trying to connect to GRPC host:port={}:{}, host:observerPort={}:{}, ", host, port, observerPort);
ManagedChannel channel = NettyChannelBuilder.forAddress(host, port).negotiationType(NegotiationType.PLAINTEXT).build();
ManagedChannel observerChannel = NettyChannelBuilder.forAddress(host, observerPort).negotiationType(NegotiationType.PLAINTEXT).build();
pbs = PeerGrpc.newBlockingStub(channel);
obs = OpenchainGrpc.newBlockingStub(channel);
observer = new GRPCObserver(observerChannel);
observer.connect();
}
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);
}
@Override
protected void runIfChecksOkay() {
try {
ChannelFactory channelFactory = () -> NettyChannelBuilder //
.forAddress(host, port)
.negotiationType(NegotiationType.PLAINTEXT)
.keepAliveTime(keepAliveInSeconds, TimeUnit.SECONDS)
.keepAliveTimeout(keepAliveTimeoutInSeconds, TimeUnit.SECONDS)
.maxInboundMessageSize(maxMessageSize)
.build();
PathRules includes = new PathRules();
PathRules excludes = new PathRules();
setupIncludesAndExcludes(includes, excludes, extraIncludes, extraExcludes, useInternalPatterns);
TaskFactory taskFactory = new ThreadBasedTaskFactory();
FileWatcherFactory watcherFactory = FileWatcherFactory.newFactory(taskFactory);
MirrorClient client = new MirrorClient(//
new MirrorPaths(Paths.get(localRoot), Paths.get(remoteRoot), includes, excludes, debugAll, debugPrefixes),
taskFactory,
new ConnectionDetector.Impl(channelFactory),
watcherFactory,
new NativeFileAccess(Paths.get(localRoot).toAbsolutePath()),
channelFactory);
client.startSession();
// dumb way of waiting until they hit control-c
CountDownLatch cl = new CountDownLatch(1);
cl.await();
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
}
public static void main(String[] args) throws Exception {
ChannelFactory cf = () -> NettyChannelBuilder.forAddress("shaberma-ld1", 49172).negotiationType(NegotiationType.PLAINTEXT).build();
while (true) {
new Impl(cf).blockUntilConnected();
System.out.println("CONNECTED");
Thread.sleep(5000);
}
}
/**
* 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();
}
/** Return {@link io.grpc.Channel} which is used by Cloud Pub/Sub gRPC API's. */
public static Channel getChannel(CredentialsProvider credentialsProvider) throws IOException {
ManagedChannel channelImpl =
NettyChannelBuilder.forAddress(ENDPOINT, 443)
.negotiationType(NegotiationType.TLS)
// Maximum Pub/Sub message size is 10MB.
.maxInboundMessageSize(10 * 1024 * 1024)
.build();
final ClientAuthInterceptor interceptor =
new ClientAuthInterceptor(
credentialsProvider.getCredentials(),
Executors.newCachedThreadPool());
return ClientInterceptors.intercept(channelImpl, interceptor);
}
public GRPCClient(String host, int port, int observerPort) {
log.debug("Trying to connect to GRPC host:port={}:{}, host:observerPort={}:{}, ", host, port, observerPort);
ManagedChannel channel = NettyChannelBuilder.forAddress(host, port).negotiationType(NegotiationType.PLAINTEXT).build();
ManagedChannel observerChannel = NettyChannelBuilder.forAddress(host, observerPort).negotiationType(NegotiationType.PLAINTEXT).build();
dbs = DevopsGrpc.newBlockingStub(channel);
obs = OpenchainGrpc.newBlockingStub(channel);
observer = new GRPCObserver(observerChannel);
observer.connect();
}
@Override
public NettyChannelBuilder build(
NettyChannelBuilder managedChannelBuilder) throws AgentPackageNotFoundException, SSLException {
File caFile = new File(AgentPackagePath.getPath(), CA_FILE_NAME);
if (caFile.exists() && caFile.isFile()) {
SslContextBuilder builder = GrpcSslContexts.forClient();
builder.trustManager(caFile);
managedChannelBuilder = managedChannelBuilder.negotiationType(NegotiationType.TLS)
.sslContext(builder.build());
}
return managedChannelBuilder;
}
public static void main(final String[] args) throws Exception {
if (args.length == 0) {
System.err.println("Please specify your project name.");
System.exit(1);
}
final String project = args[0];
ManagedChannelImpl channelImpl = NettyChannelBuilder
.forAddress("pubsub.googleapis.com", 443)
.negotiationType(NegotiationType.TLS)
.build();
GoogleCredentials creds = GoogleCredentials.getApplicationDefault();
// Down-scope the credential to just the scopes required by the service
creds = creds.createScoped(Arrays.asList("https://www.googleapis.com/auth/pubsub"));
// Intercept the channel to bind the credential
ExecutorService executor = Executors.newSingleThreadExecutor();
ClientAuthInterceptor interceptor = new ClientAuthInterceptor(creds, executor);
Channel channel = ClientInterceptors.intercept(channelImpl, interceptor);
// Create a stub using the channel that has the bound credential
PublisherGrpc.PublisherBlockingStub publisherStub = PublisherGrpc.newBlockingStub(channel);
ListTopicsRequest request = ListTopicsRequest.newBuilder()
.setPageSize(10)
.setProject("projects/" + project)
.build();
ListTopicsResponse resp = publisherStub.listTopics(request);
System.out.println("Found " + resp.getTopicsCount() + " topics.");
for (Topic topic : resp.getTopicsList()) {
System.out.println(topic.getName());
}
}
/**
* Create a new gRPC {@link ManagedChannel}.
*
* @throws IOException in case the channel can't be constructed.
*/
public static ManagedChannel newChannel(
String target,
String proxy,
AuthAndTLSOptions options,
@Nullable List<ClientInterceptor> interceptors)
throws IOException {
Preconditions.checkNotNull(target);
Preconditions.checkNotNull(options);
SslContext sslContext =
isTlsEnabled(target)
? createSSlContext(
options.tlsCertificate, options.tlsClientCertificate, options.tlsClientKey)
: null;
String targetUrl = convertTargetScheme(target);
try {
NettyChannelBuilder builder =
newNettyChannelBuilder(targetUrl, proxy)
.negotiationType(
isTlsEnabled(target) ? NegotiationType.TLS : NegotiationType.PLAINTEXT);
if (interceptors != null) {
builder.intercept(interceptors);
}
if (sslContext != null) {
builder.sslContext(sslContext);
if (options.tlsAuthorityOverride != null) {
builder.overrideAuthority(options.tlsAuthorityOverride);
}
}
return builder.build();
} catch (RuntimeException e) {
// gRPC might throw all kinds of RuntimeExceptions: StatusRuntimeException,
// IllegalStateException, NullPointerException, ...
String message = "Failed to connect to '%s': %s";
throw new IOException(String.format(message, targetUrl, e.getMessage()));
}
}
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 ManagedChannel createChannel() {
InetAddress address;
try {
address = InetAddress.getByName(serverHost);
} catch (UnknownHostException ex) {
throw new RuntimeException(ex);
}
return NettyChannelBuilder.forAddress(new InetSocketAddress(address, serverPort))
.negotiationType(NegotiationType.PLAINTEXT)
.build();
}
private ManagedChannel createChannel(InetSocketAddress address) {
SslContext sslContext = null;
if (useTestCa) {
try {
sslContext = GrpcSslContexts.forClient().trustManager(
TestUtils.loadCert("ca.pem")).build();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
return NettyChannelBuilder.forAddress(address)
.negotiationType(useTls ? NegotiationType.TLS : NegotiationType.PLAINTEXT)
.sslContext(sslContext)
.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();
}