为什么Redis无法在nodejs中获取数据?

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

这是我的Redis get函数的代码。当发送 gameid 时,它不起作用,但当使用硬编码值时,它起作用。我不知道我做错了什么。

const redis = require("redis");

const client = redis.createClient({
  url: "redis://localhost:6379",
});

// Handle Redis client errors
client.on("error", (err) => {
  console.error("Redis error:", err);
});

// Connect to Redis
(async () => {
  try {
    await client.connect();
    console.log("Connected to Redis");
  } catch (err) {
    console.error("Failed to connect to Redis:", err);
  }
})();

const testRedis = async (game_id) => {
  try {
    console.log(`Getting value for key: game:${game_id}`);
    const value = await client.get(`game:${game_id}`);
    if (value === null) {
      console.log(`No value found for key game:${game_id}`);
    } else {
      console.log("Value:", value);
    }
  } catch (err) {
    console.error("Redis test error:", err);
  } finally {
    console.log("Quitting Redis client...");
    await client.quit();
    console.log("Redis client closed.");
  }
};

module.exports = {
  testRedis,
};

这是我的路线代码:

router.get("/game", async (req, res) => {
  const { game_id } = req.query;
  console.log(`Fetching game data for game_id: ${game_id}`);
  try {
    const gameData = await testRedis(game_id);
    if (gameData) {
      res.status(200).json(JSON.parse(gameData));
    } else {
      res.status(404).json({ error: "Game not found" });
    }
  } catch (err) {
    console.error("Error fetching game from Redis:", err);
    res.status(500).json({ error: "Internal server error" });
  }
});

这是我使用硬编码值时得到的输出:

Getting value for key: game:U2WQ20

Value: {"game_id":"U2WQ20","users":[{"username":"nikhil","cards":["0_5","3_3","1_3","1_8","3_13"] },{"username":"john","cards":["3_4","1_10","0_9","1_11","0_13"]},{"username":"jane","cards":["3_9 ","3_2","1_12","3_12","1_9"]}],"play_deck":["2_5","2_7","3_11","2_8","2_4","0_12","1_2","1_6","2_ 12","1_1","3_5","3_7","2_9","0_1","0_6","1_5","0_3","0_10","1_13","2_3","2_11","2_13","3_1","0_7" ,"0_2","1_7","2_2","3_10","0_11","1_4","0_4","2_1","2_10","3_8","2_6","3_6"],"firstCard":"0_8"}


Quitting Redis client... Connected to Redis Redis client closed.

这是我使用请求查询中的游戏 ID 时得到的输出:

Server started on port 8080 Connected to Redis Fetching game data for game id: U2WQ20

Getting value for key: game:U2WQ20

No value found for key game:U2WQ20

Quitting Redis client... Redis client closed.
node.js express redis
1个回答
0
投票
    const redis = require('redis');
const express = require("express");
const { isAuthenticated } = require("../auth/middleware");
const router = express.Router();
router.use(express.json());

// Create and configure the Redis client
const client = redis.createClient({
  url: 'redis://localhost:6379'
});

client.on('error', (err) => {
  console.error('Redis error:', err);
});

// Ensure the client is connected when the application starts
(async () => {
  try {
    await client.connect();
    console.log('Redis client connected.');
  } catch (err) {
    console.error('Error connecting to Redis:', err);
  }
})();

const testRedis = async (game_id) => {
  try {
    console.log(`Getting value for key: ${game_id}`);
    const value = await client.get(game_id);
    if (value === null) {
      console.log(`No value found for key ${game_id}`);
      return null;
    } else {
      console.log('Value:', value); // Should print the JSON string
      return value;
    }
  } catch (err) {
    console.error('Redis test error:', err);
    throw err;
  }
};

// Endpoint to fetch game data
router.get("/game", async (req, res) => {
  const { game_id } = req.query;
  console.log(`Fetching game data for ${game_id}`);
  try {
    const gameData = await testRedis(game_id);
    if (gameData) {
      res.status(200).send(gameData);
    } else {
      res.status(404).json({ error: "Game not found" });
    }
  } catch (err) {
    console.error('Error fetching game from Redis:', err);
    res.status(500).json({ error: "Internal server error" });
  }
});

module.exports = router;

这给了我正确的预期输出。将两个文件放入一个文件中时,它可以正常工作。

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