栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在Java中实现数据库侦听器

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在Java中实现数据库侦听器

我有一个针对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子句或任何异常处理。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/470571.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号