我正在尝试使用 H2 触发器工具,让以自动混合模式 (AUTO_SERVER=TRUE) 连接到 H2 数据库的客户端在数据库表发生更改时收到通知
test(id INTEGER NOT NULL AUTO_INCREMENT, message varchar(1024))
到目前为止,只有 H2 服务器收到 TRIGGER 通知,而客户端无法收到任何通知,因此他们检查数据库更改的唯一方法是轮询对表的查询,但这种方式 TRIGGER 本身是无用的,我可以简单所有客户端和服务器轮询数据库的更改!。
有没有办法让触发器通知所有连接的客户端或在每个客户端内部调用一个方法,以便他们意识到表已被插入修改(不打扰我删除或更新的情况)?
我在下面发布了我的代码,该代码基于Thomas Mueller(H2 数据库创建者)的这个答案:
import java.sql.*;
import java.util.concurrent.atomic.AtomicLong;
import org.h2.api.Trigger;
public class TestSimpleDb
{
public static void main(String[] args) throws Exception
{
final String url = "jdbc:h2:test;create=true;AUTO_SERVER=TRUE;multi_threaded=true";
boolean isSender = false;
for (String arg : args)
{
if (arg.contains("receiver"))
{
System.out.println("receiver starting");
isSender = false;
}
else if (arg.contains("sender"))
{
System.out.println("sender starting");
isSender = true;
}
}
if (isSender)
{
Connection conn = DriverManager.getConnection(url);
Statement stat = conn.createStatement();
stat.execute("create table test(id INTEGER NOT NULL AUTO_INCREMENT, message varchar(1024))");
stat.execute("create trigger notifier "
+ "before insert, update, delete, rollback "
+ "on test FOR EACH ROW call \""
+ TestSimpleDb.Notifier.class.getName() + "\"");
Thread.sleep(500);
for (int i = 0; i < 10; i++) {
System.out.println("Sender: I change something...");
stat.execute("insert into test(message) values('my message')");
Thread.sleep(1000);
}
conn.close();
}
else
{
new Thread() {
public void run() {
try {
Connection conn = DriverManager.getConnection(url);
while (true) {
;
//this loop is just to keep the thread alive..
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}.start();
}
}
public static class Notifier implements Trigger
{
@Override
public void init(Connection cnctn, String string, String string1, String string2, boolean bln, int i) throws SQLException {
// Initializing trigger
}
@Override
public void fire(Connection conn, Object[] oldRow, Object[] newRow) throws SQLException {
if (newRow != null) {
System.out.println("Received: " + (String) newRow[1]);
}
}
@Override
public void close() {
// ignore
}
@Override
public void remove() {
// ignore
}
}
}