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

news/2025/2/18 23:05:40/

在使用 **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. 在业务逻辑中根据需要切换数据库

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


http://www.ppmy.cn/news/1573206.html

相关文章

deepseek部署在本地详细教程

最近&#xff0c;DeepSeek爆火&#xff0c;先进的算法、卓越的能力&#xff0c;表现出众&#xff0c;其凭一己之力推动国内Ai大模型跨越式发展。作为一款现象级的Ai产品&#xff0c;用户量暴增&#xff0c;最近服务器又被攻击&#xff0c;使用DeepSeek&#xff0c;经常出现服务…

Web项目测试专题(七)安全性测试

概述&#xff1a; 安全性测试旨在确保Web应用在设计和实现过程中能够抵御各种安全威胁&#xff0c;保护用户数据和系统资源。 步骤&#xff1a; 身份验证和授权&#xff1a;测试用户登录、权限管理和会话管理机制&#xff0c;确保只有授权用户能够访问特定资源。 数据加密…

【k8s应用管理】kubernetes 安全机制

文章目录 Kubernetes 安全机制安全机制概述认证&#xff08;Authentication&#xff09;认证方式需要认证的访问类型安全性说明证书颁发kubeconfig 文件Service Account&#xff08;SA&#xff09;1. 核心概念2. SA 组成3. Pod 挂载 SA Secret 与 SA 的关系1. Secret 类型2. 查…

vue2.x与vue3.x生命周期的比较

vue2.x 生命周期图示&#xff1a; new Vue() | v Init Events & Lifecycle | v beforeCreate | v created | v beforeMount | v mounted | v beforeUpdate (when data changes) | v updated | v beforeDestroy (when vm.…

【Elasticsearch】标准化器(Normalizers)

Elasticsearch 的标准化器&#xff08;Normalizers&#xff09;是一种特殊的分析器&#xff0c;用于对keyword类型字段的文本进行统一的格式化处理。与普通分析器不同&#xff0c;标准化器只能产生单个标记&#xff08;token&#xff09;&#xff0c;因此它不包含分词器&#x…

python学opencv|读取图像(六十八)使用cv2.Canny()函数实现图像边缘检测

【1】引言 前序学习进程中&#xff0c;在对图像进行边缘识别的基础上&#xff0c;先后进行了边缘轮廓绘制&#xff0c;矩形标注、圆形标注和凸包标注。相关文章包括且不限于&#xff1a; python学opencv|读取图像&#xff08;六十四&#xff09;使用cv2.findContours()函数cv…

git如何下载指定版本

要使用Git下载指定版本&#xff0c;可以通过以下步骤进行操作‌&#xff1a; ‌1. 使用Git命令行下载指定版本‌&#xff1a; 1.1 首先&#xff0c;使用git clone命令克隆整个git库到本地。例如&#xff1a;git clone [库的URL]。这将下载最新的代码到本地。‌ 1.2 进入克隆…

无人机飞手培训机构招生宣传技术详解

无人机飞手培训机构招生宣传技术详解如下&#xff1a; 一、行业背景与需求 1. 广泛应用&#xff1a;无人机在航拍、农业、环境监测、地理测绘、电力巡检、公安、交通、救援等多个领域得到广泛应用&#xff0c;对无人机操作员的需求持续增长。 2. 政策推动&#xff1a;政府对…