h2 doesn't start programmatically

无人久伴 提交于 2019-12-13 05:22:30

问题


I have wrote following code:

  private static void startH2(){
        Server server = null;
        try {
            server = Server.createTcpServer("-tcpAllowOthers").start();
            Class.forName("org.h2.Driver");
            Connection conn = DriverManager.
                    getConnection("jdbc:h2:tcp://localhost/~/test;MODE=PostgreSQL", "sa", "");
        } catch (Exception e) {
            LOG.error("Error while initialize", e);
        }
        System.out.println("finish");
    }
    public static void main(String [] args){
        startH2();
    }

I run my main method and see following situation:

Looks like Server.createTcpServer creates new non daemon thread.

but by url localhost:8082 I don't see h2 web console(actual result - ERR_CONNECTION_REFUSED)

How to fix this?

P.S.

I have noticed that by url

http://localhost:9092/

my browser downlods file with strange content:

if to decode this text I see following message:

Version mismatch, driver version is “0” but server version is “15”

I use h2 version 1.4.182


回答1:


H2 contains multiple servers:

  • the TCP Server (for H2 JDBC clients),
  • the Web Server (for browsers, the H2 Console application), and
  • the PG Server (for PostgreSQL clients).

You have started the TCP Server. If you want to use a browser, you also need to start the Web Server:

private static void startH2(){
    Server tcpServer = null;
    Server webServer = null;
    try {
        tcpServer = Server.createTcpServer("-tcpAllowOthers").start();
        System.out.println("TCP Server Port: " + tcpServer.getPort());
        Class.forName("org.h2.Driver");
        Connection conn = DriverManager.
                getConnection("jdbc:h2:tcp://localhost/~/test22;MODE=PostgreSQL", "sa", "");
        webServer = Server.createWebServer().start();
        System.out.println("Web Server (H2Console) Port: " + webServer.getPort());
    } catch (Exception e) {
        e.printStackTrace();
    }
    System.out.println("finish");
}


来源:https://stackoverflow.com/questions/34318611/h2-doesnt-start-programmatically

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!