ASP.Net Core 3.1
将以下packages 添加到您的.csproj
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Caching.StackExchangeRedis" Version="3.1.15" />
<PackageReference Include="StackExchange.Redis.Extensions.AspNetCore" Version="7.0.1" />
<PackageReference Include="StackExchange.Redis.Extensions.Core" Version="7.0.1" />
<PackageReference Include="StackExchange.Redis.Extensions.Newtonsoft" Version="7.0.1" />
</ItemGroup>
在Startup.cs 中,您可以通过这种方式注册Redis Client,以便将其注入您的工作流代码。
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// ... other registrations
// Used By : Sample Below : RedisCacheHelperController (Method 1 Only)
services.AddSingleton<IConnectionMultiplexer>(
ConnectionMultiplexer.Connect(DbHelper.GetRedisConnectionHost(Options.IsDevDb()))
);
// Used By : Sample Below : DistributedCacheController (Method 2 Only)
services.AddStackExchangeRedisCache(options =>
options.Configuration = DbHelper.GetRedisConnectionHost(Options.IsDevDb())
);
// ... other registrations
}
}
注意:
DbHelper.GetRedisConnectionHost(Options.IsDevDb()) :>>> 是我根据我的环境为我的 Redis 实例解析连接信息/字符串的方法。你可以在这里有自己的方式,或者如果你愿意的话,你可以在这里硬编码。
方法一
因此,有了上述内容,就可以将 Redis IConnectionMultiplexer 注入您的 Controllers 或 Services。
public class RedisCacheHelperController : ControllerBase
{
private readonly IConnectionMultiplexer multiplexer;
public RedisCacheHelperController(IConnectionMultiplexer multiplexer)
{
this.multiplexer = multiplexer;
}
}
这里有帮助程序 API 来演示如何使用 IConnectionMultiplexer。
public class RedisCacheHelperController : ControllerBase
{
private readonly IConnectionMultiplexer multiplexer;
public RedisCacheHelperController(IConnectionMultiplexer multiplexer)
{
this.multiplexer = multiplexer;
}
[HttpGet("{key}")]
public async Task<IActionResult> GetCacheByKey([FromRoute] string key)
{
var responseContent = await multiplexer.GetDatabase().StringGetAsync(key);
return Content(
responseContent,
Constants.ContentTypeHeaderValueJson // "application/json"
);
}
[HttpPost("{key}")]
public async Task<IActionResult> PostCacheByKey([FromRoute] string key, [FromBody] object data)
{
var requestContent = data.Json(); // JsonConvert.SerializeObject(data)
await multiplexer.GetDatabase().StringSetAsync(key, requestContent);
return Ok(key);
}
[HttpDelete("{key}")]
public async Task<IActionResult> DeleteCacheByKey([FromRoute] string key)
{
await multiplexer.GetDatabase().KeyDeleteAsync(key);
return Ok(key);
}
[HttpGet("CachedKeys")]
public IActionResult GetListCacheKeys([FromQuery] [DefaultValue("*")] string pattern)
{
var keys = multiplexer
.GetServer(multiplexer
.GetEndPoints()
.First())
.Keys(pattern: pattern ?? "*")
.Select(x => x.Get());
return Ok(keys);
}
// ... could have more Reids supported operations here
}
现在上面是您想要访问Redis Client 并执行更多Redis 特定工作的use-case。我们在上面的.csproj 中包含的包Microsoft.Extensions.Caching.StackExchangeRedis 支持Reids 以IDistributedCache 的形式注册和注入。接口IDistributedCache 由Microsoft 定义,支持不同分布式缓存解决方案的基本/通用功能,Redis 就是其中之一。
意思是如果您的目的仅限于set 和/或get 缓存作为key-value pair,您宁愿在下面的Method 2 中这样做。
方法二
public class DistributedCacheController : ControllerBase
{
private readonly IDistributedCache distributedCache;
public DistributedCacheController(IDistributedCache distributedCache)
{
this.distributedCache = distributedCache;
}
[HttpPost("{key}")]
public async Task<IActionResult> PostCacheByKey([FromRoute] string key, [FromBody] object data)
{
var requestContent = data.Json(); // JsonConvert.SerializeObject(data)
await distributedCache.SetStringAsync(key, requestContent);
return Ok(key);
}
[HttpGet("{key}")]
public async Task<IActionResult> GetCacheByKey([FromRoute] string key)
{
var responseContent = await distributedCache.GetStringAsync(key);
if (!string.IsNullOrEmpty(responseContent))
{
return Content(
responseContent,
Constants.ContentTypeHeaderValueJson // "application/json"
);
}
return NotFound();
}
[HttpDelete("{key}")]
public async Task<IActionResult> DeleteCacheByKey([FromRoute] string key)
{
await distributedCache.RemoveAsync(key);
return Ok(key);
}
}