您现在的位置是:首页 >学无止境 >ShardingCore读写分离网站首页学无止境
ShardingCore读写分离
1、安装插件
参考链接:ShardingCore安装笔记_Three Big Stones的博客-CSDN博客
2、配置主从数据库,具体步骤自行搜索查询
3、搭建项目
开发环境:Visual studio 项目模板:Asp.Net Core Web Api 框架:.Net5
4、添加实体类、数据库上下文
参考链接:ShardingCore分库实践_Three Big Stones的博客-CSDN博客
5、配置启动类
在启动类中配置读写分离,具体参考如下代码:
using Microsoft.EntityFrameworkCore;
using ShardingCore;
using ShardingCore.Sharding.ReadWriteConfigurations;
using ShardingTableDemo;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddShardingDbContext<MyDbContext>().UseRouteConfig(op =>
{
op.AddShardingTableRoute<SysUserVirtualTableRoute>();
op.AddShardingTableRoute<OrderVirtualTableRoute>();
}).UseConfig(op =>
{
op.ThrowIfQueryRouteNotMatch = false;
op.UseShardingQuery((conStr, bd) =>
{
bd.UseMySql(conStr, new MySqlServerVersion(new Version())).UseLoggerFactory(StartupExtension.efLogger);
});
op.UseShardingTransaction((connection, bd) =>
{
bd.UseMySql(connection, new MySqlServerVersion(new Version())).UseLoggerFactory(StartupExtension.efLogger);
});
op.AddDefaultDataSource("ds0", "Server=127.0.0.1;port=3306;user=root;password=panlei1990;database=yzwDb1;");
op.AddReadWriteSeparation(sp =>//读写分离
{
return new Dictionary<string, IEnumerable<string>>
{
{"ds0",new List<string>(){"Server=127.0.0.1;port=3306;user=root;password=panlei1990;database=yzwDb2;","Server=127.0.0.1;port=3306;user=root;password=panlei1990;database=yzwDb1;"}}
};
}, ReadStrategyEnum.Random, true);//读取数据源随机选择从库连接
//}, ReadStrategyEnum.Random, false);//读取数据源随机选择主库连接
//}, ReadStrategyEnum.Loop, true);//依次循环选择从库连接
}).AddShardingCore();
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
var app = builder.Build();
app.UseAuthorization();
app.MapControllers();
using(var scope = app.Services.CreateScope())
{
var myDbContext = scope.ServiceProvider.GetService<MyDbContext>();
myDbContext.Database.EnsureCreated();
}
app.Services.UseAutoTryCompensateTable();
//app.InitSeed();
app.Run();
参数说明:
AddReadWriteSeparation:此方法用于添加读写分离配置项,可配置多个数据源
ReadStrategyEnum:Random枚举,表示随机读取一个数据源;Loop枚举,表示如果有多个数据源的话,将按顺序依次读取数据源。
defaultEnable:true默认读取从库,false默认读取主库
6、新建controller类
增加添加数据接口
[Route("AddOrder")]
[HttpPost]
public async Task<IActionResult> Add(Order order)
{
order.CreationTime = DateTime.Now;
this.dbContext.Set<Order>().Add(order);
var i = this.dbContext.SaveChanges();
return Ok(i);
}
增加查询数据接口
[Route("GetOrder")]
public async Task<IActionResult> GetOrder(string id)
{
//this.dbContext.ReadWriteSeparationWriteOnly();//切换到写库
var order = await this.dbContext.Set<Order>().FirstOrDefaultAsync(x => x.Id == id);
return Ok(order);
}
7、使用postman测试web api
在代码中切换到写库
this.dbContext.ReadWriteSeparationWriteOnly();//切换到写库
在代码中切换到读库
this.dbContext.ReadWriteSeparationReadOnly();//切换到读库
8、结束
读写分离关键点在于Program类中读写分离配置项的配置,以及各项参数的设置,不同的参数设置将会影响读写分离的具体执行策略。