使用DBCP池以服务器模式远程连接到H2数据库 [英] Remote connection to a H2 database in server mode with DBCP pooling

查看:245
本文介绍了使用DBCP池以服务器模式远程连接到H2数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个嵌入式H2服务器,该服务器也可以远程访问并使用Tomcat DBCP池.

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;
}

当我尝试使用URL"jdbc:h2:tcp://192.168.2.58//tmp/myapp"(192.168.2.58是远程服务器的IP),这是我得到的错误:

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

有人可以解决吗?

推荐答案

以下是有效的代码:

@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();
    }
}

然后我可以使用URL jdbc:h2:tcp://<remote ip>//tmp/myapp来访问它(至少我通过SSH隧道使9020端口起作用并使用jdbc:h2:tcp://localhost//tmp/myapp来访问它)

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)

这篇关于使用DBCP池以服务器模式远程连接到H2数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆