[ 2021 年更新]
对于阅读本文的任何人,我可以推荐查看AceBase。AceBase 是一个实时数据库,可在浏览器和服务器数据库之间轻松存储和同步。它在浏览器中使用 IndexedDB,在服务器端使用自己的二进制 db 格式或 SQL Server/SQLite 存储。MySQL 存储也在路线图上。重新连接时会同步离线编辑,并通过 websocket (FAST!) 实时通知客户端远程数据库更改。
最重要的是,AceBase 有一个称为“实时数据代理”的独特功能,它允许您对内存中对象的所有更改进行持久化并同步到本地和服务器数据库,这样您就可以完全忘记数据库编码,并编程就好像您只使用本地对象一样。无论您是在线还是离线。
以下示例展示了如何在浏览器中创建本地 IndexedDB 数据库,如何连接到与本地数据库同步的远程数据库服务器,以及如何创建实时数据代理以完全消除进一步的数据库编码。
const { AceBaseClient } = require('acebase-client');
const { AceBase } = require('acebase');
// Create local database with IndexedDB storage:
const cacheDb = AceBase.WithIndexedDB('mydb-local');
// Connect to server database, use local db for offline storage:
const db = new AceBaseClient({ dbname: 'mydb', host: 'db.myproject.com', port: 443, https: true, cache: { db: cacheDb } });
// Wait for remote database to be connected, or ready to use when offline:
db.ready(async () => {
// Create live data proxy for a chat:
const emptyChat = { title: 'New chat', messages: {} };
const proxy = await db.ref('chats/chatid1').proxy(emptyChat); // Use emptyChat if chat node doesn't exist
// Get object reference containing live data:
const chat = proxy.value;
// Update chat's properties to save to local database,
// sync to server AND all other clients monitoring this chat in realtime:
chat.title = `Changing the title`;
chat.messages.push({
from: 'ewout',
sent: new Date(),
text: `Sending a message that is stored in the database and synced automatically was never this easy!` +
`This message might have been sent while we were offline. Who knows!`
});
// To monitor realtime changes to the chat:
chat.onChanged((val, prev, isRemoteChange, context) => {
if (val.title !== prev.title) {
console.log(`Chat title changed to ${val.title} by ${isRemoteChange ? 'us' : 'someone else'}`);
}
});
});
有关更多示例和文档,请参阅npmjs.com上的 AceBase实时数据库引擎