ASP.NET Core中的对象池化技术详解
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.ObjectPool;
using System.Security.Cryptography;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
// DefaultPooledObjectPolicy: 默认的策略,继承抽象类PooledObjectPolicy
builder.Services.TryAddSingleton
builder.Services.TryAddSingleton
{
var provider = serviceProvider.GetRequiredService
var policy = new DefaultPooledObjectPolicy
return provider.Create(policy);
});
builder.Services.TryAddSingleton
var provider = serviceProvider.GetRequiredService
var policy = new PersonPoolPolicy();
return provider.Create(policy);
});
builder.Services.TryAddSingleton
{
var provider = serviceProvider.GetRequiredService
var policy = new StringBuilderPooledObjectPolicy();
return provider.Create(policy);
});
var app = builder.Build();
// config middleware
app.UseMiddleware
app.MapGet("/", () => "Hello rjcql!");
// return the SHA256 hash of a word
http://localhost:5128/hash/xxxx
app.MapGet("/hash/{word}", (string word, ObjectPool
{
var buffer = bufferPool.Get();
try
{
// Set the buffer data to the ASCII values of a word
for (var i = 0; i < word.Length; i++)
{
buffer.Data[i] = (byte)word[i];
}
Span
SHA256.HashData(buffer.Data.AsSpan(0, word.Length), hash);
return "Hash: " + Convert.ToHexString(hash);
}
finally
{
// Data is automatically reset because this type implemented IResettable
bufferPool.Return(buffer);
}
});
app.MapGet("/create/{name}", (string name, ObjectPool
{
var person = personPool.Get();
try
{
person.Id = Guid.NewGuid().ToString("N");
var lastName = person.Name; // 这个是上一个对象的值
person.Name = name;
return $"{person.Id}:{person.Name}, {lastName}";
}
finally
{
// 根据条件回收
personPool.Return(person);
}
});
app.Run();
public class ReusableBuffer : IResettable
{
public byte[] Data { get; } = new byte[1024 * 1024]; // 1 MB
public bool TryReset()
{
Array.Clear(Data);
return true;
}
}
public class Person
{
public string Id { get; set; }
public string Name { get; set; }
}
public class PersonPoolPolicy : PooledObjectPolicy
{
public override Person Create()
{
return new Person { Id = "", Name = "rjcql" };
}
public override bool Return(Person p)
{
if (p.Name != "rjcql")
{
// 不允许其他名称的对象放入对象池
return false;
}
return true;
}
}
///
/// 创建中间件
///
public class BirthdayMiddleware
{
private readonly RequestDelegate _next;
public BirthdayMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context, ObjectPool
{
var stringBuilder = builderPool.Get();
try
{
stringBuilder.Append("Hi");
// 在中间干点啥别的
// await context.Response.WriteAsync(stringBuilder.ToString());
await _next.Invoke(context);
}
finally // 即使出错也要保证归还对象
{
builderPool.Return(stringBuilder);
}
}
}
- .NET Core系列之MemoryCache 初识
- 007手机一键Root(安机网一键Root) v3.0 官方最新版 一键ROOT您的Android手机
- 12306密码被盗了怎么办?12306密码外泄解决方法
- 12个字的qq网名
- 150M迷你型无线路由器怎么设置?
- 192.168.1.1打不开怎么办?路由器192.168.1.1打不开的原因以及解决办法
- 2011年电子报合订本 电子报 编辑部 中文 PDF版 [84M]
- 2015年1月15日小米新旗舰发布会现场图文直播
- 2016.3.1vivo Xplay5新品发布会现场视频直播 优酷直播
- 2016华为P9发布会视频直播地址 4月15日华为P9国行发布会直播