Edward Martin
Edward Martin

Reputation: 9

How to properly connect to Redis from node app

I'm trying to use Redis as a cache for my node app.

My app looks as follows:

--redisClient.ts--

import redis = require('redis');

const client = redis.createClient({url: 'myRedisURL'});
export default client;

--myRoute.ts--

import client from 'redisClient';
...
let redisValue: string;
await client.connect();
redisValue = await client.get(key);
if(!redisValue) redisValue = await some_external_api_call(key); 
client.set(key, value, {EX: 3600 * 24});

Done this way, I get the error "Socket already opened" on RedisSocket.connect. If I omit the line async client.connect(); then I get the error "The client is closed" at Commander._RedisClient_sendCommand.

Any clues to what I'm doing wrong would be much appreciated.

Upvotes: 0

Views: 616

Answers (2)

Harish Pydimarri
Harish Pydimarri

Reputation: 131

You must close a connection once the work is done. Or use a pooled connection

Upvotes: 0

Asad Awadia
Asad Awadia

Reputation: 1521

Should be await client.connect not async

Upvotes: 1

Related Questions