Help us understand the problem. What is going on with this article?

LambdaからRedisのデータを取得したい

使用するもの

  • Lambda
  • Redis

私の環境

Node 12系

DockerでLamdaを用意しています。方法については、以下の記事を参考にしてください。
https://qiita.com/gdtypk/items/78b6a76dc9f212296c89

Redisも同様にDockerで起動しています。
redis:4.0

困ったこと

Node.jsは非同期で動作するので、そのあたりが苦労した。

コード

const redis   = require("redis");
const Promise = require('bluebird');

// 接続情報
const config = {
    host: 'redis',
    port: 6379
};

let client = null;
let value  = "";
const key  = "key";

exports.handler = async (event, context) => {
    try {
        //Redisに接続
        client = await connectRedis();

        // データの取得
        value = await findValueOfKey(client, key);

        //Redisとの接続を切断
        disconnectRedis();

        //レスポンス返却
        console.error('レスポンス:' + value);
        context.succeed({statusCode: 200, body: JSON.stringify(value)});
    } catch (error) {
        console.error('エラー:', error);
        disconnectRedis();
    }
};

/** 
 * Redisに接続する処理。
 */
function connectRedis() {
    return new Promise(function (resolve, reject) {
        const client = redis.createClient(config);

        client.on('connect', () => {
            console.log('接続OK');
            resolve(client);
        });
        client.on('error', (error) => {
            console.log(`接続NG`);
            reject(error);
        });
    });
}

/**
 * Redisとの接続を切断する。
 */
function disconnectRedis() {
    if (client) {
        console.log("切断します");
        client.end(true);
    }
}

/**
 * Keyを使用し、Valueを取得する。
 * @param client
 * @param key
 */
function findValueOfKey(client, key) {
    return new Promise(function (resolve) {
        client.get(key, (err, reply) => {
            resolve(reply);
        });
    });
}

おわり

もっといい書き方があったり、コードがおかしいとかあれば、教えて下さい。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした