為了實作web上的實時效果和多使用者協作,傳統的技術手段有哪些呢?實時效果,在vue上是可以實作的。而協作效果,就要用websocket等技術進行廣播。
我了解的實時資料庫,是不是結合了這2種功能的?
閱讀了socket.io,google的firebase線上實時資料庫,它功能
Firebase功能
- 實時資料庫- Firebase支援JSON資料,每次更改後,連接配接到它的所有使用者都會收到實時更新。
- 身份驗證- 可以使用匿名,密碼或不同的社交身份驗證。
- 托管主機- 應用程式可以通過安全連接配接部署到Firebase伺服器。
//更多請閱讀:Firebase簡介 -FireBase教程 實時資料庫就是監聽資料更新,然後廣播到所有連接配接的使用者。
而我們現在已經無法連接配接google的任何服務了,是以國内的memfiredb是它的替代品,memfiredb使用了開源supabase這個firebase的替代品,但api接口不一樣,挺遺憾了。但感覺supabase的接口更加接近sql,supabase使用postgres資料庫,它不是一個最新的技術,它在已有的技術基礎上,進行組合,實作了實時資料庫的功能。
有了實時資料庫,據說可以比較簡單地實作一些功能了。最典型的是聊天室了。
暫時就了解這麼多了。
https://firebase.google.cn/docs/reference/js/v8/firebase.database.Reference#onceReference for Reference
https://firebase.google.cn/docs/reference/js/v8/firebase.database.Reference#onceFirebase簡介 -FireBase教程
下面以supabase為例進行驗證。
Reference Documentation | SupabaseReference documentation for the official Supabase client libraries, APIs, and tools.
https://supabase.com/docs/reference
首先在 Supabase
注冊,用git賬号即可。建立項目,例如mapus,再建立一個資料表:userdemo,字段有id和name。為了友善試驗,就這2個字段即可。
supabase項目裡的資料表
<html>
<button onclick="insertdata()">insert</button>
</html>
<!-- 首先引入supabase用戶端,這裡采用cdn引入 -->
<script src="http://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@supabase/supabase-js"></script>
<script>
// 然後把url和秘鑰複制進去可以進行資料庫連結
const { createClient } = supabase
// const _supabase = createClient('url', 'anon_key')
// 下面這個是memfiredb的登入資訊
// const _supabase = createClient('https://ccuon0a5g6h3ij.baseapi.memfiredb.com', 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoiYW5vbiIsImV4cCI6MzIwMjg5Nzg1MiwiaWF0IjoxNjY0OTc3ODUyLCJpc3MiOiJzdXBhYmFzZSJ9.AeqPG73OPjekOxpCak8XBBAqP-wSk57XVQ')
// 下面這個是supabase的登入資訊
const _supabase = createClient('https://gsglmaiuplauvkfjalkg.supabase.co', 'iJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImdzZ2xtYWl1cGxhdXZrZmphbGtnIiwicm9sZSI6ImFub24iLCJpYXQiOjE2NjUwOTgxMjQsImV4cCI6MTk4MDY3NDEyNH0.wDlCSjtYZkGj9AhCSyIIfUbzYzOAF9_4hKKe')
// 進行資料庫api操作
window.onload =async function(){
// 查詢
const { data, error } = await _supabase
.from('userdemo')
.select(`
id,
name
`)
console.log('data ', data)
// realtime
const mySubscription = _supabase
.from('userdemo')
.on('INSERT', payload => {
console.log('Change received!', payload)
})
.subscribe()
}
async function insertdata(){
//插入資料
const { data, error } = await _supabase
.from('userdemo')
.insert({id:7,name:'777'})
console.log('data', data)
}
</script>
{"event":"phx_reply","payload":{"response":{"postgres_changes":[{"id":102486372,"schema":"public","table":"userdemo"}]},"status":"ok"},"ref":"38","topic":"realtime:public:userdemo"}
[
{
"id": 1,
"name": "qin"
},
{
"id": 5,
"name": "888"
},
{
"id": 7,
"name": "777"
}
]