本文整理汇总了Java中io.grpc.Channel类的典型用法代码示例。如果您正苦于以下问题:Java Channel类的具体用法?Java Channel怎么用?Java Channel使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
Channel类属于io.grpc包,在下文中一共展示了Channel类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: metadataInterceptor
import io.grpc.Channel; //导入依赖的package包/类
private ClientInterceptor metadataInterceptor() {
ClientInterceptor interceptor = new ClientInterceptor() {
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
final io.grpc.MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, final Channel next) {
return new ClientInterceptors.CheckedForwardingClientCall<ReqT, RespT>(next.newCall(method, callOptions)) {
@Override
protected void checkedStart(Listener<RespT> responseListener, Metadata headers)
throws StatusException {
for (ConfigProto.CallMetadataEntry entry : callConfiguration.getMetadataList()) {
Metadata.Key<String> key = Metadata.Key.of(entry.getName(), Metadata.ASCII_STRING_MARSHALLER);
headers.put(key, entry.getValue());
}
delegate().start(responseListener, headers);
}
};
}
};
return interceptor;
}
示例2: unaryCall
import io.grpc.Channel; //导入依赖的package包/类
private Object unaryCall(GrpcRequest request, Channel channel) {
String serviceName = request.getServiceName();
String methodName = request.getMethodName();
GrpcURL refUrl = request.getRefUrl();
Integer retryOption = this.buildRetryOption(methodName, refUrl);
GrpcUnaryClientCall clientCall = GrpcUnaryClientCall.create(channel, retryOption, refUrl);
GrpcHystrixCommand hystrixCommand = null;
Boolean isEnableFallback = this.buildFallbackOption(methodName, refUrl);
switch (request.getCallType()) {
case Constants.RPCTYPE_ASYNC:
hystrixCommand = new GrpcFutureUnaryCommand(serviceName, methodName, isEnableFallback);
break;
case Constants.RPCTYPE_BLOCKING:
hystrixCommand = new GrpcBlockingUnaryCommand(serviceName, methodName, isEnableFallback);
break;
default:
hystrixCommand = new GrpcFutureUnaryCommand(serviceName, methodName, isEnableFallback);
break;
}
hystrixCommand.setClientCall(clientCall);
hystrixCommand.setRequest(request);
hystrixCommand.setClientServerMonitor(monitor);
return hystrixCommand.execute();
}
示例3: interceptCall
import io.grpc.Channel; //导入依赖的package包/类
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
final MethodDescriptor<ReqT, RespT> method, CallOptions callOptions,
final Channel next) {
return new ClientInterceptors.CheckedForwardingClientCall<ReqT, RespT>(
next.newCall(method, callOptions)) {
@Override
protected void checkedStart(Listener<RespT> responseListener, Metadata headers)
throws StatusException {
Metadata cachedSaved;
URI uri = serviceUri(next, method);
synchronized (this) {
Map<String, List<String>> latestMetadata = getRequestMetadata(uri);
if (mLastMetadata == null || mLastMetadata != latestMetadata) {
mLastMetadata = latestMetadata;
mCached = toHeaders(mLastMetadata);
}
cachedSaved = mCached;
}
headers.merge(cachedSaved);
delegate().start(responseListener, headers);
}
};
}
示例4: main
import io.grpc.Channel; //导入依赖的package包/类
public static void main(String[] args) throws Exception {
String host = args[0];
int port = Integer.parseInt(args[1]);
String abstractName = "mesh://timeService";
// Open a channel to the server
Channel channel = ManagedChannelBuilder
.forTarget(abstractName)
.nameResolverFactory(StaticResolver.factory(new InetSocketAddress(host, port)))
.usePlaintext(true)
.build();
// Create a CompletableFuture-based stub
TimeServiceGrpc8.TimeServiceCompletableFutureStub stub = TimeServiceGrpc8.newCompletableFutureStub(channel);
// Call the service
CompletableFuture<TimeReply> completableFuture = stub.getTime(Empty.getDefaultInstance());
TimeReply timeReply = completableFuture.get();
// Convert to JDK8 types
Instant now = MoreTimestamps.toInstantUtc(timeReply.getTime());
System.out.println("The time is " + now);
}
示例5: AbstractStubFeaturesShouldPropagate
import io.grpc.Channel; //导入依赖的package包/类
@Test
public void AbstractStubFeaturesShouldPropagate() throws Exception {
com.google.common.base.Preconditions.checkArgument(true);
Channel channel = InProcessChannelBuilder.forName("ignore").build();
com.salesforce.jprotoc.GreeterGrpc8.GreeterCompletableFutureStub stub = com.salesforce.jprotoc.GreeterGrpc8
.newCompletableFutureStub(channel)
.withCompression("bz2")
.withMaxInboundMessageSize(42);
Field innerStubField = com.salesforce.jprotoc.GreeterGrpc8.GreeterCompletableFutureStub.class.getDeclaredField("innerStub");
innerStubField.setAccessible(true);
com.salesforce.jprotoc.GreeterGrpc.GreeterFutureStub innerStub = (com.salesforce.jprotoc.GreeterGrpc.GreeterFutureStub) innerStubField.get(stub);
assertEquals("bz2", stub.getCallOptions().getCompressor());
assertEquals(new Integer(42), stub.getCallOptions().getMaxInboundMessageSize());
assertEquals("bz2", innerStub.getCallOptions().getCompressor());
assertEquals(new Integer(42), innerStub.getCallOptions().getMaxInboundMessageSize());
assertEquals(stub.getCallOptions().toString(), innerStub.getCallOptions().toString());
}
示例6: SeldonClientExample
import io.grpc.Channel; //导入依赖的package包/类
/** Construct client for accessing RouteGuide server using the existing channel. */
public SeldonClientExample(ManagedChannelBuilder<?> channelBuilder) {
ClientInterceptor interceptor = new HeaderClientInterceptor();
channel = channelBuilder.build();
Channel interceptChannel = ClientInterceptors.intercept(channel, interceptor);
blockingStub = SeldonGrpc.newBlockingStub(interceptChannel);
asyncStub = SeldonGrpc.newStub(interceptChannel);
}
示例7: rollbackConfig
import io.grpc.Channel; //导入依赖的package包/类
/**
* if the config is rollback the config of dbleAppender should be rollback too
*/
public static void rollbackConfig() {
if (stub == null && (grpcUrlOld == null && "".equals(grpcUrlOld))) {
grpcUrl = grpcUrlOld;
serverId = serverIdOld;
alertComponentId = alertComponentIdOld;
port = portOld;
grpcUrl = grpcUrlOld;
grpcLevel = grpcLevelOld;
return;
} else {
grpcUrl = grpcUrlOld;
serverId = serverIdOld;
alertComponentId = alertComponentIdOld;
port = portOld;
grpcUrl = grpcUrlOld;
try {
Channel channel = ManagedChannelBuilder.forAddress(grpcUrl, port).usePlaintext(true).build();
stub = UcoreGrpc.newBlockingStub(channel);
} catch (Exception e) {
return;
}
}
}
示例8: interceptCall
import io.grpc.Channel; //导入依赖的package包/类
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(final MethodDescriptor<ReqT, RespT> method,
CallOptions callOptions, final Channel next) {
return new ClientInterceptors.CheckedForwardingClientCall<ReqT, RespT>(
next.newCall(method, callOptions)) {
@Override
protected void checkedStart(Listener<RespT> responseListener, Metadata headers)
throws StatusException {
Metadata cachedSaved;
URI uri = serviceUri(next, method);
synchronized (GoogleCredentialsInterceptor.this) {
Map<String, List<String>> latestMetadata = getRequestMetadata(uri);
if (mLastMetadata == null || mLastMetadata != latestMetadata) {
mLastMetadata = latestMetadata;
mCached = toHeaders(mLastMetadata);
}
cachedSaved = mCached;
}
headers.merge(cachedSaved);
delegate().start(responseListener, headers);
}
};
}
示例9: authenticate
import io.grpc.Channel; //导入依赖的package包/类
/**
* get token from etcd with name and password.
*
* @param channel channel to etcd
* @param username auth name
* @param password auth password
* @return authResp
*/
private ListenableFuture<AuthenticateResponse> authenticate(
Channel channel, ByteSequence username, ByteSequence password) {
ByteString user = byteStringFromByteSequence(username);
ByteString pass = byteStringFromByteSequence(password);
checkArgument(!user.isEmpty(), "username can not be empty.");
checkArgument(!pass.isEmpty(), "password can not be empty.");
return AuthGrpc.newFutureStub(channel).authenticate(
AuthenticateRequest.newBuilder()
.setNameBytes(user)
.setPasswordBytes(pass)
.build()
);
}
示例10: generateToken
import io.grpc.Channel; //导入依赖的package包/类
/**
* get token with ClientBuilder.
*
* @return the auth token
* @throws com.coreos.jetcd.exception.EtcdException a exception indicates failure reason.
*/
private Optional<String> generateToken(Channel channel) {
if (builder.user() != null && builder.password() != null) {
try {
return Optional.of(
authenticate(channel, builder.user(), builder.password()).get().getToken()
);
} catch (InterruptedException ite) {
throw handleInterrupt(ite);
} catch (ExecutionException exee) {
throw toEtcdException(exee);
}
}
return Optional.empty();
}
示例11: interceptCall
import io.grpc.Channel; //导入依赖的package包/类
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
return new SimpleForwardingClientCall<ReqT, RespT>(next.newCall(method, callOptions)) {
@Override
public void start(Listener<RespT> responseListener, Metadata headers) {
getToken(next).ifPresent(t -> headers.put(TOKEN, t));
super.start(new SimpleForwardingClientCallListener<RespT>(responseListener) {
@Override
public void onClose(Status status, Metadata trailers) {
if (isInvalidTokenError(status)) {
try {
refreshToken(next);
} catch (Exception e) {
// don't throw any error here.
// rpc will retry on expired auth token.
}
}
super.onClose(status, trailers);
}
}, headers);
}
};
}
示例12: beforeClass
import io.grpc.Channel; //导入依赖的package包/类
@BeforeClass
public void beforeClass() throws IOException, DuplicateSessionException {
/* create and start service */
final int port = 8080;
final ServiceRunner service = new ServiceRunner.Builder()
.setSessionProvider(sessionProvider)
.setPort(port)
.build();
thread = new Thread(service);
thread.start();
/* create client */
final Channel channel = ManagedChannelBuilder.forAddress("127.0.0.1", port)
.usePlaintext(true).build();
client = DigestServiceGrpc.newBlockingStub(channel);
/* register session id */
sessionId = sessionProvider.createSession(userId);
}
示例13: MemberServiceImpl
import io.grpc.Channel; //导入依赖的package包/类
public MemberServiceImpl(String host, int port, Crypto crypto) {
Preconditions.checkNotNull(host);
Preconditions.checkNotNull(port);
InetAddress address = null;
try {
address = InetAddress.getByName(host);
} catch (UnknownHostException e) {
logger.error("Create member service failed by unknown host exception", e);
Throwables.propagate(e);
}
final Channel channel = NettyChannelBuilder
.forAddress(new InetSocketAddress(address, port))
.negotiationType(NegotiationType.PLAINTEXT)
.build();
initializeStubs(channel);
this.crypto = crypto;
}
示例14: initSession
import io.grpc.Channel; //导入依赖的package包/类
private void initSession(RpcSessionCreateRequestMsg msg) {
log.info("[{}] Initializing session", context().self());
ServerAddress remoteServer = msg.getRemoteAddress();
listener = new BasicRpcSessionListener(systemContext, context().parent(), context().self());
if (msg.getRemoteAddress() == null) {
// Server session
session = new GrpcSession(listener);
session.setOutputStream(msg.getResponseObserver());
session.initInputStream();
session.initOutputStream();
systemContext.getRpcService().onSessionCreated(msg.getMsgUid(), session.getInputStream());
} else {
// Client session
Channel channel = ManagedChannelBuilder.forAddress(remoteServer.getHost(), remoteServer.getPort()).usePlaintext(true).build();
session = new GrpcSession(remoteServer, listener);
session.initInputStream();
ClusterRpcServiceGrpc.ClusterRpcServiceStub stub = ClusterRpcServiceGrpc.newStub(channel);
StreamObserver<ClusterAPIProtos.ToRpcServerMessage> outputStream = stub.handlePluginMsgs(session.getInputStream());
session.setOutputStream(outputStream);
session.initOutputStream();
outputStream.onNext(toConnectMsg());
}
}
示例15: UnaryCallRetryInterceptor
import io.grpc.Channel; //导入依赖的package包/类
public UnaryCallRetryInterceptor(
Channel delegate,
ScheduledExecutorService executorService,
Set<MethodDescriptor<?, ?>> retriableMethods,
int initialBackoffMillis,
double backoffMultiplier,
int maxElapsedBackoffMillis) {
this(
delegate,
executorService,
Maps.asMap(retriableMethods, new Function<MethodDescriptor<?, ?>, Predicate<?>>() {
@Override
public Predicate<Object> apply(MethodDescriptor<?, ?> methodDescriptor) {
return Predicates.alwaysTrue();
}
}),
initialBackoffMillis,
backoffMultiplier,
maxElapsedBackoffMillis);
}