Skip to content

Instantly share code, notes, and snippets.

@jcfandino
Last active May 24, 2019 20:54
Show Gist options
  • Save jcfandino/129cb43a084337db55d34f70e9b083b3 to your computer and use it in GitHub Desktop.
Save jcfandino/129cb43a084337db55d34f70e9b083b3 to your computer and use it in GitHub Desktop.
H2Gis in cluster mode
plugins {
id 'java'
}
sourceCompatibility = '11'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.orbisgis:h2gis:1.5.0'
}
package com.github.jcfandino;
import org.h2.tools.CreateCluster;
import org.h2.tools.Server;
import org.h2gis.functions.factory.H2GISFunctions;
import java.nio.file.Files;
import java.nio.file.Path;
import java.sql.DriverManager;
public class TestH2GisApplication {
public static void main(String[] args) {
try {
// Cleanup
Files.deleteIfExists(Path.of("db1/db.mv.db"));
Files.deleteIfExists(Path.of("db2/db.mv.db"));
// Start server 1
Server.createTcpServer("-baseDir", "db1", "-tcp", "-tcpAllowOthers", "-tcpPort", "9091").start();
// Start server 2
Server.createTcpServer("-baseDir", "db2", "-tcp", "-tcpAllowOthers", "-tcpPort", "9092").start();
// Connect to server 1 and init database.
try (var con = DriverManager.getConnection("jdbc:h2:tcp://localhost:9091/./db")) {
H2GISFunctions.load(con); // <-- comment this line and the example works
con.createStatement().execute("create table if not exists geometries(id serial, geo geometry);");
con.createStatement().execute("insert into geometries(geo) values ('POINT(10 10)');");
// Query server 1
try (var results = con.createStatement().executeQuery("select * from geometries;")) {
results.next();
System.out.println("So far so good: " + results.getString(2));
}
}
// Create cluster between both servers (this is where it fails)
new CreateCluster().runTool(
"-urlSource", "jdbc:h2:tcp://localhost:9091/./db",
"-urlTarget", "jdbc:h2:tcp://localhost:9092/./db",
"-serverList", "localhost:9091,localhost:9092");
// Query cluster
try (var con = DriverManager.getConnection("jdbc:h2:tcp://localhost:9091,localhost:9092/./db");
var results = con.createStatement().executeQuery("select * from geometries;")) {
results.next();
System.out.println("My wish: " + results.getString(2));
}
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
System.exit(0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment