You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

0 Días
1 Hrs
53 Min
42 Seg

Conectando el microservicio a Redis

26/29
Resources

How to connect a microservice to a Redis server?

Connecting a microservice to a Redis server can be an exciting challenge, especially for developers who want to take full advantage of the in-memory storage capabilities offered by Redis. To accomplish this, you need to follow these essential steps and understand the basic configurations. Below, we walk you through the process using libraries and tools that you will work with to establish this connection.

What do you need to get started with Redis?

  • Installing a Redis server: You can install Redis locally or use an online service that offers free trials of Redis. Many popular platforms can provide you with the ability to work with Redis databases online, providing basic information such as address, port and login credentials.

  • Relevant database information: You should obtain database specific details such as the host or address, port and password. This information will be key for the configuration of the client that will connect to Redis from your application.

How to install the Redis library in your application?

We use npm in this guide, but if you work with another package manager, be sure to adapt the commands:

npm install redis

This will install the library needed to interact with Redis from your application.

How to configure the connection to Redis?

Once the library is installed, a connection client is created. Here's how to define the basic settings:

const redis = require('redis');constclient = redis.createClient({ host: 'your_redis_address', port: 'your_redis_port', password: 'your_redis_password'});

How to structure the configuration in a secure way?

It is essential that you store the settings, especially credentials, in a separate file or environment variable to avoid unnecessary exposure in the code:

// Configuration file (config.js)module.exports = { redisHost: 'your_net_address', redisPort: 'your_net_port', redisPassword: 'your_net_password'};
// Usage in your applicationconst { redisHost, redisPort, redisPassword } = require('./config');const client = redis.createClient({ host: redisHost, port: redisPort, password: redisPassword });

How to implement key functions to access Redis?

Finally, you can create functions that deal with different operations in Redis. Here is an example for listing and appending entries, handling cache states:

// Function to list datafunction listData(entity, table, callback) { client.get(table, (err, data) => { if (err) return callback(err); if (data) { callback(null, JSON.parse(data)); } else { callback(null, []); } } } );}
// Function to add datafunction addData(table, data) { const key = `${table}_${data.id}`; client.set(key, JSON.stringify(data), 'EX', 10, (err) => { if (err) throw err; });});}

With these basic configurations and functions, your application will be ready to interact effectively with a Redis server, storing and retrieving data efficiently and securely. Be sure to properly handle errors and adjust cache timeouts as needed for your application. Keep exploring and experimenting with Redis in your projects!

Contributions 19

Questions 3

Sort by:

Want to see more contributions, questions and answers from the community?

No recuerdo otro curso en que se hayan visto tantos temas en el desarrollo del proyecto y tan bien explicados.

Muy curiosos como se tomaron la molestia de editar el video para cubrir la contraseña y otros datos de acceso y luego los dejan expuestos en el código XD

Para los que estamos viendo este curso en 2022, les dejo la forma en la que el codigo me funciono, al parecer redis ha cambiado mucho desde que se realizo este video

NOTA: tuve que crear un usuario y un rol en el portal de redis porque no supe como fabricar el url con el usuario por defecto

const client = redis.createClient({
  // host: config.cacheService.dbHost,
  // port: config.cacheService.dbPort,
  // password: config.cacheService.dbPass
  url: `redis://${config.cacheService.dbUser}:${config.cacheService.dbPass}@${config.cacheService.dbHost}:${config.cacheService.dbPort}`
});

(async () => {
  await client.connect();
  console.log('Conectado a REDIS');
})();

export default {
  async list(table) {
    const value = await client.get(table);
    return JSON.parse(value);
  },

  async get(table, id) {
    const value = await client.get(`${table}_${id}`);
    return JSON.parse(value);
  },

  async upsert(table, data) {
    let key = table;
    if (data && data.id) {
      key += '_' + data.id;
    }
    await client.set(key, JSON.stringify(data));
    return true;
  }
};

Lo que vamos hacer es traer data de mysql, guardarla en redis. Pero cada vez que mi API solicite data, primero revisa en redis, si está allí la trae, si no entonces va y la trae de mysql. Estoy bien?

A alguien más le esta saliendo este error a la hora de generar el redis client?

Ready check failed: NOAUTH Authentication required

Para los que estamos viendo este curso en 2025, la librería ha sufrido muchos cambios, yo lo implemente de la siguiente forma y me funciono muy bien ```js const config = require('../config.js') const { createClient } = require('redis') const initRedis = async () => { try { const client = createClient({ url: `redis://${config.services.cache.url}`, password: `${config.services.cache.password}` }) client.on('connect', () => { console.log('Conectado a Redis') }) await client.connect() } catch (error) { throw Error(`Intento de conexion a base de datos - ${error.message}`) } } initRedis() const list = async (table) => { return new Promise((res, rej) => { client.get(table) .then(data => res(JSON.parse(data))) .catch(err => rej(err)) }) } const get = (table, id) => { return new Promise((res, rej) => { client.get(table) .then(data => { if (data){ const parseData = JSON.parse(data) const foundItem = parseData.find(item => item.id === id) res(foundItem ? foundItem : null) } else { res(null) } }) .catch(err => rej(err)) }) } const upsert = async (table, data) => { return new Promise((res,rej) => { client.get(table) .then(result => { let parseData = [] if (result){ parseData = JSON.parse(result) } parseData.push(data) const key = `${table}` const stringifyData = JSON.stringify(parseData) client.set(key, stringifyData) .then(rta => { res() }) .catch(err => { rej(err) }) }) .catch(err => rej(err)) }) } module.exports = { list, get, upsert, } ```

la gran incertidumbre que siempre tuve es: que pasa si tengo una base de 20 millones de clientes… todos los 20 millones tengo que traerlos al redis?? la memoria tendra suficiente espacio para almacenar tanta data?

En el metodo list, en caso de existir data, no deberia ser JSON.parse(data) en lugar de de stringify?, es decir, si lo que esta almacenado es una cadena de texto, no deberiamos convertir esa cadena a json al retornarlo?

const redis = require('redis');

const config = require('../config');

const client = redis.createClient({
    host: config.redis.host,
    port: config.redis.port,
    password: config.redis.password,
});

function list(table) {
    return new Promise( (resolve, reject) => {
        client.get(table, (err, data) => {
            if (err) return reject(err);

            let res = data || null
            if (res)
                res = JSON.stringify(res);
            
            resolve(res);
        })
    })
}

function get(table, id) {
    const search = `${table}_${id}`;
    returnlist(search);
}

function upsert(table, data, action) {
    action = action || 'insert'
    let key = table;
    if (action !== 'insert')
        key = key + '_' + data.id;
    
    client.setex(key,10, JSON.stringify(data));
    return true;
}


module.exports = {
    list,
    get,
    upsert,
};```
Hola a todos, me gustaría saber si alguien sabe de que año es este curso, pienso que Platzi debería tener algún a párrado en la descripción del curso donde esté este dato.

Reto resuelto:

const redis = require('redis');
const config = require('../config');

const client = redis.createClient({
    host: config.redis.host,
    port: config.redis.port,
    password: config.redis.password
});

function list(table) {
    return new Promise((resolve, reject) => {
        client.get(table, (error, result) => {
            if(error) return Promise.reject(error);
            const resp = JSON.parse(result);
            resolve(resp);
        })
    }); 
}

function get(table, id) {
    const key = `${table}_${id}`;
    return list(key);
}

async function upsert(table, data) {
    let key = table;
    if(data && data.id) {
        key += `_${data.id}`;
    }
    client.setex(key, 60, JSON.stringify(data));
    return true;
}

module.exports = {
    list,
    get,
    upsert
};

Excelente ejercicio

Creo que en la función list, si nos llega la data de Redis deberíamos usar:

JSON.parse(data)

Para convertir el JSON a un objeto (estoy suponiendo que Redis nos envía la información en a formato JSON)

Tip util para node:

Con el módulo Util de Node podemos convertir una función con callbacks en una promesa.

const { promisify } = require("util");
const getAsync = promisify(client.get).bind(client);

getAsync.then(console.log).catch(console.error);

O también podemos implementar async await.

Boooom! Muy buena esta clase! 😄

Alguien sabe de alguna herramienta gratuita o plugin para Webstorm (por ejemplo) para visualizar tus datos de la DB Redis?

Tengo un projecto en una maquina virtual ubuntu y pues no estoy usando ese redislab sino que me instale la plataforma de Redis y pues le Cambie el password (requirepass) del archivo /etc/redis/redis.conf teniendo en cuenta un tutorial de un blog de digitalOcean, asi mismo hago ese archivo de configuracion del client en node como esta clase o que le hago de diferencia?

No sabía que en un solo proyecto se podían usar bases de datos relacionales y no relacionales al mismo tiempo (de distintas formas claro), es genial este curso.