Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从Redis缓存数据库获取所有密钥_C#_Caching_Stackexchange.redis - Fatal编程技术网

C# 从Redis缓存数据库获取所有密钥

C# 从Redis缓存数据库获取所有密钥,c#,caching,stackexchange.redis,C#,Caching,Stackexchange.redis,我正在使用Redis cache进行缓存(特别是stackexchange.Redis C#driver。我想知道是否有任何方法可以在任何时间点获取缓存中可用的所有密钥。我的意思是,我可以在ASP.NET缓存对象中执行类似的操作(下面的代码示例) 但是,stackexchange.Redis是否有该命令的实现 通过connection.GetDataBase()实例进行调试,我看不到任何方法/属性 有什么想法吗?您需要的功能位于iSeries版本界面下,可以通过以下方式访问: Connectio

我正在使用Redis cache进行缓存(特别是
stackexchange.Redis C#driver
。我想知道是否有任何方法可以在任何时间点获取缓存中可用的所有密钥。我的意思是,我可以在ASP.NET
缓存
对象中执行类似的操作(下面的代码示例)

但是,
stackexchange.Redis
是否有该命令的实现

通过
connection.GetDataBase()
实例进行调试,我看不到任何方法/属性


有什么想法吗?

您需要的功能位于iSeries版本界面下,可以通过以下方式访问:

ConnectionMultiplexer m = CreateConnection();
m.GetServer("host").Keys();

请注意,在redis server 2.8版之前,它将使用您提到的KEYS命令,在某些情况下速度可能会非常慢。但是,如果您使用redis 2.8+,它将使用SCAN命令,性能会更好。另外,请确保您确实需要获取所有密钥,在我的实践中,我从未需要过此命令。

尝试使用此代码t、 这对我很有用:

IServer server = Connection.GetServer("yourcache.redis.cache.windows....", 6380);
foreach (var key in server.Keys())
{
   Console.WriteLine(key);
}

您需要数据库来区分在何处查找钥匙。因此,最后一行答案变成:

RedisKey[]keys=connection.GetServer(endPoint).keys(数据库:db.database,模式:“*”).ToArray();


其中db.Database是要查询的Redis数据库的数字标识符。

ASP.Net Core 3.1

将以下
包添加到您的
.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>
注:

DbHelper.GetRedisConnectionHost(Options.IsDevDb()):>>>是我根据我的环境解析我的Redis实例的连接信息/字符串的方法。您可以在此处使用自己的方法,或者如果愿意,可以在此处硬编码

方法1

因此,有了上述的东西,就能够将Redis
IConnectionMultiplexer
注入到您的
控制器或
服务中

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
}

您需要的是GetServer().Keys()我想是函数。@Evk,是的……请将其作为答案发布。Tanvi,感谢您的回答,但您的答案不是与已发布并接受的答案相同吗?我尝试使用此处给出的答案中的方法,但它对我不起作用,因此我发布了我在其他地方找到的解决方案。Tanvi,可能对您不起作用,因为您尝试了它作为答案-是。这是一个发布的抽象代码,但确实指出了需要做的事情。不管怎样,发布工作代码的努力都需要+1。IDatabase db=connection.GetDatabase();这一行似乎未使用。可能是…老实说,我真的记不起来了。如果可以,请检查并注释它是否真的是。指定数据库是关键!否则您将始终得到一个空集。
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
  }
}
public class RedisCacheHelperController : ControllerBase
{
    private readonly IConnectionMultiplexer multiplexer;

    public RedisCacheHelperController(IConnectionMultiplexer multiplexer)
    {
        this.multiplexer = multiplexer;
    }
}
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
}
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);
    }
}