java grizzly_java grizzly实现http服务器

记得红薯大哥以前贴过一个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();

}

}

});

}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值