数据库监听触发器java_如何在Java中实现db侦听器

我有一个针对Oracle的解决方案。你不需要创建自己的,因为现在Oracle收购了Java,它发布了一个监听器。据我所知,这不会在内部使用轮询,而是将通知推送到Java端(可能基于某些触发器):

public interface oracle.jdbc.dcn.DatabaseChangeListener

extends java.util.EventListener {

void onDatabaseChangeNotification(oracle.jdbc.dcn.DatabaseChangeEvent arg0);

}

你可以像这样实现它(这只是一个例子):

public class DBListener implements DatabaseChangeListener {

private DbChangeNotification toNotify;

public BNSDBListener(DbChangeNotification toNotify) {

this.toNotify = toNotify;

}

@Override

public void onDatabaseChangeNotification(oracle.jdbc.dcn.DatabaseChangeEvent e) {

synchronized( toNotify ) {

try {

toNotify.notifyDBChangeEvent(e); //do sth

} catch (Exception ex) {

Util.logMessage(CLASSNAME, "onDatabaseChangeNotification",

"Errors on the notifying object.", true);

Util.printStackTrace(ex);

Util.systemExit();

}

}

}

}

编辑:

您可以使用以下类注册:oracle.jdbc.OracleConnectionWrapper

public class oracle.jdbc.OracleConnectionWrapper implements oracle.jdbc.OracleConnection {...}

假设您在某处创建方法:

public void registerPushNotification(String sql) {

oracle.jdbc.driver.OracleConnection oracleConnection = ...;//connect to db

dbProperties.setProperty(OracleConnection.DCN_NOTIFY_ROWIDS, "true");

dbProperties.setProperty(OracleConnection.DCN_QUERY_CHANGE_NOTIFICATION, "true");

//this is what does the actual registering on the db end

oracle.jdbc.dcn.DatabaseChangeRegistration dbChangeRegistration= oracleConnection.registerDatabaseChangeNotification(dbProperties);

//now you can add the listener created before my EDIT

listener = new DBListener(this);

dbChangeRegistration.addListener(listener);

//now you need to add whatever tables you want to monitor

Statement stmt = oracleConnection.createStatement();

//associate the statement with the registration:

((OracleStatement) stmt).setDatabaseChangeRegistration(dbChangeRegistration); //look up the documentation to this method [http://docs.oracle.com/cd/E11882_01/appdev.112/e13995/oracle/jdbc/OracleStatement.html#setDatabaseChangeRegistration_oracle_jdbc_dcn_DatabaseChangeRegistration_]

ResultSet rs = stmt.executeQuery(sql); //you have to execute the query to link it to the statement for it to be monitored

while (rs.next()) { ...do sth with the results if interested... }

//see what tables are being monitored

String[] tableNames = dbChangeRegistration.getTables();

for (int i = 0; i < tableNames.length; i++) {

System.out.println(tableNames[i]    + " has been registered.");

}

rs.close();

stmt.close();

}

此示例不包含try-catch子句或任何异常处理。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值