-
Notifications
You must be signed in to change notification settings - Fork 172
/
Copy pathEFCoreCrud.cs
479 lines (445 loc) · 20 KB
/
EFCoreCrud.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
using BenchmarkDotNet.Attributes;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using ShardingCore;
using ShardingCore.Extensions;
using ShardingCore6x.NoShardingDbContexts;
using ShardingCore6x.ShardingDbContexts;
using System.Diagnostics;
namespace ShardingCore6x
{
public class EFCoreCrud
{
private readonly DefaultDbContext _defaultDbContext;
private readonly DefaultShardingDbContext _defaultShardingDbContext;
private readonly ServiceCollection services;
public EFCoreCrud()
{
services = new ServiceCollection();
services.AddDbContext<DefaultDbContext>(o => o
//.UseMySql("server=127.0.0.1;port=3306;database=db1;userid=root;password=L6yBtV6qNENrwBy7;", new MySqlServerVersion(new Version()))
.UseSqlServer("Data Source=localhost;Initial Catalog=db1;Integrated Security=True;")
, ServiceLifetime.Transient, ServiceLifetime.Transient);
services.AddLogging();
services.AddShardingDbContext<DefaultShardingDbContext>(ServiceLifetime.Transient, ServiceLifetime.Transient)
.UseRouteConfig(o =>
{
o.AddShardingTableRoute<OrderVirtualTableRoute>();
})
.UseConfig(op =>
{
op.UseShardingQuery((conStr, builder) =>
{
builder.UseSqlServer(conStr);
//builder.UseMySql(conStr, new MySqlServerVersion(new Version()));
});
op.UseShardingTransaction((connection, builder) =>
{
builder.UseSqlServer(connection);
//builder.UseMySql(connection, new MySqlServerVersion(new Version()));
});
op.AddDefaultDataSource("ds0",
"Data Source=localhost;Initial Catalog=db2;Integrated Security=True;");
//op.AddDefaultDataSource("ds0", "server=127.0.0.1;port=3306;database=db2;userid=root;password=L6yBtV6qNENrwBy7;");
}).AddShardingCore();
var buildServiceProvider = services.BuildServiceProvider();
buildServiceProvider.UseAutoTryCompensateTable();
ICollection<Order> orders = new LinkedList<Order>();
using (var scope = buildServiceProvider.CreateScope())
{
var defaultShardingDbContext = scope.ServiceProvider.GetService<DefaultDbContext>();
defaultShardingDbContext.Database.EnsureCreated();
if (!defaultShardingDbContext.Set<Order>().Any())
{
var begin = DateTime.Now.Date.AddDays(-8);
var now = DateTime.Now;
var current = begin;
int i = 0;
var x = new OrderStatusEnum[] { OrderStatusEnum.Failed, OrderStatusEnum.NotPay, OrderStatusEnum.Succeed };
while (current < now)
{
orders.Add(new Order()
{
Id = i.ToString(),
Amount = i,
Body = $"今天购买了的东西呀:{i}",
CreateTime = current,
Remark = $"这是我的备注哦备注哦备注哦:{i}",
Payer = Guid.NewGuid().ToString("n"),
OrderStatus = x[i % 3]
});
i++;
current = current.AddMilliseconds(100);
}
var sp = Stopwatch.StartNew();
defaultShardingDbContext.BulkInsert<Order>(orders.ToList());
sp.Stop();
Console.WriteLine($"批量插入订单数据:{orders.Count},用时:{sp.ElapsedMilliseconds}");
}
}
using (var scope = buildServiceProvider.CreateScope())
{
var defaultShardingDbContext = scope.ServiceProvider.GetService<DefaultShardingDbContext>();
if (!defaultShardingDbContext.Set<Order>().Any())
{
var sp = Stopwatch.StartNew();
var bulkShardingEnumerable = defaultShardingDbContext.BulkShardingTableEnumerable(orders.ToList());
foreach (var keyValuePair in bulkShardingEnumerable)
{
keyValuePair.Key.BulkInsert(keyValuePair.Value.ToList());
}
sp.Stop();
Console.WriteLine($"批量插入订单数据:{orders.Count},用时:{sp.ElapsedMilliseconds}");
}
}
_defaultDbContext = buildServiceProvider.GetService<DefaultDbContext>();
_defaultShardingDbContext = buildServiceProvider.GetService<DefaultShardingDbContext>();
}
[Params(10)]
public int N;
//private static readonly string[] aa = new string[] { "a", "b", "c", "d" };
//[Benchmark]
//public void ShardingCreateDbContextFirstOrDefault()
//{
// for (int i = 0; i < N; i++)
// {
// var routeTail = _routeTailFactory.Create(aa[i % 4]);
// var dbContext = _defaultShardingDbContext.GetDbContext("ds0", true, routeTail);
// }
//}
//[Benchmark]
//public void ActualConnectionStringManager()
//{
// for (int i = 0; i < N; i++)
// {
// var connectionString = _actualConnectionStringManager.GetConnectionString("ds0", false);
// }
//}
//[Benchmark]
//public async Task CreateQueryable()
//{
// for (int i = 0; i < N; i++)
// {
// var next = new Random().Next(1000000, 3000000).ToString();
// var queryable = _defaultShardingDbContext.Set<Order>().Where(o => o.Id == next);
// }
//}
//[Benchmark]
//public async Task DataSourceRouteRuleEngineFactory()
//{
// for (int i = 0; i < N; i++)
// {
// var next = new Random().Next(1000000, 3000000).ToString();
// var queryable = _defaultShardingDbContext.Set<Order>().Where(o => o.Id == next);
// _dataSourceRouteRuleEngineFactory.Route(queryable);
// }
//}
//[Benchmark]
//public async Task TableRouteRuleEngineFactory()
//{
// for (int i = 0; i < N; i++)
// {
// var next = new Random().Next(1000000, 3000000).ToString();
// var queryable = _defaultShardingDbContext.Set<Order>().Where(o => o.Id == next);
// _tableRouteRuleEngineFactory.Route(queryable);
// }
//}
//[Benchmark]
//public async Task ShardingCreateStreamMergeContext()
//{
// for (int i = 0; i < N; i++)
// {
// var next = new Random().Next(1000000, 3000000).ToString();
// var queryable = _defaultShardingDbContext.Set<Order>().Where(o => o.Id == next);
// var firstOrDefaultAsync = _streamMergeContextFactory.Create(queryable, _defaultShardingDbContext);
// }
//}
//[Benchmark]
//public async Task NoRouteParseCache()
//{
// for (int i = 0; i < N; i++)
// {
// var next = new Random().Next(1, 3000000).ToString();
// var queryable = _defaultShardingDbContext.Set<Order>().Where(o => o.Id == next);
// _virtualTable.RouteTo(new ShardingTableRouteConfig(queryable: queryable));
// }
//}
//[Benchmark]
//public async Task ShardingFirstOrDefaultAsync()
//{
// for (int i = 0; i < N; i++)
// {
// var queryable = _defaultShardingDbContext.Set<Order>().Where(o => o.Id == "1000");
// _virtualTable.RouteTo(new ShardingTableRouteConfig(queryable: queryable));
// var queryable1 = _defaultShardingDbContext.Set<Order>().Where(o => o.Id == "1000004");
// _virtualTable.RouteTo(new ShardingTableRouteConfig(queryable: queryable1));
// }
//}
//[Benchmark]
//public async Task NoShardingFirstOrDefaultAsync()
//{
// for (int i = 0; i < N; i++)
// {
// var next = new Random().Next(1, 7000000).ToString();
// var firstOrDefaultAsync = await _defaultDbContext.Set<Order>().FirstOrDefaultAsync(o => o.Id == next);
// }
//}
//[Benchmark]
//public async Task ShardingFirstOrDefaultAsync()
//{
// for (int i = 0; i < N; i++)
// {
// var next = new Random().Next(1, 7000000).ToString();
// var firstOrDefaultAsync = await _defaultShardingDbContext.Set<Order>().FirstOrDefaultAsync(o => o.Id == next);
// }
//}
[Benchmark]
public async Task NoShardingIndexFirstOrDefaultAsync()
{
for (int i = 0; i < N; i++)
{
var next = new Random().Next(1000000, 7000000).ToString();
var firstOrDefaultAsync = await _defaultDbContext.Set<Order>().FirstOrDefaultAsync(o => o.Id == next);
}
}
[Benchmark]
public async Task ShardingIndexFirstOrDefaultAsync()
{
for (int i = 0; i < N; i++)
{
var next = new Random().Next(1000000, 7000000).ToString();
var firstOrDefaultAsync = await _defaultShardingDbContext.Set<Order>().FirstOrDefaultAsync(o => o.Id == next);
}
}
[Benchmark]
public async Task NoShardingNoIndexFirstOrDefaultAsync()
{
for (int i = 0; i < N; i++)
{
var next = new Random().Next(1000000, 7000000);
var firstOrDefaultAsync1 = await _defaultDbContext.Set<Order>().FirstOrDefaultAsync(o => o.Amount == next);
}
}
[Benchmark]
public async Task ShardingNoIndexFirstOrDefaultAsync()
{
for (int i = 0; i < N; i++)
{
var next = new Random().Next(1000000, 7000000);
var firstOrDefaultAsync1 = await _defaultShardingDbContext.Set<Order>().FirstOrDefaultAsync(o => o.Amount == next);
}
}
[Benchmark]
public async Task NoShardingNoIndexCountAsync()
{
for (int i = 0; i < N; i++)
{
var next = new Random().Next(1000000, 7000000);
var firstOrDefaultAsync1 = await _defaultDbContext.Set<Order>().CountAsync(o => o.Amount == next);
}
}
[Benchmark]
public async Task ShardingNoIndexCountAsync()
{
for (int i = 0; i < N; i++)
{
var next = new Random().Next(1000000, 7000000);
var firstOrDefaultAsync1 = await _defaultShardingDbContext.Set<Order>().CountAsync(o => o.Amount == next);
}
}
//[Benchmark]
//public async Task NoShardingNoIndexFirstOrDefaultAsync0w()
//{
// for (int i = 0; i < N; i++)
// {
// var firstOrDefaultAsync = await _defaultDbContext.Set<Order>().FirstOrDefaultAsync(o => o.Amount == 0);
// }
//}
//[Benchmark]
//public async Task ShardingNoIndexFirstOrDefaultAsync0w()
//{
// for (int i = 0; i < N; i++)
// {
// var firstOrDefaultAsync = await _defaultShardingDbContext.Set<Order>().FirstOrDefaultAsync(o => o.Amount == 0);
// }
//}
//[Benchmark]
//public async Task NoShardingNoIndexFirstOrDefaultAsync99w()
//{
// for (int i = 0; i < N; i++)
// {
// var firstOrDefaultAsync = await _defaultDbContext.Set<Order>().FirstOrDefaultAsync(o => o.Amount == 999999);
// }
//}
//[Benchmark]
//public async Task ShardingNoIndexFirstOrDefaultAsync99w()
//{
// for (int i = 0; i < N; i++)
// {
// var firstOrDefaultAsync = await _defaultShardingDbContext.Set<Order>().FirstOrDefaultAsync(o => o.Amount == 999999);
// }
//}
[Benchmark]
public async Task NoShardingNoIndexLikeToListAsync()
{
for (int i = 0; i < N; i++)
{
var next = new Random().Next(1, 7000000).ToString();
var firstOrDefaultAsync = await _defaultDbContext.Set<Order>().Where(o => o.Body.Contains(next)).ToListAsync();
}
}
[Benchmark]
public async Task ShardingNoIndexLikeToListAsync()
{
for (int i = 0; i < N; i++)
{
var next = new Random().Next(1, 7000000).ToString();
var firstOrDefaultAsync = await _defaultShardingDbContext.Set<Order>().Where(o => o.Body.Contains(next)).ToListAsync();
}
}
[Benchmark]
public async Task NoShardingNoIndexToListAsync()
{
for (int i = 0; i < N; i++)
{
var next = new Random().Next(1, 7000000);
var firstOrDefaultAsync = await _defaultDbContext.Set<Order>().Where(o => o.Amount == next).ToListAsync();
}
}
[Benchmark]
public async Task ShardingNoIndexToListAsync()
{
for (int i = 0; i < N; i++)
{
var next = new Random().Next(1, 7000000);
var firstOrDefaultAsync = await _defaultShardingDbContext.Set<Order>().Where(o => o.Amount == next).ToListAsync();
}
}
//[Benchmark]
//public void ShardingRouteFirstOrDefault()
//{
// for (int i = 0; i < N; i++)
// {
// var next = new Random().Next(1000000, 7000000).ToString();
// var queryable = _defaultShardingDbContext.Set<Order>().Where(o => o.Id == next);
// _virtualTable.RouteTo(new ShardingTableRouteConfig(queryable: queryable));
// }
//}
//private static readonly string[] aa = new string[] { "a", "b", "c", "d" };
//[Benchmark]
//public void ShardingCreateDbContextFirstOrDefault()
//{
// for (int i = 0; i < N; i++)
// {
// var routeTail = _routeTailFactory.Create(aa[i % 4]);
// var dbContext = _defaultShardingDbContext.GetDbContext("ds0", true, routeTail);
// }
//}
//[Benchmark]
//public async Task ShardingWhereFirstOrDefaultAsync()
//{
// for (int i = 0; i < N; i++)
// {
// var next = new Random().Next(1000000, 7000000).ToString();
// var firstOrDefaultAsync = await _defaultShardingDbContext.Set<Order>().Where(o => o.Id == next).FirstOrDefaultAsync();
// }
//}
//[Benchmark]
//public async Task ShardingCreateStreamMergeContext()
//{
// for (int i = 0; i < N; i++)
// {
// var next = new Random().Next(1000000, 7000000).ToString();
// var queryable = _defaultShardingDbContext.Set<Order>().Where(o => o.Id == next);
// var firstOrDefaultAsync = _streamMergeContextFactory.Create(queryable, _defaultShardingDbContext);
// }
//}
//[Benchmark]
//public async Task ShardingCreateEnumerableQuery()
//{
// for (int i = 0; i < N; i++)
// {
// var next = new Random().Next(1000000, 7000000).ToString();
// var queryable = _defaultShardingDbContext.Set<Order>().Where(o => o.Id == next);
// new EnumerableQuery<Order>(queryable.Expression);
// }
//}
//private TResult GenericShardingDbContextMergeExecute<TResult>(IQueryable<Order> queryable)
//{
// //{
// // var queryEntityType = query.GetQueryEntityType();
// //var newStreamMergeEngineType = streamMergeEngineType.MakeGenericType(shardingDbContext.GetType(), queryEntityType);
// //// {
// //// //获取所有需要路由的表后缀
// //// var startNew = Stopwatch.StartNew();
// //// for (int i = 0; i < 10000; i++)
// //// {
// //// var streamEngine = ShardingCreatorHelper.CreateInstance(newStreamMergeEngineType, query, shardingDbContext);
// //// }
// //// startNew.Stop();
// //// var x = startNew.ElapsedMilliseconds;
// //// }
// //{
// // //获取所有需要路由的表后缀
// // var startNew1 = Stopwatch.StartNew();
// // for (int i = 0; i < 10000; i++)
// // {
// // var streamEngine = Activator.CreateInstance(newStreamMergeEngineType, query, shardingDbContext);
// // }
// // startNew1.Stop();
// // var x = startNew1.ElapsedMilliseconds;
// //}
// // var methodName = async ? nameof(IGenericMergeResult.MergeResultAsync) : nameof(IGenericMergeResult.MergeResult);
// // var streamEngineMethod = newStreamMergeEngineType.GetMethod(methodName);
// // if (streamEngineMethod == null)
// // throw new ShardingCoreException($"cant found InMemoryAsyncStreamMergeEngine method [{methodName}]");
// // var @params = async ? new object[] { cancellationToken } : new object[0];
// //}
// {
// var queryEntityType = queryable.Expression.GetQueryEntityType();
// var newStreamMergeEngineType = streamMergeEngineType.MakeGenericType(shardingDbContext.GetType(), queryEntityType);
// var streamEngine = Activator.CreateInstance(newStreamMergeEngineType, query, shardingDbContext);
// var methodName = async ? nameof(IGenericMergeResult.MergeResultAsync) : nameof(IGenericMergeResult.MergeResult);
// var streamEngineMethod = newStreamMergeEngineType.GetMethod(methodName);
// if (streamEngineMethod == null)
// throw new ShardingCoreException($"cant found InMemoryAsyncStreamMergeEngine method [{methodName}]");
// var @params = async ? new object[] { cancellationToken } : new object[0];
// return (TResult)streamEngineMethod.MakeGenericMethod(new Type[] { queryEntityType }).Invoke(streamEngine, @params);
// }
//}
//[Benchmark]
//public async Task NoShardingNoTrackingFirstOrDefaultAsync()
//{
// for (int i = 0; i < N; i++)
// {
// var next = new Random().Next(1, 3000000).ToString();
// var firstOrDefaultAsync = await _defaultDbContext.Set<Order>().AsNoTracking().FirstOrDefaultAsync(o => o.Id == next);
// }
//}
//[Benchmark]
//public async Task ShardingNoTrackingFirstOrDefaultAsync()
//{
// for (int i = 0; i < N; i++)
// {
// var next = new Random().Next(1, 3000000).ToString();
// var firstOrDefaultAsync = await _defaultShardingDbContext.Set<Order>().AsNoTracking().FirstOrDefaultAsync(o => o.Id == next);
// }
//}
//[Benchmark]
//public async Task NoShardingCountAsync()
//{
// for (int i = 0; i < N; i++)
// {
// var firstOrDefaultAsync = await _defaultDbContext.Set<Order>().CountAsync();
// }
//}
//[Benchmark]
//public async Task ShardingCountAsync()
//{
// for (int i = 0; i < N; i++)
// {
// var firstOrDefaultAsync = await _defaultShardingDbContext.Set<Order>().CountAsync();
// }
//}
}
}