when netty connects to my server? - java

I am using the Channle pool API code written here:
ChannelPool section http://netty.io/news/2015/05/07/4-0-28-Final.html
EventLoopGroup group = new NioEventLoopGroup();
final Bootstrap cb = new Bootstrap();
InetSocketAddress addr1 = new InetSocketAddress("10.0.0.10", 8888);
InetSocketAddress addr2 = new InetSocketAddress("10.0.0.11", 8888);
cb.group(group).channel(NioSocketChannel.class);
ChannelPoolMap<InetSocketAddress, SimpleChannelPool> poolMap = new AbstractChannelPoolMap<InetSocketAddress, SimpleChannelPool>() {
#Override
protected SimpleChannelPool newPool(InetSocketAddress key) {
return new SimpleChannelPool(cb.remoteAddress(key), new TestChannelPoolHandler());
}
};
// depending on when you use addr1 or addr2 you will get different pools.
final SimpleChannelPool pool = poolMap.get(addr1);
Future<Channel> f = pool.acquire();
f.addListener(new FutureListener<Channel>() {
#Override
public void operationComplete(Future<Channel> f) {
if (f.isSuccess()) {
Channel ch = f.getNow();
// Do somethings
// ...
// ...
// Release back to pool
pool.release(ch);
}
}
});
As i see the code we never called .connect method so my question is when netty trying to connecting my channel to server ?

As you use SimpleChannelPool it will do connect when you call acquire and there is nothing left in the ChannelPool.

Related

RabbitMQ Flow Control Not Working (Java Client)

I'm constructing my RabbitMQ (RabbitMQ 3.6.5, Erlang R16B03) connection as follows:
ConnectionFactory factory = new ConnectionFactory();
factory.setHost(App.rabbitMQServer);
factory.setVirtualHost(App.rabbitVirtualHost);
factory.setRequestedHeartbeat(5);
factory.setConnectionTimeout(5000);
factory.setAutomaticRecoveryEnabled(true);
factory.setNetworkRecoveryInterval(5000);
Map<String, Object> clientProperties = new HashMap<>();
Map<String, Object> capabilities = new HashMap<>();
capabilities.put("connection.blocked", true);
clientProperties.put("capabilities", capabilities);
factory.setClientProperties(clientProperties);
_connection = factory.newConnection();
_channel = _connection.createChannel();
_connection.addBlockedListener(new BlockedListener() {
public void handleBlocked(String reason) throws IOException {
connectionIsBlocked = true;
log.warn("RabbitMQ connection blocked");
}
public void handleUnblocked() throws IOException {
connectionIsBlocked = false;
log.warn("RabbitMQ connection unblocked");
}
});
The connection looks ok in the management web console - the capabilities are present however the BlockedListener methods are never called. What am I missing?
Incidentally, I have another process written in Go which also never calls its flow listener...
flow := ch.NotifyFlow(make(chan bool))
go func() {
for f := range flow {
shouldFailoverToSQS = f
log.Infof("Flow status changed")
}
}()
I was confusing the BlockedListener and the FlowListener (which is deprecated).

Netty channelAcquired is not getting called

I'm using netty channel pool for a http client and in the ChannelPoolHandler implementation channelAcquired is not getting called when the channelPool.acquire() invoked. I'm using netty 4.0.32.Final. Here's how I created the chanelpool. I just followed the simple example listed at netty.io. If someone can just explain what I've done wrong or if there is a bug that'll be very helpful. Thanks.
EventLoopGroup group = new NioEventLoopGroup();
final Bootstrap b = new Bootstrap();
b.group(group).channel(NioSocketChannel.class);
AbstractChannelPoolMap<InetSocketAddress, SimpleChannelPool> poolMap = new AbstractChannelPoolMap<InetSocketAddress, SimpleChannelPool>() {
#Override
protected SimpleChannelPool newPool(InetSocketAddress key) {
return new SimpleChannelPool(b.remoteAddress(key), new HttpClientPoolHandler());
}
};
final SimpleChannelPool simpleChannelPool = poolMap.get(new InetSocketAddress(uri.getHost(), uri.getPort()));
final Future<Channel> acquire = simpleChannelPool.acquire();
acquire.addListener(new FutureListener<Channel>() {
public void operationComplete(Future<Channel> f) throws Exception {
if (f.isSuccess()) {
final Channel ch = f.getNow();
// Send the HTTP request.
ChannelFuture channelFuture = ch.writeAndFlush(request);
channelFuture.addListener(new ChannelFutureListener() {
public void operationComplete(ChannelFuture channelFuture) throws Exception {
if (channelFuture.isSuccess()) {
simpleChannelPool.release(ch);
} else {
}
}
});
} else {
System.out.println("ERROR : " + f.cause());
}
}
});
The channelAcquiredmethod will only be called if you "acquire" a previous created channel. In your case there is not channel yet in the pool so it will call channelCreated.

What is the best approach to bind to different port on same handler in Netty?

Please review the below code. Here i am trying to listen two ports with same factory. Only one port listening right now. Please suggest how to achieve multiple port listening with same factory for same handler function for all ports.
public static void main(String[] args)
{
ChannelFactory factory = new NioServerSocketChannelFactory(Executors.newCachedThreadPool(),Executors.newFixedThreadPool(1));
ServerBootstrap bootstrap = new ServerBootstrap(factory);
ChannelPipelineFactory cpf = new ChannelPipelineFactory()
{
public ChannelPipeline getPipeline()
{
return Channels.pipeline(new testHandler());
}
};
bootstrap.setPipelineFactory(cpf);
bootstrap.setOption("child.tcpNoDelay", true);
ChannelGroup allChannels = new DefaultChannelGroup();
Channel serverChannel = bootstrap.bind(new InetSocketAddress(5000));
allChannels.add(serverChannel);
Channel serverChannel1 = bootstrap.bind(new InetSocketAddress(6000));
allChannels.add(serverChannel1);
bootstrap.bind(new InetSocketAddress(5000));
}
You can create multiple ServerBootstrap instances. Each ServerBootstrap use a Server Channel to bind.

Netty Scheduling

I am using netty HexDumpProxy example(using Netty 5 lib),in that I want to send some messages to server for each 40 seconds. How to achieve this using Netty.
Help me to solve this.
Update:
here is my initChannel method,
protected void initChannel(SocketChannel sc) throws Exception {
int readerIdleTimeSeconds = 5;
int writerIdleTimeSeconds = 5;
int allIdleTimeSeconds = 0;
ChannelPipeline pipe = sc.pipeline();
// pipe.addLast("rtspdecoder", new RtspRequestDecoder());
// pipe.addLast("rtspencoder", new RtspResponseEncoder());
// pipe.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
// pipe.addLast("encoder", new StringEncoder());
// pipe.addLast("decoder", new StringDecoder());
// pipe.addLast("idleStateHandler", new IdleStateHandler(readerIdleTimeSeconds, writerIdleTimeSeconds, allIdleTimeSeconds));
// pipe.addLast("idleStateEventHandler", new MyIdlestaeEvtHandler());
pipe.addLast("decoder", new MyRtspRequestDecoder());
pipe.addLast("encoder", new MyRtspResponseEncoder());
pipe.addLast("handler", new PServerRequestHandler(remoteHost, remotePort));
pipe.addLast("idleStateHandler", new IdleStateHandler(readerIdleTimeSeconds, writerIdleTimeSeconds, allIdleTimeSeconds));
pipe.addLast("idleStateEventHandler", new MyIdlestaeEvtHandler());
}
here is MyIdlestaeEvtHandler class,
public class MyIdlestaeEvtHandler extends ChannelDuplexHandler {
#Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if(evt instanceof IdleStateEvent) {
IdleStateEvent e = (IdleStateEvent) evt;
if(e.state() == IdleState.WRITER_IDLE) {
String s = "Ping Pong!";
ctx.channel().writeAndFlush(Unpooled.copiedBuffer(s.getBytes()));
System.err.println("writing idle------------------------");
} else if(e.state() == IdleState.READER_IDLE) {
System.err.println("reading idle------------------------");
String s = "Pong Pong!";
ctx.channel().writeAndFlush(Unpooled.copiedBuffer(s.getBytes()));
}
}
}
}
I am able to see the writing idle------------------------ but, the same is not passed to server, because I am not able to see this message in server debug messages.
Anything wrong with the code?
ThankYou
Netty 4.x provides the capability to schedule an instance of Runnable to be executed at a fixed rate using the scheduleAtFixedRate() method on a channel's eventloop.
see javadoc for scheduleAtFixedRate() in EventExecutorGroup
Example:
channel.eventLoop().scheduleAtFixedRate(new Runnable(){
#Override
public void run()
{
System.out.println("print a line every 10 seconds with a 5 second initial delay");
}
}, 5, 10, TimeUnit.SECONDS);
Use IdleStateHandler. For more informations please check its javadocs.

HttpClient How to set Connection Timeout in individual GetMethod

In my web application I have a global static HttpClient that is used in many parts of the application. It is created like this:
MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
HttpConnectionManagerParams params = new HttpConnectionManagerParams();
params.setConnectionTimeout( 15000 );
params.setSoTimeout( 15000 );
connectionManager.setParams(params);
httpclient = new HttpClient(connectionManager);
HttpClientParams clientParams = new HttpClientParams();
clientParams.setParameter("http.protocol.allow-circular-redirects", true);
clientParams.setParameter("http.protocol.max-redirects", 4);
httpclient.setParams(clientParams);
The timeouts are fine for most use cased, but in a specific call I would like a shorter timeout. So I have:
GetMethod get = new GetMethod(finalUrl);
get.getParams().setParameter("http.socket.timeout", new Integer(1000));
get.getParams().setParameter("http.connection.timeout", new Integer(1000));
HttpClientUtil.getShortTimeoutInstance().executeMethod(get);
It does not work. The connection timeout is still 15000. Can I set a specific connection timeout in the GetMethod without creating a new HttpClient instance (this is because I believe creating a new HttpClient instance would not be a good idea).
you might want to look at
./impl/conn/tsccm/ThreadSafeClientConnManager.java
method
ClientConnectionRequest requestConnection(final HttpRoute route,
final Object state)
Once the connection pool has been initialized for the route, the originally configured value for socket timeOut will continue to be used unless you extend/override it.
public ClientConnectionRequest requestConnection(
final HttpRoute route,
final Object state) {
final PoolEntryRequest poolRequest = pool.requestPoolEntry(
route, state);
return new ClientConnectionRequest() {
public void abortRequest() {
poolRequest.abortRequest();
}
public ManagedClientConnection getConnection(
long timeout, TimeUnit tunit) throws InterruptedException,
ConnectionPoolTimeoutException {
if (route == null) {
throw new IllegalArgumentException("Route may not be null.");
}
if (log.isDebugEnabled()) {
log.debug("Get connection: " + route + ", timeout = " + timeout);
}
BasicPoolEntry entry = poolRequest.getPoolEntry(timeout, tunit);
return new BasicPooledConnAdapter(ThreadSafeClientConnManager.this, entry);
}
};
}

Categories

Resources