Created
November 7, 2013 14:55
-
-
Save chocotan/7355929 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment