1 回答

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