Azure Cache for Redis空闲并重新连接,即使我设置了ping来唤醒它

ufj5ltwl  于 5个月前  发布在  Redis
关注(0)|答案(1)|浏览(54)

我有一个NodeJS应用程序在Azure容器应用程序中运行,该应用程序使用Azure Cache for Redis。此连接每10分钟中断一次,应用程序必须重新连接。我有一个ping设置,根据文档https://learn.microsoft.com/en-us/azure/azure-cache-for-redis/cache-best-practices-connection#idle-timeout中的本文。
当在缓存中使用monitor时,我可以看到ping正在进入。我也尝试过不使用RedisClient的ping功能,而只是在每个ping间隔设置一个键值对-这不起作用,缓存仍然空闲。关于什么可能导致这个问题或如何修复它,有什么想法吗?

px9o7tmv

px9o7tmv1#

在这里,我配置了一个连接池来有效地管理和重用Redis连接。根据应用的需求调整maxmin的值。本示例使用generic-pool库。


的数据
Azure Cache for Redis空闲和重新连接

  • 在这里,我使用Express构建了一个Web服务器,并与Redis缓存进行交互。此代码结构用作构建可扩展和可维护应用程序的起点。
const express = require('express');
const redis = require('redis');
const genericPool = require('generic-pool');

// Create a Redis connection pool
const redisPool = genericPool.createPool({
  create: () => redis.createClient({ host: '<your-redis-host>', port: 6379 }),
  destroy: (client) => client.quit(),
}, { max: 10, min: 2 });

// Create an Express application
const app = express();

// Middleware to acquire a Redis client from the pool
app.use((req, res, next) => {
  redisPool.acquire().then((client) => {
    req.redisClient = client;
    next();
  }).catch((err) => {
    console.error('Error acquiring Redis client:', err);
    res.status(500).send('Internal Server Error');
  });
});

// Routes
app.get('/', (req, res) => {
  // Example route using Redis client
  const { redisClient } = req;
  redisClient.get('exampleKey', (err, result) => {
    if (err) {
      console.error('Error getting value from Redis:', err);
      res.status(500).send('Internal Server Error');
    } else {
      res.send(`Value from Redis: ${result}`);
    }

    // Release the Redis client back to the pool
    redisPool.release(redisClient);
  });
});

// Error handling middleware
app.use((err, req, res, next) => {
  console.error('Error:', err);
  res.status(500).send('Internal Server Error');
});

// Start the Express server
const port = process.env.PORT || 3000;
app.listen(port, () => {
  console.log(`Server listening on port ${port}`);
});

字符串
您还可以使用连接池来创建和重用连接。

async function performRedisOperation() {
  let client;
  try {
    client = await pool.acquire();
    // Perform Redis operation using 'client'
    // Example: client.get('key', (err, reply) => { /* handle response */ });
  } catch (error) {
    console.error('Error acquiring Redis connection:', error);
  } finally {
    if (client) {
      await pool.release(client);
    }
  }
}

// Schedule periodic Redis operations
setInterval(performRedisOperation, 600000); // 10 minutes

  • 这个输出表明应用程序成功连接到Redis,每10分钟执行一次操作。


相关问题