- 数据库配置读写分离
- 项目设置负载均衡查询,注意.net5下面全程使用依赖注入,摒弃掉new事例的方式
1.数据库配置读写分离 具体查看 https://www.cnblogs.com/LZXX/p/13044841.html
1.设置一个共享文件夹,设置文件夹EveryOn 完全控制权限---最大的开发权限 配
2.配置置分发服务器
3.配置发布
4.配置订阅
5.需要注意的是每次表结构更改需要重新更新一下订阅的从库
2.项目设置负载均衡查询 具体思路就是数据库设置好了读写分离,项目增删改使用主库,查询的时候负载均衡去查询多个从库
例如控制器里面的一个查询方法如何进行负载均衡
1.控制器下的查询方法
2.增加查询枚举类
3.在相关的查询方法父类里面进行判断枚举
4.设置配置文件依赖注入,主库包含一个数据库链接,从库以逗号分割多个从库数据库链接
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "AllowedHosts": "*", "ConnectionStrings": { "WriteConnection": "Server=DESKTOP-63QE7M1;Database=ZhaoxiNet5DbInfoTest;Trusted_Connection=True;", "ReadConnectionList": [ "Server=DESKTOP-63QE7M1;Database=ZhaoxiNet5DbInfo0001;Trusted_Connection=True;", "Server=DESKTOP-63QE7M1;Database=ZhaoxiNet5DbInfo0002;Trusted_Connection=True;", "Server=DESKTOP-63QE7M1;Database=ZhaoxiNet5DbInfo0003;Trusted_Connection=True;" ] } }
在satup.cs configservice() 增加: services.Configure<DBConnectionOption>(Configuration.GetSection("ConnectionStrings"));//注入多个链接
public class DBConnectionOption { /// <summary> /// 主库的链接字符串 /// </summary> public string WriteConnection { get; set; } /// <summary> /// 一堆从库的链接字符串 /// </summary> public List<string> ReadConnectionList { get; set; } }
依赖注入实现
5.最后在具体查询的dbcontext类里面进行判断是主还是从,主库就正常增删改查,从库就设置负载均衡
public class DbContextFactory : IDbContextFactory { private DBConnectionOption dBConnections = null; private DbContext _Context = null; //构造函数 public DbContextFactory(DbContext context, IOptions<DBConnectionOption> options) { _Context = context; dBConnections = options.Value; } /// <summary> /// 在这里的主要职责是要根据不同的操作要选择不同的链接字符串; /// /// 字符串分为两类:1.一个字符串(主库) 2.多个字符串 /// </summary> /// <param name="readAndWriteEnum"></param> /// <returns></returns> public DbContext CreateDbCotnext(ReadAndWriteEnum readAndWriteEnum) { switch (readAndWriteEnum) { case ReadAndWriteEnum.Read: //这里是做做查询 return ToRead(); case ReadAndWriteEnum.Write: //增删改 return ToWrite(); default: throw new Exception("枚举值错误"); } } private static int staticIndex = 0; private DbContext ToRead() { //这里就可以选择一下使用哪一个链接字符串; #region MyRegion //1.随机策略 { int index = new Random().Next(0, dBConnections.ReadConnectionList.Count); string connectionString = dBConnections.ReadConnectionList[index]; //需要改善 return _Context.ToWriteOrRead(connectionString); } #endregion #region 轮训策略---这里没有支持多线程---大家要考虑一下线程安全问题; { //string connectionString = string.Empty; //if (staticIndex == dBConnections.ReadConnectionList.Count - 1) //{ // connectionString = dBConnections.ReadConnectionList[staticIndex]; // staticIndex = 0; //} //else //{ // connectionString = dBConnections.ReadConnectionList[staticIndex]; // staticIndex++; //} //return _Context.ToWriteOrRead(connectionString); } #endregion #region 权重策略 #endregion } private DbContext ToWrite() { string connectionString = dBConnections.WriteConnection; return _Context.ToWriteOrRead(connectionString); } }