use of io.netty.util.Timeout in project web3sdk by FISCO-BCOS.
the class Service method asyncSendChannelMessage.
public void asyncSendChannelMessage(ChannelRequest request, ChannelResponseCallback callback) {
try {
logger.debug("处理链上链下请求: " + request.getMessageID());
callback.setService(this);
ChannelMessage channelMessage = new ChannelMessage();
channelMessage.setSeq(request.getMessageID());
channelMessage.setResult(0);
// 链上链下请求0x20
channelMessage.setType((short) 0x20);
channelMessage.setData(request.getContent().getBytes());
try {
List<ConnectionInfo> fromConnectionInfos = new ArrayList<ConnectionInfo>();
List<ConnectionInfo> toConnectionInfos = new ArrayList<ConnectionInfo>();
// 设置发送节点
ChannelConnections fromChannelConnections = allChannelConnections.get(orgID);
if (fromChannelConnections == null) {
// 没有找到对应的链
// 返回错误
logger.error("没有找到本机构:{}", request.getFromOrg());
throw new Exception("未找到本机构");
}
fromConnectionInfos.addAll(fromChannelConnections.getConnections());
logger.debug("发送结构:{} 节点数:{}", request.getFromOrg(), fromChannelConnections.getConnections().size());
callback.setFromChannelConnections(fromChannelConnections);
callback.setFromConnectionInfos(fromConnectionInfos);
// 设置目的节点
ChannelConnections toChannelConnections = allChannelConnections.get(request.getToOrg());
if (toChannelConnections == null) {
logger.error("未找到目的机构: {}", request.getToOrg());
throw new Exception("未找到目标机构");
}
toConnectionInfos.addAll(toChannelConnections.getConnections());
logger.debug("机构:{} 节点数:{}", request.getToOrg(), toChannelConnections.getConnections().size());
callback.setToConnectionInfos(toConnectionInfos);
// 设置消息内容
callback.setRequest(channelMessage);
seq2Callback.put(request.getMessageID(), callback);
if (request.getTimeout() > 0) {
final ChannelResponseCallback callbackInner = callback;
callback.setTimeout(timeoutHandler.newTimeout(new TimerTask() {
ChannelResponseCallback _callback = callbackInner;
@Override
public void run(Timeout timeout) throws Exception {
// 处理超时逻辑
_callback.onTimeout();
}
}, request.getTimeout(), TimeUnit.MILLISECONDS));
}
callback.retrySendMessage(0);
} catch (Exception e) {
logger.error("发送消息异常 消息未发出", e);
ChannelResponse response = new ChannelResponse();
response.setErrorCode(100);
response.setMessageID(request.getMessageID());
response.setErrorMessage(e.getMessage());
response.setContent("");
callback.onResponse(response);
return;
}
} catch (Exception e) {
logger.error("系统错误", e);
}
}
use of io.netty.util.Timeout in project web3sdk by FISCO-BCOS.
the class Service method asyncSendEthereumMessage.
public void asyncSendEthereumMessage(EthereumRequest request, EthereumResponseCallback callback) {
logger.debug("处理Ethereum请求: " + request.getMessageID());
Boolean sended = false;
EthereumMessage ethereumMessage = new EthereumMessage();
ethereumMessage.setSeq(request.getMessageID());
ethereumMessage.setResult(0);
ethereumMessage.setType((short) 0x12);
ethereumMessage.setData(request.getContent().getBytes());
// 选取发送节点
try {
ChannelConnections fromChannelConnections = allChannelConnections.get(orgID);
if (fromChannelConnections == null) {
// 没有找到对应的链
// 返回错误
logger.error("没有找到本机构:{}", orgID);
throw new Exception("未找到本机构");
}
ChannelHandlerContext ctx = fromChannelConnections.randomNetworkConnection();
ByteBuf out = ctx.alloc().buffer();
ethereumMessage.writeHeader(out);
ethereumMessage.writeExtra(out);
seq2Callback.put(request.getMessageID(), callback);
if (request.getTimeout() > 0) {
// ethereum名字可能会搞混,换成channel
final EthereumResponseCallback callbackInner = callback;
callback.setTimeout(timeoutHandler.newTimeout(new TimerTask() {
EthereumResponseCallback _callback = callbackInner;
@Override
public void run(Timeout timeout) throws Exception {
// 处理超时逻辑
_callback.onTimeout();
}
}, request.getTimeout(), TimeUnit.MILLISECONDS));
}
ctx.writeAndFlush(out);
logger.debug("发送Ethereum消息至 " + ((SocketChannel) ctx.channel()).remoteAddress().getAddress().getHostAddress() + ":" + ((SocketChannel) ctx.channel()).remoteAddress().getPort() + " 成功");
sended = true;
} catch (Exception e) {
logger.error("系统错误", e);
EthereumResponse response = new EthereumResponse();
response.setErrorCode(-1);
response.setErrorMessage("系统错误");
response.setContent("");
response.setMessageID(request.getMessageID());
if (callback.getTimeout() != null) {
callback.getTimeout().cancel();
}
callback.onResponse(response);
}
}
use of io.netty.util.Timeout in project redisson by redisson.
the class CommandAsyncService method async.
protected <V, R> void async(final boolean readOnlyMode, final NodeSource source, final Codec codec, final RedisCommand<V> command, final Object[] params, final RPromise<R> mainPromise, final int attempt) {
if (mainPromise.isCancelled()) {
return;
}
if (!connectionManager.getShutdownLatch().acquire()) {
mainPromise.tryFailure(new RedissonShutdownException("Redisson is shutdown"));
return;
}
final AsyncDetails<V, R> details = AsyncDetails.acquire();
if (isRedissonReferenceSupportEnabled()) {
try {
for (int i = 0; i < params.length; i++) {
RedissonReference reference = redisson != null ? RedissonObjectFactory.toReference(redisson, params[i]) : RedissonObjectFactory.toReference(redissonReactive, params[i]);
params[i] = reference == null ? params[i] : reference;
}
} catch (Exception e) {
connectionManager.getShutdownLatch().release();
mainPromise.tryFailure(e);
return;
}
}
final RFuture<RedisConnection> connectionFuture;
if (readOnlyMode) {
connectionFuture = connectionManager.connectionReadOp(source, command);
} else {
connectionFuture = connectionManager.connectionWriteOp(source, command);
}
final RPromise<R> attemptPromise = connectionManager.newPromise();
details.init(connectionFuture, attemptPromise, readOnlyMode, source, codec, command, params, mainPromise, attempt);
final TimerTask retryTimerTask = new TimerTask() {
@Override
public void run(Timeout t) throws Exception {
if (details.getAttemptPromise().isDone()) {
return;
}
if (details.getConnectionFuture().cancel(false)) {
connectionManager.getShutdownLatch().release();
} else {
if (details.getConnectionFuture().isSuccess()) {
ChannelFuture writeFuture = details.getWriteFuture();
if (writeFuture != null && !writeFuture.cancel(false) && writeFuture.isSuccess()) {
return;
}
}
}
if (details.getMainPromise().isCancelled()) {
if (details.getAttemptPromise().cancel(false)) {
AsyncDetails.release(details);
}
return;
}
if (details.getAttempt() == connectionManager.getConfig().getRetryAttempts()) {
if (details.getException() == null) {
details.setException(new RedisTimeoutException("Command execution timeout for command: " + command + " with params: " + LogHelper.toString(details.getParams())));
}
details.getAttemptPromise().tryFailure(details.getException());
return;
}
if (!details.getAttemptPromise().cancel(false)) {
return;
}
int count = details.getAttempt() + 1;
if (log.isDebugEnabled()) {
log.debug("attempt {} for command {} and params {}", count, details.getCommand(), Arrays.toString(details.getParams()));
}
async(details.isReadOnlyMode(), details.getSource(), details.getCodec(), details.getCommand(), details.getParams(), details.getMainPromise(), count);
AsyncDetails.release(details);
}
};
Timeout timeout = connectionManager.newTimeout(retryTimerTask, connectionManager.getConfig().getRetryInterval(), TimeUnit.MILLISECONDS);
details.setTimeout(timeout);
connectionFuture.addListener(new FutureListener<RedisConnection>() {
@Override
public void operationComplete(Future<RedisConnection> connFuture) throws Exception {
if (connFuture.isCancelled()) {
return;
}
if (!connFuture.isSuccess()) {
connectionManager.getShutdownLatch().release();
details.setException(convertException(connectionFuture));
return;
}
if (details.getAttemptPromise().isDone() || details.getMainPromise().isDone()) {
releaseConnection(source, connectionFuture, details.isReadOnlyMode(), details.getAttemptPromise(), details);
return;
}
final RedisConnection connection = connFuture.getNow();
if (details.getSource().getRedirect() == Redirect.ASK) {
List<CommandData<?, ?>> list = new ArrayList<CommandData<?, ?>>(2);
RPromise<Void> promise = connectionManager.newPromise();
list.add(new CommandData<Void, Void>(promise, details.getCodec(), RedisCommands.ASKING, new Object[] {}));
list.add(new CommandData<V, R>(details.getAttemptPromise(), details.getCodec(), details.getCommand(), details.getParams()));
RPromise<Void> main = connectionManager.newPromise();
ChannelFuture future = connection.send(new CommandsData(main, list));
details.setWriteFuture(future);
} else {
if (log.isDebugEnabled()) {
log.debug("aquired connection for command {} and params {} from slot {} using node {}", details.getCommand(), Arrays.toString(details.getParams()), details.getSource(), connection.getRedisClient().getAddr());
}
ChannelFuture future = connection.send(new CommandData<V, R>(details.getAttemptPromise(), details.getCodec(), details.getCommand(), details.getParams()));
details.setWriteFuture(future);
}
details.getWriteFuture().addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
checkWriteFuture(details, connection);
}
});
releaseConnection(source, connectionFuture, details.isReadOnlyMode(), details.getAttemptPromise(), details);
}
});
attemptPromise.addListener(new FutureListener<R>() {
@Override
public void operationComplete(Future<R> future) throws Exception {
checkAttemptFuture(source, details, future);
}
});
}
use of io.netty.util.Timeout in project redisson by redisson.
the class RedissonBlockingFairQueue method tryPollAsync.
private void tryPollAsync(final long startTime, final long timeout, final TimeUnit unit, final RFuture<RedissonLockEntry> subscribeFuture, final RPromise<V> promise) {
if (promise.isDone()) {
unsubscribe(subscribeFuture);
return;
}
long spentTime = System.currentTimeMillis() - startTime;
long remainTime = unit.toMillis(timeout) - spentTime;
if (remainTime <= 0) {
unsubscribe(subscribeFuture);
promise.trySuccess(null);
return;
}
RFuture<Long> tryAcquireFuture = tryAcquireAsync();
tryAcquireFuture.addListener(new FutureListener<Long>() {
@Override
public void operationComplete(Future<Long> future) throws Exception {
if (!future.isSuccess()) {
unsubscribe(subscribeFuture);
promise.tryFailure(future.cause());
return;
}
Long currentTimeout = future.getNow();
if (currentTimeout == null) {
long spentTime = System.currentTimeMillis() - startTime;
long remainTime = unit.toMillis(timeout) - spentTime;
if (remainTime > 0) {
final RFuture<V> pollFuture = RedissonBlockingFairQueue.super.pollAsync(remainTime, TimeUnit.MILLISECONDS);
pollFuture.addListener(new FutureListener<V>() {
@Override
public void operationComplete(Future<V> future) throws Exception {
unsubscribe(subscribeFuture);
if (!future.isSuccess()) {
promise.tryFailure(future.cause());
return;
}
promise.trySuccess(future.getNow());
}
});
} else {
unsubscribe(subscribeFuture);
promise.trySuccess(null);
}
} else {
final RedissonLockEntry entry = getEntry();
synchronized (entry) {
if (entry.getLatch().tryAcquire()) {
tryPollAsync(startTime, timeout, unit, subscribeFuture, promise);
} else {
final AtomicBoolean executed = new AtomicBoolean();
final AtomicReference<Timeout> futureRef = new AtomicReference<Timeout>();
final Runnable listener = new Runnable() {
@Override
public void run() {
executed.set(true);
if (futureRef.get() != null) {
futureRef.get().cancel();
}
tryPollAsync(startTime, timeout, unit, subscribeFuture, promise);
}
};
entry.addListener(listener);
if (!executed.get()) {
long spentTime = System.currentTimeMillis() - startTime;
long remainTime = unit.toMillis(timeout) - spentTime;
Timeout scheduledFuture = commandExecutor.getConnectionManager().newTimeout(new TimerTask() {
@Override
public void run(Timeout t) throws Exception {
synchronized (entry) {
if (entry.removeListener(listener)) {
tryPollAsync(startTime, timeout, unit, subscribeFuture, promise);
}
}
}
}, remainTime, TimeUnit.MILLISECONDS);
futureRef.set(scheduledFuture);
}
}
}
}
}
;
});
}
use of io.netty.util.Timeout in project redisson by redisson.
the class RedissonSemaphore method tryAcquireAsync.
@Override
public RFuture<Boolean> tryAcquireAsync(final int permits, long waitTime, TimeUnit unit) {
final RPromise<Boolean> result = newPromise();
final AtomicLong time = new AtomicLong(unit.toMillis(waitTime));
final long current = System.currentTimeMillis();
RFuture<Boolean> tryAcquireFuture = tryAcquireAsync(permits);
tryAcquireFuture.addListener(new FutureListener<Boolean>() {
@Override
public void operationComplete(Future<Boolean> future) throws Exception {
if (!future.isSuccess()) {
result.tryFailure(future.cause());
return;
}
if (future.getNow()) {
if (!result.trySuccess(true)) {
releaseAsync(permits);
}
return;
}
long elapsed = System.currentTimeMillis() - current;
time.addAndGet(-elapsed);
if (time.get() <= 0) {
result.trySuccess(false);
return;
}
final long current = System.currentTimeMillis();
final AtomicReference<Timeout> futureRef = new AtomicReference<Timeout>();
final RFuture<RedissonLockEntry> subscribeFuture = subscribe();
subscribeFuture.addListener(new FutureListener<RedissonLockEntry>() {
@Override
public void operationComplete(Future<RedissonLockEntry> future) throws Exception {
if (!future.isSuccess()) {
result.tryFailure(future.cause());
return;
}
if (futureRef.get() != null) {
futureRef.get().cancel();
}
long elapsed = System.currentTimeMillis() - current;
time.addAndGet(-elapsed);
if (time.get() < 0) {
unsubscribe(subscribeFuture);
result.trySuccess(false);
return;
}
tryAcquireAsync(time, permits, subscribeFuture, result);
}
});
if (!subscribeFuture.isDone()) {
Timeout scheduledFuture = commandExecutor.getConnectionManager().newTimeout(new TimerTask() {
@Override
public void run(Timeout timeout) throws Exception {
if (!subscribeFuture.isDone()) {
result.trySuccess(false);
}
}
}, time.get(), TimeUnit.MILLISECONDS);
futureRef.set(scheduledFuture);
}
}
});
return result;
}
Aggregations