數(shù)據(jù)庫分庫

2019-04-04 17:40 更新

WTM框架支持自動選擇讀寫分離的數(shù)據(jù)庫,以及根據(jù)條件動態(tài)使用不同的數(shù)據(jù)庫連接

讀寫分離
框架會自動識別ConnectionString中以下劃線+數(shù)字結(jié)尾的key值,作為只讀庫,比如下面的定義:
  1. "ConnectionStrings": [
  2. {
  3. "Key": "default",
  4. "Value": "Server=(localdb)\\mssqllocaldb;Database=demo;Trusted_Connection=True;MultipleActiveResultSets=true"
  5. },
  6. {
  7. "Key": "default_1",
  8. "Value": "Server=(localdb)\\mssqllocaldb;Database=demo1;Trusted_Connection=True;MultipleActiveResultSets=true"
  9. },
  10. {
  11. "Key": "default_2",
  12. "Value": "Server=(localdb)\\mssqllocaldb;Database=demo2;Trusted_Connection=True;MultipleActiveResultSets=true"
  13. },
  14. {
  15. "Key": "default_3",
  16. "Value": "Server=(localdb)\\mssqllocaldb;Database=demo3;Trusted_Connection=True;MultipleActiveResultSets=true"
  17. },
  18. ]

這個配置文件定義了四個連接字符串,default是寫庫,default_1,default_2,default_3是三個只讀庫

框架會默認(rèn)在所有標(biāo)記了HttpPost的Controller方法中使用寫庫來創(chuàng)建DataContext,而在其他方法中隨機(jī)選擇一個讀庫

指定連接字符串

如果框架的默認(rèn)實現(xiàn)不能滿足需求,可以使用FixConnection屬性來指定連接字符串,比如下面的Controller

  1. [FixConnection(DBOperationEnum.Read, CsName = "test")]
  2. [HttpPost]
  3. public IActionResult Create()
  4. {
  5. var testDc = this.DC;
  6. return PartialView();
  7. }

通過在方法上加FixConnection,我們指定這個方法里的DC應(yīng)該使用連接字符串是test開頭的只讀庫,框架會去尋找比如test_1,test_2,test_3...這種key值的連接字符串,如果找不到就會使用叫test的連接字符串,如果仍然找不到,則會使用默認(rèn)的default

另一種指定連接字符串的方法是不使用Controller和VM中已經(jīng)生成的DC,而是直接使用指定連接字符串新實例化一個DataContext,比如

  1. [HttpPost]
  2. public IActionResult Create()
  3. {
  4. var testDc = new DataContext("test_2");
  5. return PartialView();
  6. }

以上代碼指定使用key值為test_2的連接字符串來創(chuàng)建一個新的DataContext

動態(tài)選擇連接字符串

框架可以根據(jù)頁面?zhèn)鬟f過來的數(shù)據(jù),或者session里的信息等動態(tài)選擇需要連接的數(shù)據(jù)庫,請看以下代碼

  1. public class Program
  2. {
  3. public static void Main(string[] args)
  4. {
  5. BuildWebHost(args).Run();
  6. }
  7. public static IWebHost BuildWebHost(string[] args) =>
  8. WebHost.CreateDefaultBuilder(args)
  9. .ConfigureServices(x =>
  10. {
  11. x.AddFrameworkService(CsSector: CSSelector);
  12. x.AddLayui();
  13. })
  14. .Configure(x =>
  15. {
  16. x.UseFrameworkService();
  17. })
  18. .Build();
  19. public static string CSSelector(ActionExecutingContext context)
  20. {
  21. var userinfo = (context.Controller as BaseController).LoginUserInfo;
  22. if(userinfo == null)
  23. {
  24. return "default";
  25. }
  26. else
  27. {
  28. if (userinfo.ITCode.StartsWith("a"))
  29. {
  30. return "user1";
  31. }
  32. else
  33. {
  34. return "user2";
  35. }
  36. }
  37. }
  38. }

上面的代碼將一個用于選擇連接字符串的函數(shù)傳給了AddFrameworkService,這個函數(shù)根據(jù)當(dāng)前登錄用戶來選擇使用的數(shù)據(jù)庫。沒有登陸時用default,用戶名以a開頭時用user1庫,其他用user2庫


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號