尝试使用 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次?