论坛首页 Java企业应用论坛

基于JDK HttpServer的RESTEasy

浏览 6077 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2012-05-30  
从RESTEasy 2.3开始,加入了一种新的无需Servlet容器的运行方式-通过使用JDK自带的轻量级HTTP Server进行加载。

HttpServer介绍

首先介绍一下JDK中自带的HttpServer,下面是一个例子:

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Executors;

public class HttpServerDemo {
    public static void main(String[] args) throws IOException {
        InetSocketAddress addr = new InetSocketAddress(8080);
        HttpServer server = HttpServer.create(addr, 0);

        server.createContext("/", new MyHandler());
        server.setExecutor(Executors.newCachedThreadPool());
        server.start();
        System.out.println("Server is listening on port 8080");
    }
}

class MyHandler implements HttpHandler {
    public void handle(HttpExchange exchange) throws IOException {
        String requestMethod = exchange.getRequestMethod();
        if (requestMethod.equalsIgnoreCase("GET")) {
            Headers responseHeaders = exchange.getResponseHeaders();
            responseHeaders.set("Content-Type", "text/plain");
            exchange.sendResponseHeaders(200, 0);

            OutputStream responseBody = exchange.getResponseBody();
            Headers requestHeaders = exchange.getRequestHeaders();
            Set<String> keySet = requestHeaders.keySet();
            Iterator<String> iter = keySet.iterator();
            while (iter.hasNext()) {
                String key = iter.next();
                List values = requestHeaders.get(key);
                String s = key + " = " + values.toString() + "\n";
                responseBody.write(s.getBytes());
            }
            responseBody.close();
        }
    }
}


JDK自带的HttpServer是一个非常轻量级的Http服务端框架,但是它非常灵活,易于扩展,组成框架的核心类及框架为:

com.sun.net.httpserver.HttpExchange;
com.sun.net.httpserver.HttpHandler;
com.sun.net.httpserver.HttpServer;


其中,HttpHandler框架是我们要实现的服务接口:通过处理HttpExchange中包含的Request,Response及各种HTTP协议信息,实现我们的处理逻辑。上面的例子中,在MyHandler中实现了服务器端的处理逻辑:将用户的请求信息打印出来。

最后,通过将HttpServer绑定至服务端口,进行启动:

InetSocketAddress addr = new InetSocketAddress(8080);
HttpServer server = HttpServer.create(addr, 0);
server.start();



执行上面的例子,访问:

http://localhost:8080


返回如下:

Host = [localhost:8080]
Accept-encoding = [gzip, deflate]
Connection = [keep-alive]
Accept-language = [en-us]
User-agent = [Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/534.55.3 (KHTML, like Gecko) Version/5.1.5 Safari/534.55.3]
Accept = [text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8]


RESTEasy + HttpServer

从RESTEasy 2.3.3开始,添加了对JDK的HttpSever支持,使得RESTEasy容器可以脱离Servlet容器(比如Tomcat或JBoss),基于HttpSever启动。新的机制主要依赖于:

org.jboss.resteasy.plugins.server.sun.http.HttpContextBuilder;


通过使用RESTEasy新提供的HttpContextBuilder,便可将RESTFul WebService注册进HttpServer。假设我们有resouce如下:

@Path("/")
public class SimpleResource
{
   @GET
   @Path("basic")
   @Produces("text/plain")
   public String getBasic()
   {
      System.out.println("getBasic()");
      return "basic";
   }
}


则结合HttpServer的具体调用方式如下:

InetSocketAddress addr = new InetSocketAddress(8080);
HttpServer httpServer = HttpServer.create(addr, 0);
...
contextBuilder = new HttpContextBuilder();
contextBuilder.getDeployment().getActualResourceClasses().add(SimpleResource.class);
contextBuilder.bind(httpServer);
...
httpServer.start();


RESTEasy的这一新模块位于RESTEasy源代码目录中的server-adapters/resteasy-jdk-http子项目:

https://github.com/resteasy/Resteasy/tree/master/jaxrs/server-adapters/resteasy-jdk-http

论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics