use of org.jboss.netty.channel.ChannelFuture in project crate by crate.
the class Messages method sendShortMsg.
/**
* Send a message that just contains the msgType and the msg length
*/
private static void sendShortMsg(Channel channel, char msgType, final String traceLogMsg) {
ChannelBuffer buffer = ChannelBuffers.buffer(5);
buffer.writeByte(msgType);
buffer.writeInt(4);
ChannelFuture channelFuture = channel.write(buffer);
if (LOGGER.isTraceEnabled()) {
channelFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
LOGGER.trace(traceLogMsg);
}
});
}
}
use of org.jboss.netty.channel.ChannelFuture in project jstorm by alibaba.
the class NettyClient method closeChannel.
/**
* Avoid channel double close
*
* @param channel
*/
void closeChannel(final Channel channel) {
synchronized (channelClosing) {
if (closingChannel.contains(channel)) {
LOG.info(channel.toString() + " is already closed");
return;
}
closingChannel.add(channel);
}
LOG.debug(channel.toString() + " begin to closed");
ChannelFuture closeFuture = channel.close();
closeFuture.addListener(new ChannelFutureListener() {
public void operationComplete(ChannelFuture future) throws Exception {
synchronized (channelClosing) {
closingChannel.remove(channel);
}
LOG.debug(channel.toString() + " finish closed");
}
});
}
use of org.jboss.netty.channel.ChannelFuture in project canal by alibaba.
the class ClientAuthenticationHandler method messageReceived.
public void messageReceived(final ChannelHandlerContext ctx, MessageEvent e) throws Exception {
ChannelBuffer buffer = (ChannelBuffer) e.getMessage();
final Packet packet = Packet.parseFrom(buffer.readBytes(buffer.readableBytes()).array());
switch(packet.getVersion()) {
case SUPPORTED_VERSION:
default:
final ClientAuth clientAuth = ClientAuth.parseFrom(packet.getBody());
// 如果存在订阅信息
if (StringUtils.isNotEmpty(clientAuth.getDestination()) && StringUtils.isNotEmpty(clientAuth.getClientId())) {
ClientIdentity clientIdentity = new ClientIdentity(clientAuth.getDestination(), Short.valueOf(clientAuth.getClientId()), clientAuth.getFilter());
try {
MDC.put("destination", clientIdentity.getDestination());
embeddedServer.subscribe(clientIdentity);
// 设置状态数据
ctx.setAttachment(clientIdentity);
// 尝试启动,如果已经启动,忽略
if (!embeddedServer.isStart(clientIdentity.getDestination())) {
ServerRunningMonitor runningMonitor = ServerRunningMonitors.getRunningMonitor(clientIdentity.getDestination());
if (!runningMonitor.isStart()) {
runningMonitor.start();
}
}
} finally {
MDC.remove("destination");
}
}
NettyUtils.ack(ctx.getChannel(), new ChannelFutureListener() {
public void operationComplete(ChannelFuture future) throws Exception {
logger.info("remove unused channel handlers after authentication is done successfully.");
ctx.getPipeline().remove(HandshakeInitializationHandler.class.getName());
ctx.getPipeline().remove(ClientAuthenticationHandler.class.getName());
int readTimeout = defaultSubscriptorDisconnectIdleTimeout;
int writeTimeout = defaultSubscriptorDisconnectIdleTimeout;
if (clientAuth.getNetReadTimeout() > 0) {
readTimeout = clientAuth.getNetReadTimeout();
}
if (clientAuth.getNetWriteTimeout() > 0) {
writeTimeout = clientAuth.getNetWriteTimeout();
}
IdleStateHandler idleStateHandler = new IdleStateHandler(NettyUtils.hashedWheelTimer, readTimeout, writeTimeout, 0);
ctx.getPipeline().addBefore(SessionHandler.class.getName(), IdleStateHandler.class.getName(), idleStateHandler);
IdleStateAwareChannelHandler idleStateAwareChannelHandler = new IdleStateAwareChannelHandler() {
public void channelIdle(ChannelHandlerContext ctx, IdleStateEvent e) throws Exception {
logger.warn("channel:{} idle timeout exceeds, close channel to save server resources...", ctx.getChannel());
ctx.getChannel().close();
}
};
ctx.getPipeline().addBefore(SessionHandler.class.getName(), IdleStateAwareChannelHandler.class.getName(), idleStateAwareChannelHandler);
}
});
break;
}
}
use of org.jboss.netty.channel.ChannelFuture in project neo4j by neo4j.
the class Client method start.
@Override
public void start() {
bootstrap = new ClientBootstrap(new NioClientSocketChannelFactory(newCachedThreadPool(daemon(getClass().getSimpleName() + "-boss@" + destination)), newCachedThreadPool(daemon(getClass().getSimpleName() + "-worker@" + destination))));
bootstrap.setPipelineFactory(this);
channelPool = new ResourcePool<ChannelContext>(maxUnusedChannels, new ResourcePool.CheckStrategy.TimeoutCheckStrategy(DEFAULT_CHECK_INTERVAL, Clocks.systemClock()), new LoggingResourcePoolMonitor(msgLog)) {
@Override
protected ChannelContext create() {
msgLog.info(threadInfo() + "Trying to open a new channel from " + origin + " to " + destination, true);
// We must specify the origin address in case the server has multiple IPs per interface
ChannelFuture channelFuture = bootstrap.connect(destination, origin);
channelFuture.awaitUninterruptibly(5, TimeUnit.SECONDS);
if (channelFuture.isSuccess()) {
msgLog.info(threadInfo() + "Opened a new channel from " + channelFuture.getChannel().getLocalAddress() + " to " + channelFuture.getChannel().getRemoteAddress());
return new ChannelContext(channelFuture.getChannel(), ChannelBuffers.dynamicBuffer(), ByteBuffer.allocate(1024 * 1024));
}
Throwable cause = channelFuture.getCause();
String msg = Client.this.getClass().getSimpleName() + " could not connect from " + origin + " to " + destination;
msgLog.debug(msg, true);
throw traceComException(new ComException(msg, cause), "Client.start");
}
@Override
protected boolean isAlive(ChannelContext context) {
return context.channel().isConnected();
}
@Override
protected void dispose(ChannelContext context) {
Channel channel = context.channel();
if (channel.isConnected()) {
msgLog.info(threadInfo() + "Closing: " + context + ". " + "Channel pool size is now " + currentSize());
channel.close();
}
}
private String threadInfo() {
return "Thread[" + Thread.currentThread().getId() + ", " + Thread.currentThread().getName() + "] ";
}
};
/*
* This is here to couple the channel releasing to Response.close() itself and not
* to TransactionStream.close() as it is implemented here. The reason is that a Response
* that is returned without a TransactionStream will still hold the channel and should
* release it eventually. Also, logically, closing the channel is not dependent on the
* TransactionStream.
*/
resourcePoolReleaser = () -> {
if (channelPool != null) {
channelPool.release();
}
};
}
use of org.jboss.netty.channel.ChannelFuture in project neo4j by neo4j.
the class NetworkSender method send.
private synchronized void send(final Message message) {
monitor.queuedMessage(message);
final URI to = URI.create(message.getHeader(Message.TO));
ExecutorService senderExecutor = senderExecutors.get(to);
if (senderExecutor == null) {
senderExecutor = Executors.newSingleThreadExecutor(new NamedThreadFactory("Cluster Sender " + to.toASCIIString(), monitor));
senderExecutors.put(to, senderExecutor);
}
senderExecutor.submit(new Runnable() {
@Override
public void run() {
Channel channel = getChannel(to);
try {
if (channel == null) {
channel = openChannel(to);
openedChannel(to, channel);
// Instance could be connected to, remove any marker of it being failed
failedInstances.remove(to);
}
} catch (Exception e) {
// Only print out failure message on first fail
if (!failedInstances.contains(to)) {
msgLog.warn(e.getMessage());
failedInstances.add(to);
}
return;
}
try {
// Set FROM header
message.setHeader(Message.FROM, me.toASCIIString());
msgLog.debug("Sending to " + to + ": " + message);
ChannelFuture future = channel.write(message);
future.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
monitor.sentMessage(message);
if (!future.isSuccess()) {
msgLog.debug("Unable to write " + message + " to " + future.getChannel(), future.getCause());
closedChannel(future.getChannel());
// Try again
send(message);
}
}
});
} catch (Exception e) {
if (Exceptions.contains(e, ClosedChannelException.class)) {
msgLog.warn("Could not send message, because the connection has been closed.");
} else {
msgLog.warn("Could not send message", e);
}
channel.close();
}
}
});
}
Aggregations