我知道這個問題已經被問過很多次了,但我沒有為我的情況找到一個好的答案。我正在使用 SQLC 生成用于查詢數據庫的方法。使用開始時初始化的一個連接時,一切正?!,F在,我需要在多租戶環境中進行設置,其中每個租戶將具有單獨的數據庫。現在,我想從連接映射(映射[字符串]*sql。DB) 將租戶與數據庫連接連接起來。我的問題是關于在運行時覆蓋/選擇連接。使用一個連接,存儲庫被初始化為:type Repository interface { GetCustomerById(ctx context.Context, id int64) (Customer, error) ListCustomers(ctx context.Context) ([]Customer, error)}type repoSvc struct { *Queries db *sql.DB}func NewRepository(dbconn *sql.DB) Repository { return &repoSvc{ Queries: New(dbconn), db: dbconn, }}customerRepo := customerRepo.NewRepository(conn)GetCustomerById 是 SQLC 生成的方法,連接是數據庫連接如何根據參數(從 Cookie 或上下文)建立連接?
1 回答

冉冉說
TA貢獻1877條經驗 獲得超1個贊
假設您使用的是單獨的數據庫,最簡單的方法是維護 ,其中是區分租戶(例如,包含租戶 ID 的 或)的方式。map[tenantID]Repository
tenantID
string
uint
這樣,您就可以在運行時執行所有操作:
當您需要添加租戶時,只需實例化該租戶并將其添加到地圖中
Repository
當您需要刪除租戶時,只需將其從映射中刪除并關閉數據庫連接
Repository
當您需要對租戶執行查詢時,請在映射中查找相應的,并使用它來執行該租戶的查詢
Repository
如果上述操作可能同時發生,請確保使用某種同步機制來避免訪問映射時的數據爭用(例如 、或 )。sync.Map
sync.RWMutex
如果您有一個存儲租戶及其數據庫連接 URI 的數據庫表,您仍然可以使用此方法:當您需要執行查詢檢查時,如果 缺少 :,則查詢租戶表并將該租戶的 添加到映射中。然后,您可以定期掃描 并刪除任何一段時間未使用的內容。Repository
map
Repository
map
Repository
為了使所有這些更容易,您還可以將整個機器包裝到一個接口中,該接口與接口相同,但每個方法上都接受一個附加參數:MultitenantRepository
Repository
tenantID
type MultitenantRepository interface { GetCustomerById(ctx context.Context, tenant tenantID, id int64) (Customer, error) ListCustomers(ctx context.Context, tenant tenantID) ([]Customer, error) }
這將避免將多租戶設置的所有復雜性暴露給業務邏輯。
- 1 回答
- 0 關注
- 72 瀏覽
添加回答
舉報
0/150
提交
取消