尝试使用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()");
}
}
}
有效。我输入
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()
为什么叫它2次?
答案 0 :(得分:0)
我建议打印(或注销)交换参数以查看正在处理的请求类型。
System.out.println(exchange.getRequestURL());
一个选项是第二个请求是针对/favicon.ico的。您还可以尝试以更加可控的方式提出请求 - 即。使用其中一个REST客户端甚至卷曲。