现代Web应用中,前后端数据同步是关键环节。本文将详细介绍基于Electric的同步方案及其实现细节。
采用PostgreSQL作为数据库存储方案,通过RESTful API对外提供数据访问接口。同时建立SSE连接通道,确保数据变更时能实时推送给前端。

electric.ax/docs/sync/a…
前端通过Electric实现本地数据存储与管理,利用RESTful API获取后端数据,并借助SSE连接接收实时推送。核心使用@electric-sql/client库中的Shape和ShapeStream组件。
import { Shape, ShapeStream } from '@electric-sql/client'export interface IElectricShapeOption {
authorization: string
table: string
where: string
subscribe?: boolean
columns?: string[]
}export const createShapeStreamOptions = (option: IElectricShapeOption) => {
const { subscribe = true } = option
return {
// 后端接口地址
url: `${import.meta.env.VITE_APP_API_BASEURL}api/v1/shape`,
headers: {
Authorization: option.authorization,
},
params: {
table: option.table, // 同步的表名
where: option.where, // 同步的条件
columns: option.columns, // 需要同步的列,不设置就是同步所有的 设置了就只同步指定的列
},
subscribe, // 是否订阅实时数据推送,默认为 true
liveSse: true, // 是否使用 sse 连接,默认为 true 开启 sse 连接后会自动处理连接断开和重连逻辑
}
}async function useElectricShape(option: IElectricShapeOption) {
const rows = ref() const stream = new ShapeStream(createShapeStreamOptions(option))
const shape = new Shape(stream)
rows.value = await shape.rows as T[] shape.subscribe((callback) => {
rows.value = callback.rows as T[]
}) const destroy = async () => {
shape.unsubscribeAll()
} return { rows, destroy }
}
Electric同步方案兼顾实时性与易用性,通过合理优化可满足各类业务场景的数据同步需求。