Esempio n. 1
0
  private static void start() throws Exception {
    List<Transport> transports =
        Collections.<Transport>singletonList(new WebSocketTransport(new StandardWebSocketClient()));
    WebSocketStompClient stompClient = new WebSocketStompClient(new SockJsClient(transports));

    stompClient.setMessageConverter(new MappingJackson2MessageConverter());

    StompSessionHandlerAdapter handler =
        new StompSessionHandlerAdapter() {
          @Override
          public void afterConnected(StompSession session, StompHeaders connectedHeaders) {
            LOG.info("Connected to {}", session);
          }

          @Override
          public void handleException(
              StompSession session,
              StompCommand command,
              StompHeaders headers,
              byte[] payload,
              Throwable exception) {
            throw new RuntimeException(exception);
          }
        };

    ListenableFuture<StompSession> lss = stompClient.connect(URL, handler);

    StompSession ss = lss.get();

    ss.subscribe("/user/queue/greetings", new StringHandler());
    ss.subscribe("/topic/latest/USD/EUR", new RatesHandler());
    ss.subscribe("/topic/latest/BRE/USD", new RatesHandler());

    ss.send("/app/hello", "dede");

    LOG.info("hello done");
  }
  @Test
  public void basicMessagingWithJson() throws Throwable {
    EnvironmentTestUtils.addEnvironment(
        this.context, "server.port:0", "spring.jackson.serialization.indent-output:true");
    this.context.register(WebSocketMessagingConfiguration.class);
    new ServerPortInfoApplicationContextInitializer().initialize(this.context);
    this.context.refresh();
    WebSocketStompClient stompClient = new WebSocketStompClient(this.sockJsClient);
    final AtomicReference<Throwable> failure = new AtomicReference<Throwable>();
    final AtomicReference<Object> result = new AtomicReference<Object>();
    final CountDownLatch latch = new CountDownLatch(1);
    StompSessionHandler handler =
        new StompSessionHandlerAdapter() {

          @Override
          public void afterConnected(StompSession session, StompHeaders connectedHeaders) {
            session.subscribe(
                "/app/data",
                new StompFrameHandler() {

                  @Override
                  public void handleFrame(StompHeaders headers, Object payload) {
                    result.set(payload);
                    latch.countDown();
                  }

                  @Override
                  public Type getPayloadType(StompHeaders headers) {
                    return Object.class;
                  }
                });
          }

          @Override
          public void handleFrame(StompHeaders headers, Object payload) {
            latch.countDown();
          }

          @Override
          public void handleException(
              StompSession session,
              StompCommand command,
              StompHeaders headers,
              byte[] payload,
              Throwable exception) {
            failure.set(exception);
            latch.countDown();
          }

          @Override
          public void handleTransportError(StompSession session, Throwable exception) {
            failure.set(exception);
            latch.countDown();
          }
        };

    stompClient.setMessageConverter(new SimpleMessageConverter());
    stompClient.connect(
        "ws://localhost:{port}/messaging",
        handler,
        this.context.getEnvironment().getProperty("local.server.port"));

    if (!latch.await(30, TimeUnit.SECONDS)) {
      if (failure.get() != null) {
        throw failure.get();
      } else {
        fail("Response was not received within 30 seconds");
      }
    }
    assertThat(
        new String((byte[]) result.get()),
        is(equalTo(String.format("{%n  \"foo\" : 5,%n  \"bar\" : \"baz\"%n}"))));
  }
  public static void main(String[] args) throws Exception {

    // Modify host and port below to match wherever StompWebSocketServer.java is running!!
    // When StompWebSocketServer starts it prints the selected available

    String host = "localhost";
    if (args.length > 0) {
      host = args[0];
    }

    int port = 37232;
    if (args.length > 1) {
      port = Integer.valueOf(args[1]);
    }

    String homeUrl = "http://{host}:{port}/home";
    logger.debug("Sending warm-up HTTP request to " + homeUrl);
    HttpStatus status =
        new RestTemplate().getForEntity(homeUrl, Void.class, host, port).getStatusCode();
    Assert.state(status == HttpStatus.OK);

    final CountDownLatch connectLatch = new CountDownLatch(NUMBER_OF_USERS);
    final CountDownLatch subscribeLatch = new CountDownLatch(NUMBER_OF_USERS);
    final CountDownLatch messageLatch = new CountDownLatch(NUMBER_OF_USERS);
    final CountDownLatch disconnectLatch = new CountDownLatch(NUMBER_OF_USERS);

    final AtomicReference<Throwable> failure = new AtomicReference<>();

    StandardWebSocketClient webSocketClient = new StandardWebSocketClient();

    HttpClient jettyHttpClient = new HttpClient();
    jettyHttpClient.setMaxConnectionsPerDestination(1000);
    jettyHttpClient.setExecutor(new QueuedThreadPool(1000));
    jettyHttpClient.start();

    List<Transport> transports = new ArrayList<>();
    transports.add(new WebSocketTransport(webSocketClient));
    transports.add(new JettyXhrTransport(jettyHttpClient));

    SockJsClient sockJsClient = new SockJsClient(transports);

    try {
      ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
      taskScheduler.afterPropertiesSet();

      String stompUrl = "ws://{host}:{port}/stomp";
      WebSocketStompClient stompClient = new WebSocketStompClient(sockJsClient);
      stompClient.setMessageConverter(new StringMessageConverter());
      stompClient.setTaskScheduler(taskScheduler);
      stompClient.setDefaultHeartbeat(new long[] {0, 0});

      logger.debug("Connecting and subscribing " + NUMBER_OF_USERS + " users ");
      StopWatch stopWatch = new StopWatch("STOMP Broker Relay WebSocket Load Tests");
      stopWatch.start();

      List<ConsumerStompSessionHandler> consumers = new ArrayList<>();
      for (int i = 0; i < NUMBER_OF_USERS; i++) {
        consumers.add(
            new ConsumerStompSessionHandler(
                BROADCAST_MESSAGE_COUNT,
                connectLatch,
                subscribeLatch,
                messageLatch,
                disconnectLatch,
                failure));
        stompClient.connect(stompUrl, consumers.get(i), host, port);
      }

      if (failure.get() != null) {
        throw new AssertionError("Test failed", failure.get());
      }
      if (!connectLatch.await(5000, TimeUnit.MILLISECONDS)) {
        fail("Not all users connected, remaining: " + connectLatch.getCount());
      }
      if (!subscribeLatch.await(5000, TimeUnit.MILLISECONDS)) {
        fail("Not all users subscribed, remaining: " + subscribeLatch.getCount());
      }

      stopWatch.stop();
      logger.debug("Finished: " + stopWatch.getLastTaskTimeMillis() + " millis");

      logger.debug(
          "Broadcasting "
              + BROADCAST_MESSAGE_COUNT
              + " messages to "
              + NUMBER_OF_USERS
              + " users ");
      stopWatch.start();

      ProducerStompSessionHandler producer =
          new ProducerStompSessionHandler(BROADCAST_MESSAGE_COUNT, failure);
      stompClient.connect(stompUrl, producer, host, port);
      stompClient.setTaskScheduler(taskScheduler);

      if (failure.get() != null) {
        throw new AssertionError("Test failed", failure.get());
      }
      if (!messageLatch.await(60 * 1000, TimeUnit.MILLISECONDS)) {
        for (ConsumerStompSessionHandler consumer : consumers) {
          if (consumer.messageCount.get() < consumer.expectedMessageCount) {
            logger.debug(consumer);
          }
        }
      }
      if (!messageLatch.await(60 * 1000, TimeUnit.MILLISECONDS)) {
        fail("Not all handlers received every message, remaining: " + messageLatch.getCount());
      }

      producer.session.disconnect();
      if (!disconnectLatch.await(5000, TimeUnit.MILLISECONDS)) {
        fail("Not all disconnects completed, remaining: " + disconnectLatch.getCount());
      }

      stopWatch.stop();
      logger.debug("Finished: " + stopWatch.getLastTaskTimeMillis() + " millis");

      System.out.println("\nPress any key to exit...");
      System.in.read();
    } catch (Throwable t) {
      t.printStackTrace();
    } finally {
      jettyHttpClient.stop();
    }

    logger.debug("Exiting");
    System.exit(0);
  }