当前位置: 首页 > news >正文

C#+SqlSugar实现主从库读写分离

在使用 **SqlSugar** 进行分库操作时,可以通过配置多个数据库连接,并根据业务逻辑动态切换数据库。以下是一个完整的分库示例,展示如何实现分库功能。

---

### **1. 安装 NuGet 包**
安装 `SqlSugarCore`:
```bash
dotnet add package SqlSugarCore
```

---

### **2. 分库场景**
假设有两个数据库:
- **主库**:用于写操作。
- **从库**:用于读操作。

---

### **3. 配置数据库连接**
在 `appsettings.json` 中配置多个数据库连接:
```json
{
  "ConnectionStrings": {
    "Master": "Server=master_server;Database=master_db;User Id=your_user;Password=your_password;",
    "Slave": "Server=slave_server;Database=slave_db;User Id=your_user;Password=your_password;"
  }
}
```

---

### **4. 创建数据库上下文**
创建一个 `SqlSugarContext` 类,用于管理主库和从库的连接。

```csharp
using Microsoft.Extensions.Configuration;
using SqlSugar;

public class SqlSugarContext
{
    private readonly IConfiguration _configuration;
    private readonly SqlSugarClient _masterDb;
    private readonly SqlSugarClient _slaveDb;

    public SqlSugarContext(IConfiguration configuration)
    {
        _configuration = configuration;

        // 初始化主库
        _masterDb = new SqlSugarClient(new ConnectionConfig
        {
            ConnectionString = _configuration["ConnectionStrings:Master"],
            DbType = DbType.SqlServer,
            IsAutoCloseConnection = true,
            InitKeyType = InitKeyType.Attribute
        });

        // 初始化从库
        _slaveDb = new SqlSugarClient(new ConnectionConfig
        {
            ConnectionString = _configuration["ConnectionStrings:Slave"],
            DbType = DbType.SqlServer,
            IsAutoCloseConnection = true,
            InitKeyType = InitKeyType.Attribute
        });
    }

    // 获取主库
    public SqlSugarClient MasterDb => _masterDb;

    // 获取从库
    public SqlSugarClient SlaveDb => _slaveDb;
}
```

---

### **5. 使用分库**
在业务逻辑中,根据需要切换主库和从库。

#### **5.1 写入主库**
```csharp
public class UserService
{
    private readonly SqlSugarContext _dbContext;

    public UserService(SqlSugarContext dbContext)
    {
        _dbContext = dbContext;
    }

    public async Task AddUserAsync(User user)
    {
        await _dbContext.MasterDb.Insertable(user).ExecuteCommandAsync();
    }
}
```

#### **5.2 读取从库**
```csharp
public class UserService
{
    private readonly SqlSugarContext _dbContext;

    public UserService(SqlSugarContext dbContext)
    {
        _dbContext = dbContext;
    }

    public async Task<List<User>> GetUsersAsync()
    {
        return await _dbContext.SlaveDb.Queryable<User>().ToListAsync();
    }
}
```

---

### **6. 主程序**
在 `Program.cs` 中初始化 `SqlSugarContext` 并使用分库功能。

```csharp
using Microsoft.Extensions.Configuration;
using System.IO;
using System.Threading.Tasks;

public class Program
{
    public static async Task Main(string[] args)
    {
        // 读取配置文件
        var configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .Build();

        // 初始化数据库上下文
        var dbContext = new SqlSugarContext(configuration);

        // 使用主库写入数据
        var userService = new UserService(dbContext);
        await userService.AddUserAsync(new User { Name = "John", Age = 30 });

        // 使用从库读取数据
        var users = await userService.GetUsersAsync();
        foreach (var user in users)
        {
            Console.WriteLine($"User: {user.Name}, Age: {user.Age}");
        }
    }
}
```

---

### **7. 动态分库**
如果需要根据条件动态切换数据库,可以在 `SqlSugarContext` 中添加一个方法,根据条件返回对应的数据库连接。

#### **7.1 修改 `SqlSugarContext`**
```csharp
public SqlSugarClient GetDb(bool isWriteOperation)
{
    return isWriteOperation ? _masterDb : _slaveDb;
}
```

#### **7.2 使用动态分库**
```csharp
public class UserService
{
    private readonly SqlSugarContext _dbContext;

    public UserService(SqlSugarContext dbContext)
    {
        _dbContext = dbContext;
    }

    public async Task AddUserAsync(User user)
    {
        var db = _dbContext.GetDb(isWriteOperation: true); // 使用主库
        await db.Insertable(user).ExecuteCommandAsync();
    }

    public async Task<List<User>> GetUsersAsync()
    {
        var db = _dbContext.GetDb(isWriteOperation: false); // 使用从库
        return await db.Queryable<User>().ToListAsync();
    }
}
```

---

### **8. 总结**
通过以上步骤,您可以实现基于 SqlSugar 的分库功能:
1. 配置多个数据库连接。
2. 使用 `SqlSugarContext` 管理主库和从库。
3. 在业务逻辑中根据需要切换数据库。

这种分库方式适用于读写分离、多租户等场景,能够有效提升系统的性能和扩展性。

相关文章:

  • 面向长范围交互式 LLM 智体的强化学习
  • 动画云渲染平台技术评估与优选策略
  • 机器学习基本篇
  • 领域驱动设计叕创新,平安保险申请DDD专利
  • Java并发编程8--线程
  • React + TypeScript+ Vite 配置路径别名和vscode智能路径提示
  • AI时代:前端开发的职业发展路径拓宽
  • vsan数据恢复—vsan缓存盘故障导致虚拟磁盘文件丢失的数据恢复案例
  • 在线考试系统(代码+数据库+LW)
  • ubuntu24基于虚拟机无法从主机拖拽文件夹
  • React通用登录/注销功能实现方案(基于shadcn/ui)
  • Android 虚拟机与ClassLoader类加载笔记
  • 【工具插件类教学】实现运行时2D物体交互的利器Runtime2DTransformInteractor
  • 解压rar格式的软件有哪些?8种方法(Win/Mac/手机/网页端)
  • 新型基于Go语言的恶意软件利用Telegram作为C2通信渠道
  • Postman接口测试的cookie,token,session....鉴权
  • PyCharm 中的 %reset -f 功能:一键重置控制台变量
  • 2024 年 CSDN 博客之星年度评选:技术创作与影响力的碰撞(统计时间2025-02-17 11:06:06)
  • seata集成nacos
  • 基数排序【C语言】
  • 手机网站图片切换/百度app推广方法
  • 全屏网站 内页怎么做/石家庄今日头条新闻
  • 超级折扣2WordPress/网站为什么要seo?
  • 兰溪网站建设学徒/互联网营销师考证多少钱
  • 网页制作及网站建设/搜索广告和信息流广告区别
  • 台州做鞋子网站/北京seo收费