應用常用 Data Cache 提升效能,但快取與資料庫資料易不一致。傳統做法:使用者手動刷新或定時輪詢,皆有延遲或遺漏風險。Oracle 10g R2 引入 Database Change Notification (DCN),資料異動時主動推送通知,徹底解決快取同步難題。
using System;
using System.Data;
using System.Threading;
using Oracle.DataAccess.Client;
class Program {
static bool notificationReceived = false;
static void Main() {
string sql = "SELECT FIRST_NAME, LAST_NAME, SALARY FROM EMPLOYEES WHERE EMPLOYEE_ID = 149";
string constr = "User Id=hr;Password=hr;Data Source=oramag;Pooling=false";
using (OracleConnection con = new OracleConnection(constr)) {
con.Open();
using (OracleCommand cmd = new OracleCommand(sql, con)) {
OracleDependency dep = new OracleDependency(cmd);
dep.OnChange += OnDatabaseNotification;
cmd.ExecuteNonQuery();
while (!notificationReceived) {
Console.WriteLine("Waiting for notification...");
Thread.Sleep(2000);
}
}
}
Console.WriteLine("Press ENTER to exit...");
Console.ReadLine();
}
static void OnDatabaseNotification(object src, OracleNotificationEventArgs args) {
Console.WriteLine("Database Change Notification received!");
DataTable dt = args.Details;
Console.WriteLine("Resource {0} has changed.", dt.Rows[0]["ResourceName"]);
notificationReceived = true;
}
}
GRANT CHANGE NOTIFICATION TO HR;Oracle.DataAccess.dllusing System.Threading; using System.Data; using Oracle.DataAccess.Client;Waiting for notification...UPDATE EMPLOYEES SET SALARY=SALARY+10 WHERE EMPLOYEE_ID=149; COMMIT;Database Change Notification received! Resource HR.EMPLOYEES has changed.DCN 讓快取同步即時、被動式輪詢成為歷史,極大提升應用資料一致性與使用者體驗。