尝试使用Undertow。这里简单的例子:
public class MyExample {
private static int SIMPLE_HANDLER_CALL = 0;
private static int LIBRE_OFFICE_CALL = 0;
public static void main(String[] args) {
Undertow server = Undertow.builder()
.addHttpListener(3333, "localhost")
.setHandler(new SimpleHttpHandler())
.build();
server.start();
}
private static class SimpleHttpHandler implements HttpHandler{
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
System.out.println("---------------------------------------------");
System.out.println("start handleRequest()");
exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain");
connectToPg(exchange, "msgPrev = " + Integer.toString(SIMPLE_HANDLER_CALL) + "; msgCur = " + Integer.toString(++SIMPLE_HANDLER_CALL));
System.out.println("end handleRequest()");
}
}
private static void connectToPg(HttpServerExchange exchange, String msg){
try(
Connection connection = DriverManager.getConnection("jdbc:postgresql://10.10.2.158:5432/myDb", "myUser", "myPass");
Statement st = connection.createStatement();
)
{
ResultSet rs = st.executeQuery("select count(*) as CNT from event.event");
java.util.Date now = new java.util.Date();
while(rs.next()){
int cnt = rs.getInt("CNT");
System.out.print("cnt = " + cnt);
exchange.getResponseSender().send("Date = " + now + "; cnt = " + cnt);
}
System.out.println("rs = " + rs.toString());
System.out.println("msg = " + msg);
}
catch (Exception ex){
System.out.println(ex.getMessage());
}
finally {
System.out.println("end connectToPg()");
}
}
}
它有效。I型
http://localhost:3333/
在浏览器和处理程序中创建对Postgres的查询并接收答案。但是,处理程序重复2次!我在控制台中得到这样的输出:
---------------------------------------------
start handleRequest()
cnt = 12rs = org.postgresql.jdbc4.Jdbc4ResultSet@12eeffa4
msg = msgPrev = 0; msgCur = 1
end connectToPg()
end handleRequest()
---------------------------------------------
start handleRequest()
cnt = 12rs = org.postgresql.jdbc4.Jdbc4ResultSet@17b98b20
msg = msgPrev = 1; msgCur = 2
end connectToPg()
end handleRequest()
为什么叫了两次?
我建议打印(或注销)交换参数,看看处理的是什么类型的请求。
System.out.println(exchange.getRequestURL());
一种选择是,第二个请求是针对/favicon.ico的。您也可以尝试以更可控的方式发出请求,即使用一个REST客户端,甚至curl。