蔚来的另一个绊脚石
我有一个小型服务器,它可以在 Windows 下运行,而不能在 Red Hat 下运行。这个想法是:
- 带有 ServerSocketChannel 和 Selector 的主线程
- 当它接受一个连接时,它会创建一个带有 SocketChannel 的事件
- 事件被提供给队列
- 每个 Worker 线程都有自己的 Selector 和 DB Connection
- Worker 线程从 Queue 中获取 Event,在其中设置 Selector 和 DB Connection,并调用 Event 的 getProcessed 方法
- 事件读取 SocketChannel(总是很好),在 DB 中做一些事情(总是很好)并写入 SocketChannel(在 Windows 下工作,在 Red Hat 下不工作)
代码是:
public void processWriting()
throws Exception {
sk = client.register(selector, SelectionKey.OP_WRITE);
String s = "HTTP/1.1 301 Moved Permanently\r\n" +
"Location: " + resolution + "\r\n";
writeBuffer = ByteBuffer.wrap(s.getBytes("US-ASCII"));
LOGGER.trace("1. limit::" + writeBuffer.limit());
LOGGER.trace("1. position::" + writeBuffer.position());
LOGGER.trace("1. remaining::" + writeBuffer.remaining());
for (;;) {
selector.select(500);
// write once
for (Iterator<SelectionKey> it = selector.selectedKeys().iterator();
it.hasNext();) {
SelectionKey key = it.next();
it.remove();
if (key.isValid() && key.isWritable()) {
// write
client.write(writeBuffer);
}
}
// check all written out
if (!writeBuffer.hasRemaining()) {
break;
}
// check time
if (params.getTimeout() < processingTime()) {
break;
}
}
LOGGER.trace("2. limit::" + writeBuffer.limit());
LOGGER.trace("2. position::" + writeBuffer.position());
LOGGER.trace("2. remaining::" + writeBuffer.remaining());
if (writeBuffer.hasRemaining()) {
throw new Exception("writing failed");
}
writeBuffer = null;
}
日志输出为:
2012-12-20 18:06:13,113 [TRACE] Thread-4:: bg.nalis.pidresolver.Event:: 1. limit::137
2012-12-20 18:06:13,113 [TRACE] Thread-4:: bg.nalis.pidresolver.Event:: 1. position::0
2012-12-20 18:06:13,113 [TRACE] Thread-4:: bg.nalis.pidresolver.Event:: 1. remaining::137
2012-12-20 18:06:13,113 [TRACE] Thread-4:: bg.nalis.pidresolver.Event:: 2. limit::137
2012-12-20 18:06:13,113 [TRACE] Thread-4:: bg.nalis.pidresolver.Event:: 2. position::137
2012-12-20 18:06:13,113 [TRACE] Thread-4:: bg.nalis.pidresolver.Event:: 2. remaining::0
我将不胜感激任何意见和建议。