node 使用 redis 来缓存数据,需要每次请求都创建链接吗?

【字号: 日期:2022-08-28浏览:27作者:雯心

问题描述

目的:使用redis来缓存网站的固定内容数据在node开启的时候

遇到的问题:

var redis = require(’redis’), client = redis.createClient(); client.hset([hash, hashtest, value],function(err,reply){ callback(err,reply); // client.quit();});client.hget([hash,hashtest],function(err,reply){ callback(err,reply); // client.quit(); })

每次在请求完成以后是否需要client.quit 关闭链接,然后在请求的时候再次createClient 链接呢??

问题解答

回答1:

在配置文件中有两个配置与此相关:maxclients用来设置支持的最大客户端连接,超过了就拒绝;这来设置你的redis客户端能够同时支持多少连接;(当然,除了这个值,还需要看linux系统的limit设置)timeout 超时设置,用来设置一个用户连接之后,多长之内没有触发redis请求,就从服务器端主动关闭这个连接,以节省系统资源;

# Set the max number of connected clients at the same time. By default# this limit is set to 10000 clients, however if the Redis server is not# able to configure the process file limit to allow for the specified limit# the max number of allowed clients is set to the current file limit# minus 32 (as Redis reserves a few file descriptors for internal uses).## Once the limit is reached Redis will close all the new connections sending# an error ’max number of clients reached’.## maxclients 10000# Set the max number of connected clients at the same time. By default# this limit is set to 10000 clients, however if the Redis server is not# able to configure the process file limit to allow for the specified limit# the max number of allowed clients is set to the current file limit# minus 32 (as Redis reserves a few file descriptors for internal uses).## Once the limit is reached Redis will close all the new connections sending# an error ’max number of clients reached’.## maxclients 10000# Close the connection after a client is idle for N seconds (0 to disable)timeout 0

对于redis的连接请求,一般有以下两种场景设置:

触发用户请求的server有限(比如100个以内),这就可以将timeout 设置为0,这样redis连接请求永远有效,连接一次后不再断开;只在服务重启或出错后重连;

大量用户数并发请求,这种情况,可以将timeout 设置在几分钟之内(根据业务来确定),而客户端连接以后后不主动关闭连接,在发现连接被关闭(由于超时被服务器关闭)后再请求连接;

回答2:

好像自带连接池吧

回答3:

不建议每个请求都重新连接一次。只会浪费建立链接所花费的时间。比较好的是在每个model里建立一次链接(createClient)后一直保持着就好了。因为redis单线程处理的特性,所以连接池本身对redis是没什么用处的。

相关文章: