无法连接到redis服务器

问题描述 投票:0回答:1

我正在 Docker 容器内运行 .NET 应用程序,并尝试将其连接到 Azure Redis 缓存实例。虽然我可以在 Docker 容器内使用 redis-cli 成功连接到 Redis 实例,但 .NET 应用程序无法连接并给出以下错误:

"StackExchange.Redis.RedisConnectionException: It was not possible to connect to the redis server(s). Error connecting right now. To allow this multiplexer to continue retrying until it's able to connect, use abortConnect=false in your connection string or AbortOnConnectFail=false; in your code.\n   at StackExchange.Redis.ConnectionMultiplexer.ConnectImpl(ConfigurationOptions configuration, TextWriter log, Nullable`1 serverType, EndPointCollection endpoints) in /_/src/StackExchange.Redis/ConnectionMultiplexer.cs:line 708\n   at StackExchange.Redis.ConnectionMultiplexer.Connect(ConfigurationOptions configuration, TextWriter log) in /_/src/StackExchange.Redis/ConnectionMultiplexer.cs:line 673\n   at StackExchange.Redis.ConnectionMultiplexer.Connect(String configuration, TextWriter log) in /_/src/StackExchange.Redis/ConnectionMultiplexer.cs:line 651\n   at Program.<Main>$(String[] args)

我已经正确配置了appsettings.json并将其添加到我的program.cs中 使用 Docker 容器内的 redis-cli 验证了与 Azure Redis 缓存的连接:


redis-cli -h ghsdata.redis.cache.windows.net -p 6380 --tls

这有效,我可以运行 PING 和 SET 等命令。

使用正确的连接字符串配置 appsettings.json,包括主机名、密码和 SSL 设置。

验证了 Docker Compose 设置,以确保正确安装 appsettings.json 并传递环境变量。

我该如何解决此错误?

使用正确的连接字符串配置 appsettings.json,包括主机名、密码和 SSL 设置。

asp.net azure docker azure-redis-cache
1个回答
0
投票

我创建了一个简单的 ASP .Net 应用程序并成功将其连接到 Azure Redis 缓存实例。

  • 确保 appsettings.json 中的 Redis 连接格式正确
  • 在您的应用程序中安装包
    StackExchange.Redis

appsettings.json:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "Redis": {
    "ConnectionString": "nuxtredis.redis.cache.windows.net:6380,password=<your-password>,ssl=True,abortConnect=False"
  }
}

程序.cs:

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using StackExchange.Redis;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
builder.Services.AddSingleton<IConnectionMultiplexer>(sp =>
{
    var configuration = ConfigurationOptions.Parse(builder.Configuration["Redis:ConnectionString"]);
    return ConnectionMultiplexer.Connect(configuration);
});
var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.MapGet("/redis-test", async context =>
{
    var connectionMultiplexer = app.Services.GetRequiredService<IConnectionMultiplexer>();
    var db = connectionMultiplexer.GetDatabase();   
    await db.StringSetAsync("test_key", "test_value");   
    var value = await db.StringGetAsync("test_key");
    if (value.IsNullOrEmpty)
    {
        await context.Response.WriteAsync("Value not found in Redis.");
    }
    else
    {
        await context.Response.WriteAsync($"Value from Redis: {value}");
    }
});
app.MapGet("/set-redis-value", async context =>
{
    var connectionMultiplexer = app.Services.GetRequiredService<IConnectionMultiplexer>();
    var db = connectionMultiplexer.GetDatabase();

    var key = context.Request.Query["key"].ToString();
    var value = context.Request.Query["value"].ToString();

    if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(value))
    {
       
        await db.StringSetAsync(key, value);
        await context.Response.WriteAsync($"Successfully set key '{key}' with value '{value}' in Redis.");
    }
    else
    {
        await context.Response.WriteAsync("Key or value cannot be empty.");
    }
});
app.Run();

Index.cshtml:

@page
@model dynamic
<h2>ASP.NET Core Redis Connection Test</h2>
<p>
    <label for="keyInput">Key:</label>
    <input type="text" id="keyInput" />
</p>
<p>
    <label for="valueInput">Value:</label>
    <input type="text" id="valueInput" />
</p>
<button id="setRedisValueButton">Set Redis Value</button>
<button id="testRedisButton">Test Redis Connection</button>
<div id="result"></div>
<script>   document.getElementById("setRedisValueButton").addEventListener("click", async () => {
        const key = document.getElementById("keyInput").value;
        const value = document.getElementById("valueInput").value;

        const response = await fetch(`/set-redis-value?key=${key}&value=${value}`);
        const result = await response.text();
        document.getElementById("result").innerText = result;
    });   document.getElementById("testRedisButton").addEventListener("click", async () => {
        const response = await fetch('/redis-test');
        const result = await response.text();
        document.getElementById("result").innerText = result;
    });
</script>

本地输出:

enter image description here

我已通过 Azure 容器注册表成功将应用程序部署到 azure 应用程序服务。

部署后输出:

enter image description here

我使用Redis-cli测试了Redis是否连接成功。 运行以下命令

redis-cli -h <REDIS-HOST> -p <REDIS-PORT> -a <REDIS-PASSWORD> --tls

我成功地在 Redis 中存储和检索键和值。

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.