无法与 Redis 容器 ASP.NET Core 通信

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

我正在尝试在 ASP.NET Core 8 中创建一个演示,以将数据保存在 Redis 缓存中。当我使用

localhost:6379
时,一切都很完美。但是当我的 app.net 容器正在运行并尝试与容器 Redis 通信时,通过使用像
http://redis:6379
这样的容器名称,我收到错误:

http://redis:6379/Interactive、Initializing/NotStarted 上无法连接

这是我的作文:

api:
    image: api:latest
    container_name: api
    build:
        context: ../src/api
        dockerfile: ./Dockerfile
    ports:
        - "5168:5168"
    environment:
        - aspnetcore_environment=Production
        - aspnetcore_urls=http://+:5168
        
        
redis:
    image: redis:latest
    container_name: redis
    restart: always
    ports:
      - "6379:6379"
    volumes:
      - ./volumes/redis.data:/usr/share/root/redis
      - ./volumes/redis.conf:/usr/share/redis/redis.conf
    environment:
      - REDIS_PASSWORD=Teste@123
      - REDIS_PORT=6379
      - REDIS_DATABASES=16   
    command: [ "redis-server", "/usr/share/redis/redis.conf"]

这是我的

program.cs
文件:

var redisOptions = new ConfigurationOptions
{
    EndPoints = { { appServicesSettings.RedisHost, appServicesSettings.RedisPort } },
    AbortOnConnectFail = false,
    DefaultDatabase = 0,
    ConnectTimeout = 15000,
    SyncTimeout = 15000
};

builder.Services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = appServicesSettings.Redis;
    options.InstanceName = "SampleInstance";
});

builder.Services.AddSingleton<IConnectionMultiplexer>(ConnectionMultiplexer.Connect(redisOptions));

appsettings.json

"AppServicesSettings": {
    "RedisLocal": "localhost:6379",
    "RedisHost": "http://redis",
    "RedisPort": 6379
}

使用版本:

Microsoft.Extensions.Caching.StackExchangeRedis" Version="8.0.4"
docker asp.net-core docker-compose redis stackexchange.redis
1个回答
0
投票

好的,我通过在应用程序设置中进行一些更改来修复

改变这个

  "AppServicesSettings": {
    "RedisLocal": "localhost:6379",
    "RedisHost": "http://redis",
    "RedisPort": 6379
  }

对此:

  "AppServicesSettings": {
    "RedisLocal": "localhost:6379",
    "RedisHost": "redis",
    "RedisPort": 6379
  }

从 Redis 主机中删除“http://”:在 appsettings.json 文件中,从 Redis 主机中删除“http://”前缀。 Redis 通常不使用 HTTP 协议进行通信,仅使用 TCP。因此,主机应该只是“redis”,没有“http://”。

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