Remote connection to a H2 database in server mode with DBCP pooling

时光毁灭记忆、已成空白 提交于 2019-12-08 03:29:58

问题


I'm trying to create an embedded H2 server which I could also access remotly and also use Tomcat DBCP Pooling.

Here is my code to produce the dataSource :

@Produces @ApplicationScoped
public DataSource getDataSource() throws NamingException, SQLException {
    dataSource = new BasicDataSource();
    dataSource.setDriverClassName("org.h2.jdbcx.JdbcDataSource");
    dataSource.setUrl("jdbc:h2:/tmp/myapp");
    dataSource.setUsername("sa");
    dataSource.setPassword("");
    dataSource.setMaxActive(100);
    dataSource.setMaxIdle(30);
    dataSource.setMaxWait(10000);
    // start the pool
    Connection connection = dataSource.getConnection();
    // start the server
    server = Server.createTcpServer("-tcpAllowOthers").start();
    connection.close();
    return dataSource;
}

And when I try to connect it remotly (using for example H2 Browser (java -jar h2.jar -browser)) using URL "jdbc:h2:tcp://192.168.2.58//tmp/myapp" (192.168.2.58 is the remote IP of the server) here is the error I get :

Database may be already in use: "/tmp/myapp.mv.db". Possible solutions: close all other connection(s); use the server mode [90020-179] 90020/90020

Does somebody have a solution?


回答1:


Here is finally the code that worked:

@ApplicationScoped
public class DataSourceProducer {

    private JdbcDataSource dataSource;
    private Server server;

    @Produces @ApplicationScoped
    public DataSource getDataSource() throws NamingException, SQLException {
        dataSource = new JdbcDataSource();
        dataSource.setUrl("jdbc:h2:/tmp/myapp");
        dataSource.setUser("sa");
        dataSource.setPassword("");
        // start the server
        server = Server.createTcpServer("-tcpAllowOthers").start();
        return dataSource;
    }

    public void disposeDataSource(@Disposes DataSource dataSource) throws SQLException {
        server.stop();
    }
}

And then I can access it via using URL jdbc:h2:tcp://<remote ip>//tmp/myapp (at least I made it working via SSH tunneling the 9020 port and access it with jdbc:h2:tcp://localhost//tmp/myapp)




回答2:


Check H2 Multiple connections. You need a client/server mode to be able to open the database multiple of times. By default, embedded databases cannot be opened several times. You need to use the "automatic mixed-mode" feature :

Mixed Mode for H2 database

So if you modify your jdbc url as follow, it should work :

jdbc:h2:/tmp/myapp;AUTO_SERVER=TRUE



来源:https://stackoverflow.com/questions/24528160/remote-connection-to-a-h2-database-in-server-mode-with-dbcp-pooling

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