Search in sources :

Example 1 with InvokeCallback

use of com.alipay.sofa.jraft.rpc.InvokeCallback in project sofa-jraft by sofastack.

the class DefaultRheaKVRpcService method internalCallAsyncWithRpc.

private <V> void internalCallAsyncWithRpc(final Endpoint endpoint, final BaseRequest request, final FailoverClosure<V> closure) {
    final InvokeContext invokeCtx = new InvokeContext();
    invokeCtx.put(BoltRpcClient.BOLT_CTX, ExtSerializerSupports.getInvokeContext());
    final InvokeCallback invokeCallback = new InvokeCallback() {

        @Override
        public void complete(final Object result, final Throwable err) {
            if (err == null) {
                final BaseResponse<?> response = (BaseResponse<?>) result;
                if (response.isSuccess()) {
                    closure.setData(response.getValue());
                    closure.run(Status.OK());
                } else {
                    closure.setError(response.getError());
                    closure.run(new Status(-1, "RPC failed with address: %s, response: %s", endpoint, response));
                }
            } else {
                closure.failure(err);
            }
        }

        @Override
        public Executor executor() {
            return rpcCallbackExecutor;
        }
    };
    try {
        this.rpcClient.invokeAsync(endpoint, request, invokeCtx, invokeCallback, this.rpcTimeoutMillis);
    } catch (final Throwable t) {
        closure.failure(t);
    }
}
Also used : Status(com.alipay.sofa.jraft.Status) BaseResponse(com.alipay.sofa.jraft.rhea.cmd.store.BaseResponse) InvokeContext(com.alipay.sofa.jraft.rpc.InvokeContext) InvokeCallback(com.alipay.sofa.jraft.rpc.InvokeCallback)

Example 2 with InvokeCallback

use of com.alipay.sofa.jraft.rpc.InvokeCallback in project sofa-jraft by sofastack.

the class HeartbeatSender method callAsyncWithRpc.

private <V> void callAsyncWithRpc(final Endpoint endpoint, final BaseRequest request, final HeartbeatClosure<V> closure) {
    final com.alipay.sofa.jraft.rpc.InvokeContext invokeCtx = new com.alipay.sofa.jraft.rpc.InvokeContext();
    invokeCtx.put(BoltRpcClient.BOLT_CTX, ExtSerializerSupports.getInvokeContext());
    final InvokeCallback invokeCallback = new InvokeCallback() {

        @SuppressWarnings("unchecked")
        @Override
        public void complete(final Object result, final Throwable err) {
            if (err == null) {
                final BaseResponse<?> response = (BaseResponse<?>) result;
                if (response.isSuccess()) {
                    closure.setResult((V) response.getValue());
                    closure.run(Status.OK());
                } else {
                    closure.setError(response.getError());
                    closure.run(new Status(-1, "RPC failed with address: %s, response: %s", endpoint, response));
                }
            } else {
                closure.run(new Status(-1, err.getMessage()));
            }
        }

        @Override
        public Executor executor() {
            return heartbeatRpcCallbackExecutor;
        }
    };
    try {
        this.rpcClient.invokeAsync(endpoint, request, invokeCtx, invokeCallback, this.heartbeatRpcTimeoutMillis);
    } catch (final Throwable t) {
        closure.run(new Status(-1, t.getMessage()));
    }
}
Also used : Status(com.alipay.sofa.jraft.Status) InvokeCallback(com.alipay.sofa.jraft.rpc.InvokeCallback) BaseResponse(com.alipay.sofa.jraft.rhea.cmd.pd.BaseResponse)

Example 3 with InvokeCallback

use of com.alipay.sofa.jraft.rpc.InvokeCallback in project sofa-jraft by sofastack.

the class CounterClient method incrementAndGet.

private static void incrementAndGet(final CliClientServiceImpl cliClientService, final PeerId leader, final long delta, CountDownLatch latch) throws RemotingException, InterruptedException {
    IncrementAndGetRequest request = IncrementAndGetRequest.newBuilder().setDelta(delta).build();
    cliClientService.getRpcClient().invokeAsync(leader.getEndpoint(), request, new InvokeCallback() {

        @Override
        public void complete(Object result, Throwable err) {
            if (err == null) {
                latch.countDown();
                System.out.println("incrementAndGet result:" + result);
            } else {
                err.printStackTrace();
                latch.countDown();
            }
        }

        @Override
        public Executor executor() {
            return null;
        }
    }, 5000);
}
Also used : InvokeCallback(com.alipay.sofa.jraft.rpc.InvokeCallback) Executor(java.util.concurrent.Executor) IncrementAndGetRequest(com.alipay.sofa.jraft.example.counter.rpc.CounterOutter.IncrementAndGetRequest)

Example 4 with InvokeCallback

use of com.alipay.sofa.jraft.rpc.InvokeCallback in project sofa-jraft by sofastack.

the class AbstractClientService method invokeWithDone.

public <T extends Message> Future<Message> invokeWithDone(final Endpoint endpoint, final Message request, final InvokeContext ctx, final RpcResponseClosure<T> done, final int timeoutMs, final Executor rpcExecutor) {
    final RpcClient rc = this.rpcClient;
    final FutureImpl<Message> future = new FutureImpl<>();
    final Executor currExecutor = rpcExecutor != null ? rpcExecutor : this.rpcExecutor;
    try {
        if (rc == null) {
            future.failure(new IllegalStateException("Client service is uninitialized."));
            // should be in another thread to avoid dead locking.
            RpcUtils.runClosureInExecutor(currExecutor, done, new Status(RaftError.EINTERNAL, "Client service is uninitialized."));
            return future;
        }
        rc.invokeAsync(endpoint, request, ctx, new InvokeCallback() {

            @SuppressWarnings({ "unchecked", "ConstantConditions" })
            @Override
            public void complete(final Object result, final Throwable err) {
                if (future.isCancelled()) {
                    onCanceled(request, done);
                    return;
                }
                if (err == null) {
                    Status status = Status.OK();
                    Message msg;
                    if (result instanceof ErrorResponse) {
                        status = handleErrorResponse((ErrorResponse) result);
                        msg = (Message) result;
                    } else if (result instanceof Message) {
                        final Descriptors.FieldDescriptor fd = // 
                        ((Message) result).getDescriptorForType().findFieldByNumber(RpcResponseFactory.ERROR_RESPONSE_NUM);
                        if (fd != null && ((Message) result).hasField(fd)) {
                            final ErrorResponse eResp = (ErrorResponse) ((Message) result).getField(fd);
                            status = handleErrorResponse(eResp);
                            msg = eResp;
                        } else {
                            msg = (T) result;
                        }
                    } else {
                        msg = (T) result;
                    }
                    if (done != null) {
                        try {
                            if (status.isOk()) {
                                done.setResponse((T) msg);
                            }
                            done.run(status);
                        } catch (final Throwable t) {
                            LOG.error("Fail to run RpcResponseClosure, the request is {}.", request, t);
                        }
                    }
                    if (!future.isDone()) {
                        future.setResult(msg);
                    }
                } else {
                    if (done != null) {
                        try {
                            done.run(new Status(err instanceof InvokeTimeoutException ? RaftError.ETIMEDOUT : RaftError.EINTERNAL, "RPC exception:" + err.getMessage()));
                        } catch (final Throwable t) {
                            LOG.error("Fail to run RpcResponseClosure, the request is {}.", request, t);
                        }
                    }
                    if (!future.isDone()) {
                        future.failure(err);
                    }
                }
            }

            @Override
            public Executor executor() {
                return currExecutor;
            }
        }, timeoutMs <= 0 ? this.rpcOptions.getRpcDefaultTimeout() : timeoutMs);
    } catch (final InterruptedException e) {
        Thread.currentThread().interrupt();
        future.failure(e);
        // should be in another thread to avoid dead locking.
        RpcUtils.runClosureInExecutor(currExecutor, done, new Status(RaftError.EINTR, "Sending rpc was interrupted"));
    } catch (final RemotingException e) {
        future.failure(e);
        // should be in another thread to avoid dead locking.
        RpcUtils.runClosureInExecutor(currExecutor, done, new Status(RaftError.EINTERNAL, "Fail to send a RPC request:" + e.getMessage()));
    }
    return future;
}
Also used : Status(com.alipay.sofa.jraft.Status) InvokeCallback(com.alipay.sofa.jraft.rpc.InvokeCallback) InvokeTimeoutException(com.alipay.sofa.jraft.error.InvokeTimeoutException) Message(com.google.protobuf.Message) ErrorResponse(com.alipay.sofa.jraft.rpc.RpcRequests.ErrorResponse) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) Executor(java.util.concurrent.Executor) RemotingException(com.alipay.sofa.jraft.error.RemotingException) Descriptors(com.google.protobuf.Descriptors) RpcClient(com.alipay.sofa.jraft.rpc.RpcClient)

Example 5 with InvokeCallback

use of com.alipay.sofa.jraft.rpc.InvokeCallback in project nacos by alibaba.

the class JRaftServer method invokeToLeader.

private void invokeToLeader(final String group, final Message request, final int timeoutMillis, FailoverClosure closure) {
    try {
        final Endpoint leaderIp = Optional.ofNullable(getLeader(group)).orElseThrow(() -> new NoLeaderException(group)).getEndpoint();
        cliClientService.getRpcClient().invokeAsync(leaderIp, request, new InvokeCallback() {

            @Override
            public void complete(Object o, Throwable ex) {
                if (Objects.nonNull(ex)) {
                    closure.setThrowable(ex);
                    closure.run(new Status(RaftError.UNKNOWN, ex.getMessage()));
                    return;
                }
                if (!((Response) o).getSuccess()) {
                    closure.setThrowable(new IllegalStateException(((Response) o).getErrMsg()));
                    closure.run(new Status(RaftError.UNKNOWN, ((Response) o).getErrMsg()));
                    return;
                }
                closure.setResponse((Response) o);
                closure.run(Status.OK());
            }

            @Override
            public Executor executor() {
                return RaftExecutor.getRaftCliServiceExecutor();
            }
        }, timeoutMillis);
    } catch (Exception e) {
        closure.setThrowable(e);
        closure.run(new Status(RaftError.UNKNOWN, e.toString()));
    }
}
Also used : Status(com.alipay.sofa.jraft.Status) Response(com.alibaba.nacos.consistency.entity.Response) InvokeCallback(com.alipay.sofa.jraft.rpc.InvokeCallback) Executor(java.util.concurrent.Executor) RaftExecutor(com.alibaba.nacos.core.distributed.raft.utils.RaftExecutor) Endpoint(com.alipay.sofa.jraft.util.Endpoint) NoLeaderException(com.alibaba.nacos.core.distributed.raft.exception.NoLeaderException) JRaftException(com.alibaba.nacos.core.distributed.raft.exception.JRaftException) ConsistencyException(com.alibaba.nacos.consistency.exception.ConsistencyException) DuplicateRaftGroupException(com.alibaba.nacos.core.distributed.raft.exception.DuplicateRaftGroupException) NoLeaderException(com.alibaba.nacos.core.distributed.raft.exception.NoLeaderException) NoSuchRaftGroupException(com.alibaba.nacos.core.distributed.raft.exception.NoSuchRaftGroupException)

Aggregations

InvokeCallback (com.alipay.sofa.jraft.rpc.InvokeCallback)7 Status (com.alipay.sofa.jraft.Status)5 Executor (java.util.concurrent.Executor)4 BaseResponse (com.alipay.sofa.jraft.rhea.cmd.pd.BaseResponse)2 InvokeContext (com.alipay.sofa.jraft.rpc.InvokeContext)2 Endpoint (com.alipay.sofa.jraft.util.Endpoint)2 Response (com.alibaba.nacos.consistency.entity.Response)1 ConsistencyException (com.alibaba.nacos.consistency.exception.ConsistencyException)1 DuplicateRaftGroupException (com.alibaba.nacos.core.distributed.raft.exception.DuplicateRaftGroupException)1 JRaftException (com.alibaba.nacos.core.distributed.raft.exception.JRaftException)1 NoLeaderException (com.alibaba.nacos.core.distributed.raft.exception.NoLeaderException)1 NoSuchRaftGroupException (com.alibaba.nacos.core.distributed.raft.exception.NoSuchRaftGroupException)1 RaftExecutor (com.alibaba.nacos.core.distributed.raft.utils.RaftExecutor)1 InvokeTimeoutException (com.alipay.sofa.jraft.error.InvokeTimeoutException)1 RemotingException (com.alipay.sofa.jraft.error.RemotingException)1 IncrementAndGetRequest (com.alipay.sofa.jraft.example.counter.rpc.CounterOutter.IncrementAndGetRequest)1 BaseResponse (com.alipay.sofa.jraft.rhea.cmd.store.BaseResponse)1 RpcClient (com.alipay.sofa.jraft.rpc.RpcClient)1 ErrorResponse (com.alipay.sofa.jraft.rpc.RpcRequests.ErrorResponse)1 Descriptors (com.google.protobuf.Descriptors)1