我正在尝试从 NestJS 应用程序连接到在 Docker 容器中运行的 Redis 实例。但是,我在使用 URL 进行 Redis 连接时遇到了连接问题。当我使用主机和端口配置连接时,它工作成功。此外,当我在 Docker 外部的本地计算机上运行应用程序时,相同的 URL 连接工作正常。
app.module.ts
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import * as redisStore from 'cache-manager-ioredis';
import { CacheModule } from '@nestjs/cache-manager';
import { RedisClientOptions } from 'redis';
@Module({
imports: [
CacheModule.registerAsync<RedisClientOptions>({
isGlobal: true,
useFactory: async () => {
return {
store: redisStore,
url: 'redis://:@redis:6379/0',
// host: 'redis',
// port: 6379,
};
},
}),
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
docker-compose.yml
services:
redis:
image: redis:alpine3.20
restart: always
ports:
- 6378:6379
volumes:
- ./volumes/redis/data:/data
app:
build:
context: .
dockerfile: Dockerfile.dev
target: release
ports:
- 2080:3000
entrypoint: ['yarn', 'start:prod']
dependencies
"@nestjs/cache-manager": "^2.2.2",
"@nestjs/common": "^10.0.0",
"@nestjs/config": "^3.2.3",
"@nestjs/core": "^10.0.0",
"@nestjs/jwt": "^10.2.0",
"@nestjs/mapped-types": "*",
"@nestjs/platform-express": "^10.0.0",
"@nestjs/typeorm": "^10.0.2",
"cache-manager": "^5.7.6",
"cache-manager-ioredis": "^2.1.0",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.1",
"pg": "^8.12.0",
"redis": "^4.7.0",
"reflect-metadata": "^0.2.0",
"rxjs": "^7.8.1",
"typeorm": "^0.3.20"
我想通过url连接redis
Docker 编写 yml 文件
version: '3.3'
name: 'docker'
services:
redis:
image: redis:6.0.7
command: redis-server --requirepass Admin12
ports:
- 6380:6379
volumes:
- ./redis.conf:/usr/local/etc/redis/redis.conf
确保安装了
"cache-manager-redis-store": "^2.0.0"
import { CacheModule } from '@nestjs/cache-manager';
import { Module } from '@nestjs/common';
import * as redisStore from 'cache-manager-redis-store';
import { CacheStoreService } from './cache.service';
@Module({
imports: [
CacheModule.registerAsync({
useFactory: () => ({
store: redisStore,
host: 'localhost',
port: 6380,
password: 'yourpassword',
}),
}),
],
providers: [CacheStoreService],
exports: [CacheStoreService],
})
export class CacheStoreModule {}
如果您想使用 URL 进行连接
import { CacheModule } from '@nestjs/cache-manager';
import { Module } from '@nestjs/common';
import * as redisStore from 'cache-manager-redis-store';
import { CacheStoreService } from './cache.service';
@Module({
imports: [
CacheModule.registerAsync({
useFactory: () => ({
store: redisStore,
// host: 'localhost',
// port: 6380,
// password: 'yourpassword',
url: 'redis://default:yourpassword@localhost:6380',
}),
}),
],
providers: [CacheStoreService],
exports: [CacheStoreService],
})
export class CacheStoreModule {}