记得红薯大哥以前贴过一个mina的http服务器的实现,我就贴一个grizzly的。说起mina这个java网络通讯组件可是大名鼎鼎,说是高性能,的却性能强大。但是还有比它性能更强大的呢 就是这个 grizzly,glassfish就基于它。是个比mina性能更为强大的网络通讯组件,同样基于java NIO开发。我贴的代码是用它实现一个http服务器。
1.[代码][Java]代码
import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.grizzly.http.server.NetworkListener;
import org.glassfish.grizzly.threadpool.ThreadPoolConfig;
import java.io.IOException;
public class MyHttpServer {
public static void main(String[] args) {
HttpServer httpServer = new HttpServer();
NetworkListener networkListener = new NetworkListener("sample-listener", "127.0.0.1", 18888);
ThreadPoolConfig threadPoolConfig = ThreadPoolConfig
.defaultConfig()
.setCorePoolSize(1)
.setMaxPoolSize(1);
networkListener.getTransport().setWorkerThreadPoolConfig(threadPoolConfig);
httpServer.addListener(networkListener);
MyHttpHandler httpHandler = new MyHttpHandler();
httpServer.getServerConfiguration().addHttpHandler( httpHandler,new String[]{"/sample"});
try {
httpServer.start();
while(true){
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
import org.glassfish.grizzly.http.server.HttpHandler;
import org.glassfish.grizzly.http.server.Request;
import org.glassfish.grizzly.http.server.Response;
import org.glassfish.grizzly.http.util.HttpStatus;
import org.glassfish.grizzly.threadpool.GrizzlyExecutorService;
import org.glassfish.grizzly.threadpool.ThreadPoolConfig;
import java.util.concurrent.ExecutorService;
public class MyHttpHandler extends HttpHandler {
final ExecutorService complexAppExecutorService =
GrizzlyExecutorService.createInstance(
ThreadPoolConfig.defaultConfig()
.copy()
.setCorePoolSize(5)
.setMaxPoolSize(5));
public void service(final Request request, final Response response) throws Exception {
response.suspend(); // Instruct Grizzly to not flush response, once we exit the service(...) method
complexAppExecutorService.execute(new Runnable() { // Execute long-lasting task in the custom thread
public void run() {
try {
response.setContentType("text/plain");
// Simulate long lasting task
Thread.sleep(10000);
response.getWriter().write("Complex task is done!");
} catch (Exception e) {
response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR_500);
} finally {
response.resume();
}
}
});
}
}