org.springframework.messaging.rsocket.RSocketRequester Java Examples

The following examples show how to use org.springframework.messaging.rsocket.RSocketRequester. 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: BrokerActuatorIntegrationTests.java    From spring-cloud-rsocket with Apache License 2.0 6 votes vote down vote up
@Test
@Ignore // TODO: move to integration tests module
public void routeJoinCloseDeregisters() {
	long brokerId = random.nextLong();
	long routeId = random.nextLong();

	RouteJoin data = RouteJoin.builder().brokerId(brokerId).routeId(routeId)
			.serviceName("testServiceName").build();

	RSocketRequester requester = getRequester(brokerId);
	Mono<RouteJoin> result = callActuator(requester, brokerId, RouteJoin.class, data,
			ROUTE_JOIN_PATH);

	result.block();
	StepVerifier.create(result)
			.consumeNextWith(res -> assertThat(res).isNotNull().isEqualTo(data))
			.verifyComplete();

	requester.rsocket().dispose();

	// TODO: assert server side calls worked
}
 
Example #2
Source File: RSocketClientToSecuredServerITest.java    From spring-rsocket-demo with GNU General Public License v3.0 6 votes vote down vote up
@BeforeAll
public static void setupOnce(@Autowired RSocketRequester.Builder builder,
                             @LocalRSocketServerPort Integer port,
                             @Autowired RSocketStrategies strategies) {

    SocketAcceptor responder = RSocketMessageHandler.responder(strategies, new ClientHandler());
    mimeType = MimeTypeUtils.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_AUTHENTICATION.getString());

    // *******  The user 'test' is NOT in the required 'USER' role! **********
    credentials = new UsernamePasswordMetadata("test", "pass");

    requester = builder
            .setupRoute("shell-client")
            .setupData(UUID.randomUUID().toString())
            .setupMetadata(credentials, mimeType)
            .rsocketStrategies(b ->
                    b.encoder(new SimpleAuthenticationEncoder()))

            .rsocketConnector(connector -> connector.acceptor(responder))
            .connectTcp("localhost", port)
            .block();
}
 
Example #3
Source File: RSocketClientToServerITest.java    From spring-rsocket-demo with GNU General Public License v3.0 6 votes vote down vote up
@BeforeAll
public static void setupOnce(@Autowired RSocketRequester.Builder builder,
                             @LocalRSocketServerPort Integer port,
                             @Autowired RSocketStrategies strategies) {

    SocketAcceptor responder = RSocketMessageHandler.responder(strategies, new ClientHandler());
    credentials = new UsernamePasswordMetadata("user", "pass");
    mimeType = MimeTypeUtils.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_AUTHENTICATION.getString());

    requester = builder
            .setupRoute("shell-client")
            .setupData(UUID.randomUUID().toString())
            .setupMetadata(credentials, mimeType)
            .rsocketStrategies(b ->
                    b.encoder(new SimpleAuthenticationEncoder()))
            .rsocketConnector(connector -> connector.acceptor(responder))
            .connectTcp("localhost", port)
            .block();
}
 
Example #4
Source File: BrokerActuatorIntegrationTests.java    From spring-cloud-rsocket with Apache License 2.0 6 votes vote down vote up
public void routeRemoveWorks(RSocketRequester requester, long routeId) {
	long brokerId = random.nextLong();
	RouteRemove data = RouteRemove.builder().brokerId(brokerId).routeId(routeId)
			.build();

	Mono<Boolean> result = callActuator(requester, brokerId, Boolean.class, data,
			ROUTE_REMOVE_PATH);

	StepVerifier.create(result).consumeNextWith(res -> assertThat(res).isTrue())
			.verifyComplete();
	// TODO: assert server side calls worked

	result = callActuator(brokerId, Boolean.class, data, ROUTE_REMOVE_PATH);

	StepVerifier.create(result).consumeNextWith(res -> assertThat(res).isTrue())
			.verifyComplete();
}
 
Example #5
Source File: ClusterJoinListener.java    From spring-cloud-rsocket with Apache License 2.0 6 votes vote down vote up
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
	for (Broker broker : properties.getBrokers()) {
		RouteSetup routeSetup = RouteSetup
				.of(properties.getRouteId(), properties.getServiceName()).build();

		// TODO: micrometer
		RSocketRequester.builder().rsocketStrategies(strategies)
				.setupMetadata(routeSetup, RouteSetup.ROUTE_SETUP_MIME_TYPE)
				.rsocketFactory(rsocketFactory -> rsocketFactory
						.acceptor(brokerSocketAcceptor()))
				// TODO: other types
				.connectTcp(broker.getHost(), broker.getPort())
				.flatMap(this::callBrokerInfo).subscribe(this::registerOutgoing);
	}
}
 
Example #6
Source File: BrokerActuatorIntegrationTests.java    From spring-cloud-rsocket with Apache License 2.0 6 votes vote down vote up
@Test
@Ignore // TODO: move to integration tests module
public void routeJoinRemoveWorks() {
	long brokerId = random.nextLong();
	long routeId = random.nextLong();

	RouteJoin data = RouteJoin.builder().brokerId(brokerId).routeId(routeId)
			.serviceName("testServiceName").build();

	RSocketRequester requester = getRequester(brokerId);
	Mono<RouteJoin> result = callActuator(requester, brokerId, RouteJoin.class, data,
			ROUTE_JOIN_PATH);

	StepVerifier.create(result)
			.consumeNextWith(res -> assertThat(res).isNotNull().isEqualTo(data))
			.verifyComplete();
	// TODO: assert server side calls worked

	routeRemoveWorks(requester, routeId);
}
 
Example #7
Source File: ClusterJoinListener.java    From spring-cloud-rsocket with Apache License 2.0 5 votes vote down vote up
Mono<Tuple2<BigInteger, RSocketRequester>> callBrokerInfo(
		RSocketRequester requester) {
	Forwarding forwarding = Forwarding.of(properties.getRouteId())
			.serviceName("gateway").disableProxy().build();
	return requester.route(BrokerActuator.BROKER_INFO_PATH)
			.metadata(forwarding, Forwarding.FORWARDING_MIME_TYPE)
			.data(BrokerInfo.of(properties.getRouteId()).build())
			.retrieveMono(BigInteger.class)
			.map(brokerId -> Tuples.of(brokerId, requester));
}
 
Example #8
Source File: PongService.java    From rsocket-routing-sample with Apache License 2.0 5 votes vote down vote up
@EventListener
public void onRSocketRequester(RSocketRequester requester) {
	Boolean isClient = env.getProperty("pong.client", Boolean.class, true);

	log.info("Starting Pong isClient: " + isClient);

	if (!isClient) {
		/*FIXME: RSocketFactory.receive()
				.addServerPlugin(interceptor)
				.acceptor(this)
				.transport(TcpServerTransport.create(port)) // listen on port
				.start()
				.subscribe();*/
	}
}
 
Example #9
Source File: BrokerClient.java    From spring-cloud-rsocket with Apache License 2.0 5 votes vote down vote up
public Mono<RSocketRequester> connect(RSocketRequester.Builder requesterBuilder) {
	Broker broker = properties.getBroker();
	switch (broker.getConnectionType()) {
	case WEBSOCKET:
		return requesterBuilder.connectWebSocket(broker.getWsUri());
	}
	return requesterBuilder.connectTcp(broker.getHost(), broker.getPort());
}
 
Example #10
Source File: GatewayRSocketClientAutoConfiguration.java    From spring-cloud-rsocket with Apache License 2.0 5 votes vote down vote up
@Bean
@Scope("prototype") // TODO: I don't think prototype works here
@ConditionalOnMissingBean
public RSocketRequester.Builder gatewayRSocketRequesterBuilder(
		RSocketStrategies strategies, ClientProperties properties,
		MeterRegistry meterRegistry) {
	RouteSetup.Builder routeSetup = RouteSetup.of(properties.getRouteId(),
			properties.getServiceName());
	properties.getTags().forEach((key, value) -> {
		if (key.getWellKnownKey() != null) {
			routeSetup.with(key.getWellKnownKey(), value);
		}
		else if (key.getCustomKey() != null) {
			routeSetup.with(key.getCustomKey(), value);
		}
	});

	MicrometerRSocketInterceptor interceptor = new MicrometerRSocketInterceptor(
			meterRegistry, Tag.of("servicename", properties.getServiceName()));

	RSocketRequester.Builder builder = RSocketRequester.builder()
			.setupMetadata(routeSetup.build(), RouteSetup.ROUTE_SETUP_MIME_TYPE)
			.rsocketStrategies(strategies).rsocketFactory(configurer(interceptor));

	return new ClientRSocketRequesterBuilder(builder, properties,
			strategies.routeMatcher());
}
 
Example #11
Source File: BrokerClient.java    From spring-cloud-rsocket with Apache License 2.0 5 votes vote down vote up
public Consumer<RSocketRequester.MetadataSpec<?>> forwarding(
		Consumer<Forwarding.Builder> builderConsumer) {
	return spec -> {
		Forwarding.Builder builder = Forwarding.of(properties.getRouteId());
		builderConsumer.accept(builder);
		spec.metadata(builder.build(), Forwarding.FORWARDING_MIME_TYPE);
	};
}
 
Example #12
Source File: BrokerActuatorIntegrationTests.java    From spring-cloud-rsocket with Apache License 2.0 5 votes vote down vote up
private RSocketRequester getRequester(long brokerId) {
	RouteSetup routeSetup = RouteSetup.of(brokerId, "gateway")
			.with("proxy", Boolean.FALSE.toString()).build();
	// mimic rsocket client autoconfig
	return requesterBuilder
			.setupMetadata(routeSetup, RouteSetup.ROUTE_SETUP_MIME_TYPE)
			.rsocketFactory(rsocketFactory -> rsocketFactory
					.acceptor(messageHandler.responder()))
			.connectTcp("localhost", port).block();
}
 
Example #13
Source File: BrokerActuatorIntegrationTests.java    From spring-cloud-rsocket with Apache License 2.0 5 votes vote down vote up
private <T, D> Mono<T> callActuator(RSocketRequester requester, long brokerId,
		Class<T> type, D data, String path) {

	Forwarding forwarding = Forwarding.of(brokerId).serviceName("gateway")
			.disableProxy().build();

	return requester.route(path).metadata(forwarding, Forwarding.FORWARDING_MIME_TYPE)
			.data(data).retrieveMono(type);
}
 
Example #14
Source File: RSocketClientDeniedConnectionToSecuredServerITest.java    From spring-rsocket-demo with GNU General Public License v3.0 5 votes vote down vote up
@BeforeAll
public static void setupOnce(@Autowired RSocketRequester.Builder builder,
                             @LocalRSocketServerPort Integer port,
                             @Autowired RSocketStrategies strategies) {

    mimeType = MimeTypeUtils.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_AUTHENTICATION.getString());
    reqbuilder = builder;
    theport = port;

    // *******  The user 'fake' is NOT in the user list! **********
    credentials = new UsernamePasswordMetadata("fake", "pass");


}
 
Example #15
Source File: RSocketController.java    From spring-rsocket-demo with GNU General Public License v3.0 5 votes vote down vote up
@ConnectMapping("shell-client")
void connectShellClientAndAskForTelemetry(RSocketRequester requester,
                                          @Payload String client) {

    requester.rsocket()
            .onClose()
            .doFirst(() -> {
                // Add all new clients to a client list
                log.info("Client: {} CONNECTED.", client);
                CLIENTS.add(requester);
            })
            .doOnError(error -> {
                // Warn when channels are closed by clients
                log.warn("Channel to client {} CLOSED", client);
            })
            .doFinally(consumer -> {
                // Remove disconnected clients from the client list
                CLIENTS.remove(requester);
                log.info("Client {} DISCONNECTED", client);
            })
            .subscribe();

    // Callback to client, confirming connection
    requester.route("client-status")
            .data("OPEN")
            .retrieveFlux(String.class)
            .doOnNext(s -> log.info("Client: {} Free Memory: {}.", client, s))
            .subscribe();
}
 
Example #16
Source File: RSocketServerToClientITest.java    From spring-rsocket-demo with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Test method. When a client connects to this server, ask the client for its telemetry data
 * and test that the telemetry received is within a good range.
 *
 * @param requester
 * @param client
 */
@ConnectMapping("shell-client")
void verifyConnectShellClientAndAskForTelemetry(RSocketRequester requester, @Payload String client) {

    // test the client's message payload contains the expected client ID
    assertThat(client).isNotNull();
    assertThat(client).isNotEmpty();
    assertThat(client).isEqualTo(clientId);
    log.info("************** CONNECTION - Client ID: {}", client);

    runTest(() -> {
        Flux<String> flux = requester
                .route("client-status") // Test the 'client-status' message handler mapping
                .data("OPEN") // confirm to the client th connection is open
                .retrieveFlux(String.class); // ask the client for its telemetry

        StepVerifier.create(flux)
                .consumeNextWith(s -> {
                    // assert the memory reading is in the 'good' range
                    assertThat(s).isNotNull();
                    assertThat(s).isNotEmpty();
                    assertThat(Integer.valueOf(s)).isPositive();
                    assertThat(Integer.valueOf(s)).isGreaterThan(0);
                })
                .thenCancel()
                .verify(Duration.ofSeconds(10));
    });
}
 
Example #17
Source File: RSocketServerToClientITest.java    From spring-rsocket-demo with GNU General Public License v3.0 5 votes vote down vote up
/**
 * This private method is used to establish a connection to our fake RSocket server.
 * It also controls the state of our test controller. This method is reusable by many tests.
 *
 * @param connectionRoute
 */
private void connectAndRunTest(String connectionRoute) {

    ServerController controller = context.getBean(ServerController.class);
    RSocketStrategies strategies = context.getBean(RSocketStrategies.class);
    RSocketRequester requester = null;

    try {
        controller.reset();

        // Add our ClientHandler as a responder
        SocketAcceptor responder = RSocketMessageHandler.responder(strategies, new ClientHandler());

        // Create an RSocket requester that includes our responder
        requester = RSocketRequester.builder()
                .setupRoute(connectionRoute)
                .setupData(clientId)
                .rsocketStrategies(strategies)
                .rsocketConnector(connector -> connector.acceptor(responder))
                .connectTcp("localhost", server.address().getPort())
                .block();

        // Give the test time to run, wait for the server's call.
        controller.await(Duration.ofSeconds(10));
    } finally {
        if (requester != null) {
            requester.rsocket().dispose();
        }
    }
}
 
Example #18
Source File: ServiceConsumeConfiguration.java    From alibaba-rsocket-broker with Apache License 2.0 5 votes vote down vote up
@Bean
public RSocketRequester rsocketRequester(UpstreamManager upstreamManager) {
    LoadBalancedRSocket loadBalancedRSocket = upstreamManager.findBroker().getLoadBalancedRSocket();
    RSocketStrategies rSocketStrategies = RSocketStrategies.builder()
            .encoder(new HessianEncoder())
            .decoder(new HessianDecoder())
            .build();
    return RSocketRequester.wrap(loadBalancedRSocket,
            MimeType.valueOf("application/x-hessian"),
            MimeType.valueOf("message/x.rsocket.composite-metadata.v0"),
            rSocketStrategies);
}
 
Example #19
Source File: ClientRSocketRequesterBuilder.java    From spring-cloud-rsocket with Apache License 2.0 4 votes vote down vote up
@Override
public Mono<RSocketRequester> connectWebSocket(URI uri) {
	return connect(WebsocketClientTransport.create(uri));
}
 
Example #20
Source File: ClientRSocketRequesterBuilder.java    From spring-cloud-rsocket with Apache License 2.0 4 votes vote down vote up
@Override
public RSocketRequester.Builder rsocketFactory(
		ClientRSocketFactoryConfigurer configurer) {
	return delegate.rsocketFactory(configurer);
}
 
Example #21
Source File: ClientRSocketRequesterBuilder.java    From spring-cloud-rsocket with Apache License 2.0 4 votes vote down vote up
@Override
public Mono<RSocketRequester> connectTcp(String host, int port) {
	return connect(TcpClientTransport.create(host, port));
}
 
Example #22
Source File: ClientRSocketRequesterBuilder.java    From spring-cloud-rsocket with Apache License 2.0 4 votes vote down vote up
@Override
public Mono<RSocketRequester> connect(ClientTransport transport) {
	return delegate.connect(transport)
			.map(requester -> new ClientRSocketRequester(requester, properties,
					routeMatcher));
}
 
Example #23
Source File: ClientRSocketRequesterBuilder.java    From spring-cloud-rsocket with Apache License 2.0 4 votes vote down vote up
@Override
public RSocketRequester.Builder apply(Consumer<RSocketRequester.Builder> configurer) {
	return delegate.apply(configurer);
}
 
Example #24
Source File: BrokerClient.java    From spring-cloud-rsocket with Apache License 2.0 4 votes vote down vote up
public BrokerClient(ClientProperties properties, RSocketRequester.Builder builder) {
	this.properties = properties;
	this.builder = builder;
}
 
Example #25
Source File: BrokerClientConnectionListener.java    From spring-cloud-rsocket with Apache License 2.0 4 votes vote down vote up
@Override
public ResolvableType getResolvableType() {
	return ResolvableType.forClassWithGenerics(getClass(),
			ResolvableType.forClass(RSocketRequester.class));
}
 
Example #26
Source File: BrokerClient.java    From spring-cloud-rsocket with Apache License 2.0 4 votes vote down vote up
public RSocketRequester.Builder getRSocketRequesterBuilder() {
	return this.builder;
}
 
Example #27
Source File: BrokerClient.java    From spring-cloud-rsocket with Apache License 2.0 4 votes vote down vote up
public Mono<RSocketRequester> connect() {
	return connect(builder);
}
 
Example #28
Source File: RsocketClientApplication.java    From bootiful-reactive-microservices with Apache License 2.0 4 votes vote down vote up
GreetingsClientRestController(RSocketRequester requester) {
	this.requester = requester;
}
 
Example #29
Source File: RsocketClientApplication.java    From bootiful-reactive-microservices with Apache License 2.0 4 votes vote down vote up
@Bean
RSocketRequester requester(RSocketStrategies rSocketStrategies) {
	return RSocketRequester
		.create(this.rSocket(), MimeTypeUtils.APPLICATION_JSON, rSocketStrategies);
}
 
Example #30
Source File: ClientConfiguration.java    From tutorials with MIT License 4 votes vote down vote up
@Bean
RSocketRequester rSocketRequester(RSocketStrategies rSocketStrategies) {
    return RSocketRequester.wrap(rSocket(), MimeTypeUtils.APPLICATION_JSON, MimeTypeUtils.APPLICATION_JSON, rSocketStrategies);
}