Search in sources :

Example 1 with RSocketCompositeMetadata

use of com.alibaba.rsocket.metadata.RSocketCompositeMetadata in project alibaba-broker-example-parent by linux-china.

the class UserServiceRSocketTest method testFindById.

@Test
public void testFindById() throws Exception {
    RSocketCompositeMetadata compositeMetadata = new RSocketCompositeMetadata();
    GSVRoutingMetadata routingMetadata = new GSVRoutingMetadata("", "com.alibaba.user.UserService2", "findById", "");
    compositeMetadata.addMetadata(routingMetadata);
    MessageMimeTypeMetadata dataEncodingMetadata = new MessageMimeTypeMetadata(WellKnownMimeType.APPLICATION_JSON);
    compositeMetadata.addMetadata(dataEncodingMetadata);
    rsocket.requestResponse(DefaultPayload.create(Unpooled.wrappedBuffer(objectMapper.writeValueAsBytes(1)), compositeMetadata.getContent())).doOnTerminate(() -> {
        ReferenceCountUtil.safeRelease(compositeMetadata);
    }).subscribe(payload -> {
        System.out.println(payload.getDataUtf8());
    });
    Thread.sleep(1000);
}
Also used : RSocketCompositeMetadata(com.alibaba.rsocket.metadata.RSocketCompositeMetadata) GSVRoutingMetadata(com.alibaba.rsocket.metadata.GSVRoutingMetadata) MessageMimeTypeMetadata(com.alibaba.rsocket.metadata.MessageMimeTypeMetadata)

Example 2 with RSocketCompositeMetadata

use of com.alibaba.rsocket.metadata.RSocketCompositeMetadata in project alibaba-rsocket-broker by alibaba.

the class UpstreamForwardRSocket method requestChannel.

public Flux<Payload> requestChannel(Payload signal, Publisher<Payload> payloads) {
    BinaryRoutingMetadata binaryRoutingMetadata = binaryRoutingMetadata(signal.metadata());
    GSVRoutingMetadata gsvRoutingMetadata;
    if (binaryRoutingMetadata != null) {
        gsvRoutingMetadata = GSVRoutingMetadata.from(new String(binaryRoutingMetadata.getRoutingText(), StandardCharsets.UTF_8));
    } else {
        RSocketCompositeMetadata compositeMetadata = RSocketCompositeMetadata.from(signal.metadata());
        gsvRoutingMetadata = compositeMetadata.getRoutingMetaData();
        if (gsvRoutingMetadata == null) {
            return Flux.error(new InvalidException(RsocketErrorCode.message("RST-600404")));
        }
    }
    Mono<RSocket> destination = findDestination(gsvRoutingMetadata);
    return destination.flatMapMany(rsocket -> {
        metrics(gsvRoutingMetadata, "0x07");
        return rsocket.requestChannel(payloads);
    });
}
Also used : RSocketCompositeMetadata(com.alibaba.rsocket.metadata.RSocketCompositeMetadata) GSVRoutingMetadata(com.alibaba.rsocket.metadata.GSVRoutingMetadata) BinaryRoutingMetadata(com.alibaba.rsocket.metadata.BinaryRoutingMetadata) InvalidException(io.rsocket.exceptions.InvalidException) RSocket(io.rsocket.RSocket) AbstractRSocket(com.alibaba.rsocket.AbstractRSocket)

Example 3 with RSocketCompositeMetadata

use of com.alibaba.rsocket.metadata.RSocketCompositeMetadata in project alibaba-rsocket-broker by alibaba.

the class UpstreamForwardRSocket method requestStream.

@Override
@NotNull
public Flux<Payload> requestStream(@NotNull Payload payload) {
    BinaryRoutingMetadata binaryRoutingMetadata = binaryRoutingMetadata(payload.metadata());
    GSVRoutingMetadata gsvRoutingMetadata;
    if (binaryRoutingMetadata != null) {
        gsvRoutingMetadata = GSVRoutingMetadata.from(new String(binaryRoutingMetadata.getRoutingText(), StandardCharsets.UTF_8));
    } else {
        RSocketCompositeMetadata compositeMetadata = RSocketCompositeMetadata.from(payload.metadata());
        gsvRoutingMetadata = compositeMetadata.getRoutingMetaData();
        if (gsvRoutingMetadata == null) {
            return Flux.error(new InvalidException(RsocketErrorCode.message("RST-600404")));
        }
    }
    Mono<RSocket> destination = findDestination(gsvRoutingMetadata);
    if (this.filterChain.isFiltersPresent()) {
        RSocketExchange requestContext = new RSocketExchange(FrameType.REQUEST_STREAM, gsvRoutingMetadata, payload, this.upstreamBrokerMetadata);
        destination = filterChain.filter(requestContext).then(destination);
    }
    return destination.flatMapMany(rsocket -> {
        metrics(gsvRoutingMetadata, "0x06");
        return rsocket.requestStream(payload);
    });
}
Also used : RSocketCompositeMetadata(com.alibaba.rsocket.metadata.RSocketCompositeMetadata) RSocketExchange(com.alibaba.rsocket.RSocketExchange) GSVRoutingMetadata(com.alibaba.rsocket.metadata.GSVRoutingMetadata) BinaryRoutingMetadata(com.alibaba.rsocket.metadata.BinaryRoutingMetadata) InvalidException(io.rsocket.exceptions.InvalidException) RSocket(io.rsocket.RSocket) AbstractRSocket(com.alibaba.rsocket.AbstractRSocket) NotNull(org.jetbrains.annotations.NotNull)

Example 4 with RSocketCompositeMetadata

use of com.alibaba.rsocket.metadata.RSocketCompositeMetadata in project alibaba-rsocket-broker by alibaba.

the class RSocketRequesterRpcProxy method invoke.

@Override
@RuntimeType
public Object invoke(@This Object proxy, @Origin Method method, @AllArguments Object[] allArguments) throws Throwable {
    // interface default method validation for JDK Proxy only, not necessary for ByteBuddy
    if (jdkProxy && method.isDefault()) {
        return DefaultMethodHandler.getMethodHandle(method, serviceInterface).bindTo(proxy).invokeWithArguments(allArguments);
    } else if (method.getDeclaringClass().equals(Object.class)) {
        // delegate hashCode, equals, or toString methods to this
        return method.invoke(this);
    }
    MutableContext mutableContext = new MutableContext();
    if (!methodMetadataMap.containsKey(method)) {
        methodMetadataMap.put(method, new ReactiveMethodMetadata(group, service, version, method, encodingType, this.acceptEncodingTypes, endpoint, sticky, sourceUri));
    }
    ReactiveMethodMetadata methodMetadata = methodMetadataMap.get(method);
    mutableContext.put(ReactiveMethodMetadata.class, methodMetadata);
    Object[] args = allArguments;
    if (methodMetadata.isKotlinSuspend()) {
        args = Arrays.copyOfRange(args, 0, args.length - 1);
        mutableContext.put(Continuation.class, allArguments[allArguments.length - 1]);
    }
    // ----- return type deal------
    if (methodMetadata.getRsocketFrameType() == FrameType.REQUEST_CHANNEL) {
        metrics(methodMetadata);
        Payload routePayload;
        Flux<Object> source;
        // 1 param or 2 params
        if (args.length == 1) {
            routePayload = ByteBufPayload.create(Unpooled.EMPTY_BUFFER, methodMetadata.getCompositeMetadataByteBuf().retainedDuplicate());
            source = methodMetadata.getReactiveAdapter().toFlux(args[0]);
        } else {
            ByteBuf bodyBuffer = encodingFacade.encodingResult(args[0], methodMetadata.getParamEncoding());
            routePayload = ByteBufPayload.create(bodyBuffer, methodMetadata.getCompositeMetadataByteBuf().retainedDuplicate());
            source = methodMetadata.getReactiveAdapter().toFlux(args[1]);
        }
        Flux<Payload> payloadFlux = source.startWith(routePayload).map(obj -> {
            if (obj instanceof Payload)
                return (Payload) obj;
            return ByteBufPayload.create(encodingFacade.encodingResult(obj, encodingType), methodMetadata.getCompositeMetadataByteBuf().retainedDuplicate());
        });
        Flux<Payload> payloads = upstreamManager.getRSocket(this.serviceId).requestChannel(payloadFlux);
        Flux<Object> fluxReturn = payloads.concatMap(payload -> {
            try {
                RSocketCompositeMetadata compositeMetadata = RSocketCompositeMetadata.from(payload.metadata());
                return Mono.justOrEmpty(encodingFacade.decodeResult(extractPayloadDataMimeType(compositeMetadata, encodingType), payload.data(), methodMetadata.getInferredClassForReturn()));
            } catch (Exception e) {
                return Flux.error(e);
            }
        }).subscriberContext(mutableContext::putAll);
        if (methodMetadata.isMonoChannel()) {
            return fluxReturn.last();
        } else {
            return methodMetadata.getReactiveAdapter().fromPublisher(fluxReturn, method.getReturnType());
        }
    } else {
        // body content
        ByteBuf bodyBuffer = encodingFacade.encodingParams(args, methodMetadata.getParamEncoding());
        Class<?> returnType = method.getReturnType();
        if (methodMetadata.getRsocketFrameType() == FrameType.REQUEST_RESPONSE) {
            metrics(methodMetadata);
            Mono<Payload> payloadMono = remoteRequestResponse(methodMetadata, methodMetadata.getCompositeMetadataByteBuf().retainedDuplicate(), bodyBuffer);
            Mono<Object> result = payloadMono.handle((payload, sink) -> {
                try {
                    RSocketCompositeMetadata compositeMetadata = RSocketCompositeMetadata.from(payload.metadata());
                    Object obj = encodingFacade.decodeResult(extractPayloadDataMimeType(compositeMetadata, encodingType), payload.data(), methodMetadata.getInferredClassForReturn());
                    if (obj != null) {
                        sink.next(obj);
                    }
                    sink.complete();
                } catch (Exception e) {
                    sink.error(e);
                }
            });
            return methodMetadata.getReactiveAdapter().fromPublisher(result, returnType, mutableContext);
        } else if (methodMetadata.getRsocketFrameType() == FrameType.REQUEST_FNF) {
            metrics(methodMetadata);
            return remoteFireAndForget(methodMetadata, methodMetadata.getCompositeMetadataByteBuf().retainedDuplicate(), bodyBuffer);
        } else if (methodMetadata.getRsocketFrameType() == FrameType.REQUEST_STREAM) {
            metrics(methodMetadata);
            Flux<Payload> flux = remoteRequestStream(methodMetadata, methodMetadata.getCompositeMetadataByteBuf().retainedDuplicate(), bodyBuffer);
            Flux<Object> result = flux.concatMap((payload) -> {
                try {
                    RSocketCompositeMetadata compositeMetadata = RSocketCompositeMetadata.from(payload.metadata());
                    return Mono.justOrEmpty(encodingFacade.decodeResult(extractPayloadDataMimeType(compositeMetadata, encodingType), payload.data(), methodMetadata.getInferredClassForReturn()));
                } catch (Exception e) {
                    return Mono.error(e);
                }
            });
            return methodMetadata.getReactiveAdapter().fromPublisher(result, returnType, mutableContext);
        } else {
            ReferenceCountUtil.safeRelease(bodyBuffer);
            return Mono.error(new Exception(RsocketErrorCode.message("RST-200405", methodMetadata.getRsocketFrameType())));
        }
    }
}
Also used : This(net.bytebuddy.implementation.bind.annotation.This) Continuation(kotlin.coroutines.Continuation) Arrays(java.util.Arrays) Origin(net.bytebuddy.implementation.bind.annotation.Origin) LoggerFactory(org.slf4j.LoggerFactory) TimeoutException(java.util.concurrent.TimeoutException) Metrics(io.micrometer.core.instrument.Metrics) Unpooled(io.netty.buffer.Unpooled) RuntimeType(net.bytebuddy.implementation.bind.annotation.RuntimeType) MessageMimeTypeMetadata(com.alibaba.rsocket.metadata.MessageMimeTypeMetadata) ByteBuf(io.netty.buffer.ByteBuf) AllArguments(net.bytebuddy.implementation.bind.annotation.AllArguments) MutableContext(com.alibaba.rsocket.MutableContext) Duration(java.time.Duration) Map(java.util.Map) URI(java.net.URI) Method(java.lang.reflect.Method) RSocketEncodingFacade(com.alibaba.rsocket.encoding.RSocketEncodingFacade) ByteBufPayload(io.rsocket.util.ByteBufPayload) RSocketMimeType(com.alibaba.rsocket.metadata.RSocketMimeType) FrameType(io.rsocket.frame.FrameType) Logger(org.slf4j.Logger) RsocketErrorCode(com.alibaba.rsocket.observability.RsocketErrorCode) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Mono(reactor.core.publisher.Mono) RSocketCompositeMetadata(com.alibaba.rsocket.metadata.RSocketCompositeMetadata) Nullable(org.jetbrains.annotations.Nullable) Flux(reactor.core.publisher.Flux) Payload(io.rsocket.Payload) ReferenceCountUtil(io.netty.util.ReferenceCountUtil) UpstreamManager(com.alibaba.rsocket.upstream.UpstreamManager) InvocationHandler(java.lang.reflect.InvocationHandler) NotNull(org.jetbrains.annotations.NotNull) ServiceLocator(com.alibaba.rsocket.ServiceLocator) RSocketCompositeMetadata(com.alibaba.rsocket.metadata.RSocketCompositeMetadata) MutableContext(com.alibaba.rsocket.MutableContext) ByteBuf(io.netty.buffer.ByteBuf) TimeoutException(java.util.concurrent.TimeoutException) ByteBufPayload(io.rsocket.util.ByteBufPayload) Payload(io.rsocket.Payload) RuntimeType(net.bytebuddy.implementation.bind.annotation.RuntimeType)

Example 5 with RSocketCompositeMetadata

use of com.alibaba.rsocket.metadata.RSocketCompositeMetadata in project alibaba-rsocket-broker by alibaba.

the class UserServiceTest method testFindById.

@Test
public void testFindById() throws Exception {
    RSocketCompositeMetadata compositeMetadata = new RSocketCompositeMetadata();
    GSVRoutingMetadata routingMetadata = new GSVRoutingMetadata("", "com.alibaba.user.UserService2", "findById", "");
    compositeMetadata.addMetadata(routingMetadata);
    MessageMimeTypeMetadata dataEncodingMetadata = new MessageMimeTypeMetadata(WellKnownMimeType.APPLICATION_JSON);
    compositeMetadata.addMetadata(dataEncodingMetadata);
    rsocket.requestResponse(DefaultPayload.create(Unpooled.wrappedBuffer(objectMapper.writeValueAsBytes(1)), compositeMetadata.getContent())).doOnTerminate(() -> {
        ReferenceCountUtil.safeRelease(compositeMetadata);
    }).subscribe(payload -> {
        System.out.println(payload.getDataUtf8());
    });
    Thread.sleep(1000);
}
Also used : RSocketCompositeMetadata(com.alibaba.rsocket.metadata.RSocketCompositeMetadata) GSVRoutingMetadata(com.alibaba.rsocket.metadata.GSVRoutingMetadata) MessageMimeTypeMetadata(com.alibaba.rsocket.metadata.MessageMimeTypeMetadata)

Aggregations

RSocketCompositeMetadata (com.alibaba.rsocket.metadata.RSocketCompositeMetadata)16 GSVRoutingMetadata (com.alibaba.rsocket.metadata.GSVRoutingMetadata)13 MessageMimeTypeMetadata (com.alibaba.rsocket.metadata.MessageMimeTypeMetadata)7 ByteBuf (io.netty.buffer.ByteBuf)6 NotNull (org.jetbrains.annotations.NotNull)5 AbstractRSocket (com.alibaba.rsocket.AbstractRSocket)4 BinaryRoutingMetadata (com.alibaba.rsocket.metadata.BinaryRoutingMetadata)4 RSocket (io.rsocket.RSocket)4 InvalidException (io.rsocket.exceptions.InvalidException)4 Nullable (org.jetbrains.annotations.Nullable)4 RSocketExchange (com.alibaba.rsocket.RSocketExchange)3 ServiceLocator (com.alibaba.rsocket.ServiceLocator)3 RSocketMimeType (com.alibaba.rsocket.metadata.RSocketMimeType)3 Unpooled (io.netty.buffer.Unpooled)3 Payload (io.rsocket.Payload)3 ByteBufPayload (io.rsocket.util.ByteBufPayload)3 RsocketErrorCode (com.alibaba.rsocket.observability.RsocketErrorCode)2 RSocketBrokerHandlerRegistry (com.alibaba.spring.boot.rsocket.broker.responder.RSocketBrokerHandlerRegistry)2 RSocketBrokerResponderHandler (com.alibaba.spring.boot.rsocket.broker.responder.RSocketBrokerResponderHandler)2 ServiceRoutingSelector (com.alibaba.spring.boot.rsocket.broker.route.ServiceRoutingSelector)2