问题
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