Java Code Examples for io.rsocket.RSocket#dispose()

The following examples show how to use io.rsocket.RSocket#dispose() . 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: RSocketServerToClientIntegrationTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
private static void connectAndVerify(String destination) {

		ServerController serverController = context.getBean(ServerController.class);
		serverController.reset();

		RSocket rsocket = null;
		try {
			rsocket = RSocketFactory.connect()
					.setupPayload(DefaultPayload.create("", destination))
					.dataMimeType("text/plain")
					.frameDecoder(PayloadDecoder.ZERO_COPY)
					.acceptor(context.getBean("clientAcceptor", MessageHandlerAcceptor.class))
					.transport(TcpClientTransport.create("localhost", 7000))
					.start()
					.block();

			serverController.await(Duration.ofSeconds(5));
		}
		finally {
			if (rsocket != null) {
				rsocket.dispose();
			}
		}
	}
 
Example 2
Source File: LoadBalancedRSocket.java    From alibaba-rsocket-broker with Apache License 2.0 6 votes vote down vote up
public void onRSocketClosed(String rsocketUri, RSocket rsocket, @Nullable Throwable cause) {
    //in last rsocket uris or not
    if (this.lastRSocketUris.contains(rsocketUri)) {
        this.unHealthyUriSet.add(rsocketUri);
        if (activeSockets.containsKey(rsocketUri)) {
            activeSockets.remove(rsocketUri);
            this.randomSelector = new RandomSelector<>(this.serviceId, new ArrayList<>(activeSockets.values()));
            log.error(RsocketErrorCode.message("RST-500407", rsocketUri));
            tryToReconnect(rsocketUri, cause);
        }
        if (!rsocket.isDisposed()) {
            try {
                rsocket.dispose();
            } catch (Exception ignore) {

            }
        }
    }
}
 
Example 3
Source File: LoadBalancedRSocket.java    From alibaba-rsocket-broker with Apache License 2.0 5 votes vote down vote up
public void dispose() {
    super.dispose();
    for (RSocket rsocket : activeSockets.values()) {
        try {
            rsocket.dispose();
        } catch (Exception ignore) {

        }
    }
    activeSockets.clear();
}
 
Example 4
Source File: LoadBalancedRSocket.java    From alibaba-rsocket-broker with Apache License 2.0 5 votes vote down vote up
public void onRSocketClosed(RSocket rsocket, @Nullable Throwable cause) {
    for (Map.Entry<String, RSocket> entry : activeSockets.entrySet()) {
        if (entry.getValue() == rsocket) {
            onRSocketClosed(entry.getKey(), entry.getValue(), null);
        }
    }
    if (!rsocket.isDisposed()) {
        try {
            rsocket.dispose();
        } catch (Exception ignore) {

        }
    }
}
 
Example 5
Source File: HelloWorldClient.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {

    RSocket rsocket =
        new RSocket() {
          boolean fail = true;

          @Override
          public Mono<Payload> requestResponse(Payload p) {
            if (fail) {
              fail = false;
              return Mono.error(new Throwable("Simulated error"));
            } else {
              return Mono.just(p);
            }
          }
        };

    RSocketServer.create(SocketAcceptor.with(rsocket))
        .bind(TcpServerTransport.create("localhost", 7000))
        .subscribe();

    RSocket socket =
        RSocketConnector.connectWith(TcpClientTransport.create("localhost", 7000)).block();

    for (int i = 0; i < 3; i++) {
      socket
          .requestResponse(DefaultPayload.create("Hello"))
          .map(Payload::getDataUtf8)
          .onErrorReturn("error")
          .doOnNext(logger::debug)
          .block();
    }

    socket.dispose();
  }
 
Example 6
Source File: WebSocketHeadersSample.java    From rsocket-java with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {

    ServerTransport.ConnectionAcceptor connectionAcceptor =
        RSocketServer.create(SocketAcceptor.forRequestResponse(Mono::just))
            .payloadDecoder(PayloadDecoder.ZERO_COPY)
            .asConnectionAcceptor();

    DisposableServer server =
        HttpServer.create()
            .host("localhost")
            .port(0)
            .route(
                routes ->
                    routes.get(
                        "/",
                        (req, res) -> {
                          if (req.requestHeaders().containsValue("Authorization", "test", true)) {
                            return res.sendWebsocket(
                                (in, out) ->
                                    connectionAcceptor
                                        .apply(new WebsocketDuplexConnection((Connection) in))
                                        .then(out.neverComplete()));
                          }
                          res.status(HttpResponseStatus.UNAUTHORIZED);
                          return res.send();
                        }))
            .bindNow();

    logger.debug(
        "\n\nStart of Authorized WebSocket Connection\n----------------------------------\n");

    WebsocketClientTransport transport =
        WebsocketClientTransport.create(server.host(), server.port())
            .header("Authorization", "test");

    RSocket clientRSocket =
        RSocketConnector.create()
            .keepAlive(Duration.ofMinutes(10), Duration.ofMinutes(10))
            .payloadDecoder(PayloadDecoder.ZERO_COPY)
            .connect(transport)
            .block();

    Flux.range(1, 100)
        .concatMap(i -> clientRSocket.requestResponse(ByteBufPayload.create("Hello " + i)))
        .doOnNext(payload -> logger.debug("Processed " + payload.getDataUtf8()))
        .blockLast();
    clientRSocket.dispose();

    logger.debug(
        "\n\nStart of Unauthorized WebSocket Upgrade\n----------------------------------\n");

    RSocketConnector.create()
        .keepAlive(Duration.ofMinutes(10), Duration.ofMinutes(10))
        .payloadDecoder(PayloadDecoder.ZERO_COPY)
        .connect(WebsocketClientTransport.create(server.host(), server.port()))
        .block();
  }
 
Example 7
Source File: TaskProcessingWithServerSideNotificationsExample.java    From rsocket-java with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws InterruptedException {
  UnicastProcessor<Task> tasksProcessor =
      UnicastProcessor.create(Queues.<Task>unboundedMultiproducer().get());
  ConcurrentMap<String, BlockingQueue<Task>> idToCompletedTasksMap = new ConcurrentHashMap<>();
  ConcurrentMap<String, RSocket> idToRSocketMap = new ConcurrentHashMap<>();
  BackgroundWorker backgroundWorker =
      new BackgroundWorker(tasksProcessor, idToCompletedTasksMap, idToRSocketMap);

  RSocketServer.create(new TasksAcceptor(tasksProcessor, idToCompletedTasksMap, idToRSocketMap))
      .bindNow(TcpServerTransport.create(9991));

  Logger logger = LoggerFactory.getLogger("RSocket.Client.ID[Test]");

  Mono<RSocket> rSocketMono =
      RSocketConnector.create()
          .setupPayload(DefaultPayload.create("Test"))
          .acceptor(
              SocketAcceptor.forFireAndForget(
                  p -> {
                    logger.info("Received Processed Task[{}]", p.getDataUtf8());
                    p.release();
                    return Mono.empty();
                  }))
          .connect(TcpClientTransport.create(9991));

  RSocket rSocketRequester1 = rSocketMono.block();

  for (int i = 0; i < 10; i++) {
    rSocketRequester1.fireAndForget(DefaultPayload.create("task" + i)).block();
  }

  Thread.sleep(4000);

  rSocketRequester1.dispose();
  logger.info("Disposed");

  Thread.sleep(4000);

  RSocket rSocketRequester2 = rSocketMono.block();

  logger.info("Reconnected");

  Thread.sleep(10000);
}
 
Example 8
Source File: DefaultRSocketClient.java    From rsocket-java with Apache License 2.0 4 votes vote down vote up
@Override
protected void doOnValueExpired(RSocket value) {
  value.dispose();
}