本文整理汇总了Java中io.grpc.stub.StreamObserver类的典型用法代码示例。如果您正苦于以下问题:Java StreamObserver类的具体用法?Java StreamObserver怎么用?Java StreamObserver使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
StreamObserver类属于io.grpc.stub包,在下文中一共展示了StreamObserver类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: downloadProducts
import io.grpc.stub.StreamObserver; //导入依赖的package包/类
@Override
public void downloadProducts(DownloadProductsRequest request, StreamObserver<Product> responseObserver) {
PublishSubject<Product> productPublishSubject = PublishSubject.create();
productPublishSubject
.doOnNext(product -> {
responseObserver.onNext(product);
counter.labels("downloadProducts", "success");
})
.doOnComplete(() -> responseObserver.onCompleted())
.doOnError(t -> {
responseObserver.onError(t);
counter.labels("downloadProducts", "failed");
})
.subscribe();
productDao.downloadProducts(request, productPublishSubject);
}
示例2: manyToOne
import io.grpc.stub.StreamObserver; //导入依赖的package包/类
@Test
public void manyToOne() {
AtomicBoolean called = new AtomicBoolean(false);
GreeterGrpc.GreeterStub stub = GreeterGrpc.newStub(channel);
StreamObserver<HelloRequest> requestStream = stub.sayHelloReqStream(new LambdaStreamObserver<>(
response -> {
assertThat(response.getMessage()).isEqualTo("Hello A and B and C");
called.set(true);
}
));
requestStream.onNext(HelloRequest.newBuilder().setName("A").build());
requestStream.onNext(HelloRequest.newBuilder().setName("B").build());
requestStream.onNext(HelloRequest.newBuilder().setName("C").build());
requestStream.onCompleted();
await().atMost(1, TimeUnit.SECONDS).untilTrue(called);
}
示例3: manyToOne
import io.grpc.stub.StreamObserver; //导入依赖的package包/类
/**
* Implements a stream -> unary call as {@link Flux} -> {@link Mono}, where the client transits a stream of
* messages.
*/
public static <TRequest, TResponse> Mono<TResponse> manyToOne(
Flux<TRequest> rxRequest,
Function<StreamObserver<TResponse>, StreamObserver<TRequest>> delegate) {
try {
return Mono
.<TResponse>create(emitter -> {
ReactiveProducerStreamObserver<TRequest, TResponse> reactiveProducerStreamObserver = new ReactiveProducerStreamObserver<>(
rxRequest,
emitter::success,
emitter::error,
Runnables.doNothing());
delegate.apply(
new CancellableStreamObserver<>(reactiveProducerStreamObserver,
reactiveProducerStreamObserver::cancel));
reactiveProducerStreamObserver.rxSubscribe();
})
.transform(Operators.lift(new SubscribeOnlyOnceLifter<TResponse>()));
} catch (Throwable throwable) {
return Mono.error(throwable);
}
}
示例4: execute
import io.grpc.stub.StreamObserver; //导入依赖的package包/类
@Override
public void execute(
ExecuteRequest request, StreamObserver<Operation> responseObserver) {
Instance instance;
try {
instance = instances.get(request.getInstanceName());
} catch (InstanceNotFoundException ex) {
responseObserver.onError(BuildFarmInstances.toStatusException(ex));
return;
}
instance.execute(
request.getAction(),
request.getSkipCacheLookup(),
request.getTotalInputFileCount(),
request.getTotalInputFileBytes(),
(operation) -> {
responseObserver.onNext(operation);
responseObserver.onCompleted();
});
}
示例5: downloadProductImage
import io.grpc.stub.StreamObserver; //导入依赖的package包/类
@Override
public void downloadProductImage(DownloadProductImageRequest request, StreamObserver<DataChunk> responseObserver) {
try {
BufferedInputStream imageStream = new BufferedInputStream(
productImageSeeker.seekProductImage(request.getProductId())
);
int bufferSize = 256 * 1024;// 256k
byte[] buffer = new byte[bufferSize];
int length;
while ((length = imageStream.read(buffer, 0, bufferSize)) != -1) {
responseObserver.onNext(
DataChunk.newBuilder().setData(ByteString.copyFrom(buffer, 0, length)).build()
);
}
responseObserver.onCompleted();
imageStream.close();
counter.labels("downloadProductImage", "success");
} catch (Exception e) {
counter.labels("downloadProductImage", "failed");
log.error("error on read product image", e);
responseObserver.onError(e);
}
}
示例6: testPublishSome
import io.grpc.stub.StreamObserver; //导入依赖的package包/类
@Test
public void testPublishSome() throws Exception {
doNothing().when(backend).publish(acFactList.capture());
Builder b = MSG_Facts.newBuilder();
Test0Fact f1 = new Test0Fact();
Test0Fact f2 = new Test0Fact();
MSG_Fact msg1 = protoConverter.toProto(f1);
MSG_Fact msg2 = protoConverter.toProto(f2);
b.addAllFact(Arrays.asList(msg1, msg2));
MSG_Facts r = b.build();
uut.publish(r, mock(StreamObserver.class));
verify(backend).publish(anyList());
List<Fact> facts = acFactList.getValue();
assertFalse(facts.isEmpty());
assertEquals(2, facts.size());
assertEquals(f1.id(), facts.get(0).id());
assertEquals(f2.id(), facts.get(1).id());
}
示例7: sayHelloStreaming
import io.grpc.stub.StreamObserver; //导入依赖的package包/类
@Override
public void sayHelloStreaming(HelloRequest req, StreamObserver<HelloReply> responseObserver) {
try {
logger.info("Saying hi");
responseObserver.onNext(
HelloReply.newBuilder().setMessage("Hello " + req.getName()).build());
Thread.sleep(100);
logger.info("Saying hi");
responseObserver.onNext(
HelloReply.newBuilder().setMessage("Hello " + req.getName() + "!").build());
Thread.sleep(100);
logger.info("Saying hi");
responseObserver.onNext(
HelloReply.newBuilder().setMessage("Hello " + req.getName() + "!!").build());
} catch (InterruptedException e) {
responseObserver.onError(e);
} finally {
responseObserver.onCompleted();
}
}
示例8: subscribe
import io.grpc.stub.StreamObserver; //导入依赖的package包/类
@Override
public Subscription subscribe(@NonNull SubscriptionRequestTO req,
@NonNull FactObserver observer) {
SubscriptionImpl<Fact> subscription = SubscriptionImpl.on(observer);
StreamObserver<FactStoreProto.MSG_Notification> responseObserver = new ClientStreamObserver(
subscription);
ClientCall<MSG_SubscriptionRequest, MSG_Notification> call = stub.getChannel().newCall(
RemoteFactStoreGrpc.METHOD_SUBSCRIBE, stub.getCallOptions()
.withWaitForReady()
.withCompression("gzip"));
asyncServerStreamingCall(call, converter.toProto(req), responseObserver);
return subscription.onClose(() -> {
cancel(call);
});
}
示例9: failPlease
import io.grpc.stub.StreamObserver; //导入依赖的package包/类
@Override
public void failPlease(FailWithProbabilityOrSucceedEchoRequest request,
StreamObserver<EchoResponse> responseObserver) {
EchoRequest echoRequest = request.getEchoRequest();
int failProbability = request.getFailProbability();
Preconditions.checkArgument(failProbability >= 0 && failProbability <= 100,
"fail probability not [" + failProbability + "] not in range [0, 100] inclusive");
logger.info("fail please - p(" + failProbability + " / 100)" + " echo: " + echoRequest.getEcho()
+ " with " + "repetitions: " + echoRequest.getRepeatEcho() + " received at "
+ DATE_FORMAT.format(new Date(System.currentTimeMillis())));
int randomFail = RANDOM.nextInt(100);
if (randomFail < failProbability) {
Status status = Status.INTERNAL;
status = status.withCause(new FailPleaseException("Looks like you hit jackpot - we failed!"));
responseObserver.onError(status.asRuntimeException());
} else {
responseObserver.onNext(buildEchoResponseFromEchoRequest(echoRequest));
responseObserver.onCompleted();
}
}
示例10: manyToMany
import io.grpc.stub.StreamObserver; //导入依赖的package包/类
/**
* Implements a bidirectional stream -> stream call as {@link Flowable} -> {@link Flowable}, where both the client
* and the server independently stream to each other.
*/
public static <TRequest, TResponse> Flowable<TResponse> manyToMany(
Flowable<TRequest> rxRequest,
Function<StreamObserver<TResponse>, StreamObserver<TRequest>> delegate) {
try {
final RxProducerConsumerStreamObserver<TRequest, TResponse> consumerStreamObserver = new RxProducerConsumerStreamObserver<TRequest, TResponse>(rxRequest);
delegate.apply(new CancellableStreamObserver<TRequest, TResponse>(consumerStreamObserver, new Runnable() {
@Override
public void run() {
consumerStreamObserver.cancel();
}
}));
consumerStreamObserver.rxSubscribe();
return ((Flowable<TResponse>) consumerStreamObserver.getRxConsumer())
.lift(new SubscribeOnlyOnceFlowableOperator<TResponse>());
} catch (Throwable throwable) {
return Flowable.error(throwable);
}
}
示例11: put
import io.grpc.stub.StreamObserver; //导入依赖的package包/类
@Override
public void put(
Operation operation,
StreamObserver<com.google.rpc.Status> responseObserver) {
Instance instance;
try {
instance = instances.getFromOperationName(operation.getName());
} catch (InstanceNotFoundException ex) {
responseObserver.onError(BuildFarmInstances.toStatusException(ex));
return;
}
boolean ok = instance.putOperation(operation);
Code code = ok ? Code.OK : Code.UNAVAILABLE;
responseObserver.onNext(com.google.rpc.Status.newBuilder()
.setCode(code.getNumber())
.build());
responseObserver.onCompleted();
}
示例12: onLinksVanished
import io.grpc.stub.StreamObserver; //导入依赖的package包/类
private void onLinksVanished(LinkVanishedMsg request,
StreamObserver<Void> responseObserver) {
String scheme = request.getProviderId();
switch (request.getSubjectCase()) {
case CONNECT_POINT:
ConnectPoint cp = translate(request.getConnectPoint());
getLinkProviderServiceFor(scheme).linksVanished(cp);
break;
case DEVICE_ID:
DeviceId did = deviceId(request.getDeviceId());
getLinkProviderServiceFor(scheme).linksVanished(did);
break;
case LINK_DESCRIPTION:
LinkDescription desc = translate(request.getLinkDescription());
getLinkProviderServiceFor(scheme).linkVanished(desc);
break;
case SUBJECT_NOT_SET:
default:
// do nothing
break;
}
}
示例13: onTxEvent
import io.grpc.stub.StreamObserver; //导入依赖的package包/类
@Override
public void onTxEvent(GrpcTxEvent message, StreamObserver<GrpcAck> responseObserver) {
boolean ok = txConsistentService.handle(new TxEvent(
message.getServiceName(),
message.getInstanceId(),
new Date(message.getTimestamp()),
message.getGlobalTxId(),
message.getLocalTxId(),
message.getParentTxId().isEmpty() ? null : message.getParentTxId(),
message.getType(),
message.getCompensationMethod(),
message.getPayloads().toByteArray()
));
responseObserver.onNext(ok ? ALLOW : REJECT);
responseObserver.onCompleted();
}
示例14: createUser
import io.grpc.stub.StreamObserver; //导入依赖的package包/类
@Override
public void createUser(MetaProto.UserParam user,
StreamObserver<StatusProto.ResponseStatus> responseStreamObserver)
{
TransactionController txController = null;
try {
txController = ConnectionPool.INSTANCE().getTxController();
ActionResponse input = new ActionResponse();
input.setParam(user);
txController.setAutoCommit(false);
txController.addAction(new CreateUserAction());
txController.commit(input);
responseStreamObserver.onNext(MetaConstants.OKStatus);
responseStreamObserver.onCompleted();
}
catch (ParaFlowException e) {
responseStreamObserver.onNext(e.getResponseStatus());
responseStreamObserver.onCompleted();
e.handle();
}
finally {
if (txController != null) {
txController.close();
}
}
}
示例15: testNullsOnConstructor
import io.grpc.stub.StreamObserver; //导入依赖的package包/类
@Test
public void testNullsOnConstructor() throws Exception {
String id = "id";
StreamObserver so = mock(StreamObserver.class);
Function p = mock(Function.class);
expectNPE(() -> new GrpcObserverAdapter(null, so, p));
expectNPE(() -> new GrpcObserverAdapter(null, null, p));
expectNPE(() -> new GrpcObserverAdapter(null, null, null));
expectNPE(() -> new GrpcObserverAdapter(id, so, null));
expectNPE(() -> new GrpcObserverAdapter(id, null, p));
expectNPE(() -> new GrpcObserverAdapter(id, null, null));
}