reactor.core.publisher.ReplayProcessor Java Examples

The following examples show how to use reactor.core.publisher.ReplayProcessor. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: WebSocketIntegrationTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void echoForHttp() throws Exception {
	int count = 100;
	Flux<String> input = Flux.range(1, count).map(index -> "msg-" + index);
	ReplayProcessor<Object> output = ReplayProcessor.create(count);

	client.execute(getHttpUrl("/echoForHttp"), session -> {
		logger.debug("Starting to send messages");
		return session
				.send(input.doOnNext(s -> logger.debug("outbound " + s))
						.map(s -> session.textMessage(s)))
				.thenMany(session.receive().take(count)
						.map(WebSocketMessage::getPayloadAsText))
				.subscribeWith(output).doOnNext(s -> logger.debug("inbound " + s))
				.then().doOnSuccess(aVoid -> logger.debug("Done with success"))
				.doOnError(ex -> logger.debug(
						"Done with " + (ex != null ? ex.getMessage() : "error")));
	}).block(Duration.ofMillis(5000));

	assertThat(output.collectList().block(Duration.ofMillis(5000)))
			.isEqualTo(input.collectList().block(Duration.ofMillis(5000)));
}
 
Example #2
Source File: WebSocketIntegrationTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void echo() throws Exception {
	int count = 100;
	Flux<String> input = Flux.range(1, count).map(index -> "msg-" + index);
	ReplayProcessor<Object> output = ReplayProcessor.create(count);

	client.execute(getUrl("/echo"), session -> {
		logger.debug("Starting to send messages");
		return session
				.send(input.doOnNext(s -> logger.debug("outbound " + s))
						.map(s -> session.textMessage(s)))
				.thenMany(session.receive().take(count)
						.map(WebSocketMessage::getPayloadAsText))
				.subscribeWith(output).doOnNext(s -> logger.debug("inbound " + s))
				.then().doOnSuccess(aVoid -> logger.debug("Done with success"))
				.doOnError(ex -> logger.debug(
						"Done with " + (ex != null ? ex.getMessage() : "error")));
	}).block(Duration.ofMillis(5000));

	assertThat(output.collectList().block(Duration.ofMillis(5000)))
			.isEqualTo(input.collectList().block(Duration.ofMillis(5000)));
}
 
Example #3
Source File: WebSocketIntegrationTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void echo() throws Exception {
	int count = 100;
	Flux<String> input = Flux.range(1, count).map(index -> "msg-" + index);
	ReplayProcessor<Object> output = ReplayProcessor.create(count);

	this.client.execute(getUrl("/echo"), session -> session
			.send(input.map(session::textMessage))
			.thenMany(session.receive().take(count).map(WebSocketMessage::getPayloadAsText))
			.subscribeWith(output)
			.then())
			.block(TIMEOUT);

	assertEquals(input.collectList().block(TIMEOUT), output.collectList().block(TIMEOUT));
}
 
Example #4
Source File: RateLimitOperator.java    From Discord4J with GNU Lesser General Public License v3.0 5 votes vote down vote up
public RateLimitOperator(int capacity, Duration refillPeriod, Scheduler delayScheduler, Scheduler publishScheduler) {
    this.tokens = new AtomicInteger(capacity);
    this.refillPeriod = refillPeriod;
    this.delayScheduler = delayScheduler;
    this.tokenChanged = ReplayProcessor.cacheLastOrDefault(capacity);
    this.tokenChangedSink = tokenChanged.sink(FluxSink.OverflowStrategy.LATEST);
    this.tokenPublishScheduler = publishScheduler;
}
 
Example #5
Source File: GrpcMetaProcessor.java    From milkman with MIT License 5 votes vote down vote up
@SneakyThrows
public GrpcResponseContainer listServices(GrpcRequestContainer request, Templater templater) {
	var response = new GrpcResponseContainer(request.getEndpoint());

	ReplayProcessor<String> processor = ReplayProcessor.create();
	fetchServiceList(processor.sink(), request);
  
   	var responsePayloadAspect = new GrpcResponsePayloadAspect(processor);
	response.getAspects().add(responsePayloadAspect);
	
	return response;
}
 
Example #6
Source File: GrpcMetaProcessor.java    From milkman with MIT License 5 votes vote down vote up
@SneakyThrows
public GrpcResponseContainer showServiceDefinition(GrpcRequestContainer request, Templater templater) {
	GrpcOperationAspect operationAspect = request.getAspect(GrpcOperationAspect.class).orElseThrow(() -> new IllegalArgumentException("Operation Aspect missing"));
    var protoMethod = ProtoMethodName.parseFullGrpcMethodName(operationAspect.getOperation());

	ReplayProcessor<String> processor = ReplayProcessor.create();
    fetchServiceDefinition(processor.sink(), request, protoMethod);

    var response = new GrpcResponseContainer(request.getEndpoint());
   	var responsePayloadAspect = new GrpcResponsePayloadAspect(processor);
	response.getAspects().add(responsePayloadAspect);
	
	return response;
}
 
Example #7
Source File: AppServer.java    From reactor-guice with Apache License 2.0 5 votes vote down vote up
private static void testWebsocketClient() throws IOException {
    Properties properties = new Properties();
    // properties.load(new FileInputStream("D:\\project\\reactor-guice\\application.properties"));
    properties.load(new FileInputStream("/Users/develop/Project/reactor-guice/application.properties"));

    int port = Integer.valueOf(properties.getProperty("server.port", "8081"));

    FluxProcessor<String, String> client = ReplayProcessor.<String>create().serialize();

    Flux.interval(Duration.ofMillis(1000))
        .map(Object::toString)
        .subscribe(client::onNext);

    HttpClient.create()
        // .port(port)
        // .wiretap(true)
        .websocket()
        .uri("ws://127.0.0.1:8083/kreactor/ws")
        .handle((in, out) ->
            out.withConnection(conn -> {
                in.aggregateFrames().receiveFrames().map(frames -> {
                    if (frames instanceof TextWebSocketFrame) {
                        System.out.println("Receive text message " + ((TextWebSocketFrame) frames).text());
                    }
                    else if (frames instanceof BinaryWebSocketFrame) {
                        System.out.println("Receive binary message " + frames.content());
                    }
                    else {
                        System.out.println("Receive normal message " + frames.content());
                    }
                    return Mono.empty();
                })
                    .subscribe();
            })
                // .options(NettyPipeline.SendOptions::flushOnEach)
                .sendString(client)
        )
        .blockLast();
}
 
Example #8
Source File: WebSocketIntegrationTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void echo() throws Exception {
	int count = 100;
	Flux<String> input = Flux.range(1, count).map(index -> "msg-" + index);
	ReplayProcessor<Object> output = ReplayProcessor.create(count);

	this.client.execute(getUrl("/echo"), session -> session
			.send(input.map(session::textMessage))
			.thenMany(session.receive().take(count).map(WebSocketMessage::getPayloadAsText))
			.subscribeWith(output)
			.then())
			.block(TIMEOUT);

	assertEquals(input.collectList().block(TIMEOUT), output.collectList().block(TIMEOUT));
}
 
Example #9
Source File: ServerStreamingMethodHandlerTest.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
@Test
public void testOnNextExceptionHandlerOnSubscribe() {
    ReplayProcessor<String> publisher = ReplayProcessor.create(2);
    publisher.onNext("a");
    publisher.onNext("b");
    Disposable disposable = ServerStreamingMethodHandler.internalHandleResult(publisher, responseObserver);
    assertThat(disposable.isDisposed()).isTrue();
}
 
Example #10
Source File: WebSocketSessionHandler.java    From sample-webflux-websocket-netty with Apache License 2.0 5 votes vote down vote up
public WebSocketSessionHandler(int historySize)
{
	receiveProcessor = ReplayProcessor.create(historySize);
	connectedProcessor = MonoProcessor.create();
	disconnectedProcessor = MonoProcessor.create();
	
	webSocketConnected = false;
}
 
Example #11
Source File: WebSocketDemoClient.java    From spring-reactive-sample with GNU General Public License v3.0 5 votes vote down vote up
public static final void main(String[] args) throws URISyntaxException {

        WebSocketClient client = new ReactorNettyWebSocketClient();
//        client.execute(new URI("ws://localhost:8080/echo"), (WebSocketSession session) -> {
//            session.send().log().;
//        });
        
        int count = 100;
		Flux<String> input = Flux.range(1, count).map(index -> "msg-" + index);
		ReplayProcessor<Object> output = ReplayProcessor.create(count);

		client.execute(new URI("ws://localhost:8080/echo"),
				session -> {
					log.debug("Starting to send messages");
					return session
							.send(input.doOnNext(s -> log.debug("outbound " + s)).map(session::textMessage))
							.thenMany(session.receive().take(count).map(WebSocketMessage::getPayloadAsText))
							.subscribeWith(output)
							.doOnNext(s -> log.debug("inbound " + s))
							.then()
							.doOnTerminate((aVoid, ex) ->
									log.debug("Done with " + (ex != null ? ex.getMessage() : "success")));
				})
				.block(Duration.ofMillis(5000));

//		assertEquals(input.collectList().block(Duration.ofMillis(5000)),
//				output.collectList().block(Duration.ofMillis(5000)));
//        client.execute(new URI("ws://localhost:8080/echo")), session -> {
//            session.
//        }
//        ).blockMillis(5000);
    }
 
Example #12
Source File: ReactorProxies.java    From RHub with Apache License 2.0 4 votes vote down vote up
public static ReactorProcProxy replayProcessorProxy() {
    return new ReactorProcProxy(ReplayProcessor.create(), PASS);
}
 
Example #13
Source File: RequesterLeaseHandler.java    From rsocket-java with Apache License 2.0 4 votes vote down vote up
public Impl(String tag, Consumer<Flux<Lease>> leaseReceiver) {
  this.tag = tag;
  receivedLease = ReplayProcessor.create(1);
  leaseReceiver.accept(receivedLease);
}
 
Example #14
Source File: ReactorProxies.java    From RHub with Apache License 2.0 4 votes vote down vote up
public static ReactorProcProxy serializedReplayProcessorProxy() {
    return new ReactorProcProxy(ReplayProcessor.create().serialize(), PASS);
}
 
Example #15
Source File: ReactorProxies.java    From RHub with Apache License 2.0 4 votes vote down vote up
public static ReactorProcProxy safeBehaviorProcessorProxy() {
    return new ReactorProcProxy(ReplayProcessor.create(1), WRAP);
}
 
Example #16
Source File: ReactorProxies.java    From RHub with Apache License 2.0 4 votes vote down vote up
public static ReactorProcProxy safeSerializedBehaviorProcessorProxy() {
    return new ReactorProcProxy(ReplayProcessor.create(1).serialize(), WRAP);
}
 
Example #17
Source File: ReactorProxies.java    From RHub with Apache License 2.0 4 votes vote down vote up
public static ReactorProcProxy safeReplayProcessorProxy() {
    return new ReactorProcProxy(ReplayProcessor.create(), WRAP);
}
 
Example #18
Source File: ReactorProxies.java    From RHub with Apache License 2.0 4 votes vote down vote up
public static ReactorProcProxy safeSerializedReplayProcessorProxy() {
    return new ReactorProcProxy(ReplayProcessor.create().serialize(), WRAP);
}
 
Example #19
Source File: RSocketBufferLeakTests.java    From spring-analysis-note with MIT License 4 votes vote down vote up
ReplayProcessor<PayloadLeakInfo> getPayloads() {
	return this.payloads;
}
 
Example #20
Source File: ReactorProxies.java    From RHub with Apache License 2.0 4 votes vote down vote up
public static ReactorProcProxy serializedBehaviorProcessorProxy() {
    return new ReactorProcProxy(ReplayProcessor.create(1).serialize(), PASS);
}
 
Example #21
Source File: ReactorProxies.java    From RHub with Apache License 2.0 4 votes vote down vote up
public static ReactorProcProxy behaviorProcessorProxy() {
    return new ReactorProcProxy(ReplayProcessor.create(1), PASS);
}
 
Example #22
Source File: ArchaiusSystemDisruptionBudgetResolver.java    From titus-control-plane with Apache License 2.0 4 votes vote down vote up
@Inject
public ArchaiusSystemDisruptionBudgetResolver(PropertyRepository repository) {
    this.budgetEmitter = ReplayProcessor.cacheLastOrDefault(initialBudget(repository));
    this.subscription = repository.get(PROPERTY_KEY, String.class).subscribe(this::processUpdate);
}
 
Example #23
Source File: ConsumerGroupTest.java    From liiklus with MIT License 4 votes vote down vote up
@Test
default void testExclusiveRecordDistribution() throws Exception {
    var numberOfPartitions = getNumberOfPartitions();
    Assumptions.assumeTrue(numberOfPartitions > 1, "target supports more than 1 partition");

    var groupName = UUID.randomUUID().toString();

    var receivedOffsets = new ConcurrentHashMap<Subscription, Set<Tuple2<Integer, Long>>>();

    var disposeAll = ReplayProcessor.<Boolean>create(1);

    Function<Subscription, Disposable> subscribeAndAssign = subscription -> {
        return Flux.from(subscription.getPublisher(() -> CompletableFuture.completedFuture(Collections.emptyMap())))
                .flatMap(Flux::fromStream, numberOfPartitions)
                .flatMap(PartitionSource::getPublisher, numberOfPartitions)
                .takeUntilOther(disposeAll)
                .subscribe(record -> {
                    receivedOffsets
                            .computeIfAbsent(subscription, __ -> new HashSet<>())
                            .add(Tuples.of(record.getPartition(), record.getOffset()));
                });
    };

    try {
        var firstSubscription = getTarget().subscribe(getTopic(), groupName, Optional.of("earliest"));
        var secondSubscription = getTarget().subscribe(getTopic(), groupName, Optional.of("earliest"));

        subscribeAndAssign.apply(firstSubscription);
        subscribeAndAssign.apply(secondSubscription);

        await.untilAsserted(() -> {
            try {
                assertThat(receivedOffsets)
                        .containsKeys(firstSubscription, secondSubscription)
                        .allSatisfy((key, value) -> assertThat(value).isNotEmpty());
            } catch (Throwable e) {
                publishToEveryPartition();
                throw e;
            }
        });

        assertThat(receivedOffsets.get(firstSubscription))
                .doesNotContainAnyElementsOf(receivedOffsets.get(secondSubscription));
    } finally {
        disposeAll.onNext(true);
    }
}
 
Example #24
Source File: ClientWebSocketHandler.java    From sample-webflux-websocket-netty with Apache License 2.0 4 votes vote down vote up
public ClientWebSocketHandler()
{	
	sessionHandler = new WebSocketSessionHandler();
	
	connectedProcessor = ReplayProcessor.create();
}
 
Example #25
Source File: ApiGatewayPublisher.java    From reactor-guice with Apache License 2.0 4 votes vote down vote up
@Override
public Mono<Void> onConnect(Channel channel) {

    RequestAttribute requestAttribute = channel.attr(RequestAttribute.REQUEST_ATTRIBUTE).get();
    String wsUrl = requestAttribute.getAttribute("websocket-inside-url", String.class);

    if (wsUrl==null) {
        return this.onClose(null, channel);
    }

    String channelId = channel.id().asLongText();

    messages.put(channelId, ReplayProcessor.<WebSocketFrame>create().serialize());

    clients.put(channelId, HttpClient
        .create()
        .websocket()
        .uri(wsUrl));

    return clients.get(channelId).handle((in, out) -> out
        .withConnection(con->{
            // channel
            Channel ch = con.channel();
            // on disconnect
            con.onDispose().subscribe(null, null, () ->{
                if (ch.isOpen() && ch.isActive()) {
                    ch.close();
                    clients.remove(ch.id().asLongText());
                    messages.remove(ch.id().asLongText());
                }
            });
            in.aggregateFrames().receiveFrames().subscribe(frame -> {
                if (frame instanceof CloseWebSocketFrame && ch.isOpen() && ch.isActive()) {
                    ch.close();
                    clients.remove(ch.id().asLongText());
                    messages.remove(ch.id().asLongText());
                    return;
                }
                channel.writeAndFlush(frame.retain());
            });
        })
        // .options(NettyPipeline.SendOptions::flushOnEach)
        .sendObject(messages.get(channelId))
    ).then();
}
 
Example #26
Source File: GrpcRequestProcessor.java    From milkman with MIT License 4 votes vote down vote up
protected ResponseDataHolder makeRequest(GrpcRequestContainer request,
										 Templater templater,
										 GrpcOperationAspect operationAspect,
										 GrpcHeaderAspect headerAspect,
										 GrpcPayloadAspect payloadAspect,
										 AsyncControl asyncControl) throws InterruptedException, ExecutionException {
   
	HeaderClientInterceptor clientInterceptor = createHeaderInterceptor(headerAspect, templater);
    var managedChannel = createChannel(request);
	Channel channel = ClientInterceptors.intercept(managedChannel, clientInterceptor);
	
	
    var protoMethod = ProtoMethodName.parseFullGrpcMethodName(operationAspect.getOperation());
	FileDescriptorSet descriptorSet = operationAspect.isUseReflection() 
					? fetchServiceDescriptionViaReflection(channel, protoMethod) 
					: compileProtoSchema(operationAspect.getProtoSchema(), protoMethod);
					
					
	DynamicMessageDeEncoder deenc = new DynamicMessageDeEncoder(protoMethod, descriptorSet);


	ReplayProcessor<DynamicMessage> publisher = ReplayProcessor.create();

	var requestMessages = deenc.deserializeFromJson(templater.replaceTags(payloadAspect.getPayload()));
    var dynamicClient  = DynamicGrpcClient.create(deenc.getMethodDefinition(), channel);
    long startTime = System.currentTimeMillis();
    CompletableFuture<Long> requestTime = new CompletableFuture<>();
    asyncControl.triggerReqeuestStarted();
    var streamObserver = new StreamObserverToPublisherBridge<>(publisher.sink(), () -> managedChannel.shutdown());
	var callFuture = dynamicClient.call(requestMessages, streamObserver, CallOptions.DEFAULT);
    
    asyncControl.onCancellationRequested.add(streamObserver::cancel);
    
    Futures.addCallback(callFuture, new FutureCallback<>() {
		@Override
		public void onSuccess(Void result) {
			requestTime.complete(System.currentTimeMillis() - startTime);
			asyncControl.triggerRequestSucceeded();
		}

		@Override
		public void onFailure(Throwable t) {
			requestTime.complete(System.currentTimeMillis() - startTime);
			asyncControl.triggerRequestFailed(t);
		}
	}, MoreExecutors.directExecutor());
    
    
   	var responseStream = publisher.map(deenc::serializeToJson);
	return new ResponseDataHolder(responseStream, clientInterceptor.getResponseHeaders(), requestTime);
}
 
Example #27
Source File: KVStorageServiceImpl.java    From alibaba-rsocket-broker with Apache License 2.0 4 votes vote down vote up
private void initNotification(String appName) {
    watchNotification.put(appName, ReplayProcessor.cacheLast());
}
 
Example #28
Source File: ConfigurationServiceMVStoreImpl.java    From alibaba-rsocket-broker with Apache License 2.0 4 votes vote down vote up
private void initNotification(String appName) {
    watchNotification.put(appName, ReplayProcessor.cacheLast());
}
 
Example #29
Source File: RSocketBufferLeakTests.java    From spring-analysis-note with MIT License 4 votes vote down vote up
void reset() {
	this.payloads = ReplayProcessor.create();
}