使用环境变量在redis.conf中设置动态路径

8

我有一个环境变量MY_HOME,其指向一个目录路径/home/abc

现在,我有一个redis.conf文件,需要将这个路径设置为:

**redis.conf**

pidfile $MY_HOME/local/var/pids/redis.pid
logfile $MY_HOME/local/var/log/redis.log
dir $MY_HOME/local/var/lib/redis/

就像我们在命令行中做的那样,这样我的配置文件就可以根据环境变量选择路径。

看起来 Redis 配置中没有环境变量的支持(至少在 2.6.16 版本中没有),很遗憾。 - BorisOkunskiy
3个回答

3

因为Redis可以从 stdin 读取其配置,所以我做了与@jolestar建议的非常相似的事情。我在我的redis.conf中放置占位符变量,然后在我的Redis启动器中使用sed替换它们。例如:

==========
$MY_HOME/redis/redis.conf
==========
...
pidfile {DIR}/pids/server{n}.pid
port 123{n}
...

然后我有一个脚本来启动Redis:

==========
runredis.sh
==========
DIR=$MY_HOME/redis
for n in {1..4}; do
    echo "starting redis-server #$n ..."
    sed -e "s/{n}/$n/g" -e "s/{DIR}/$DIR/g" < $DIR/redis.conf | redis-server -
done

我一直使用这种方法,效果很好。


0

我也找到了一个解决方案,但是 Redis 配置不支持环境变量。我认为有两种方法:

  1. 通过脚本启动 Redis,脚本获取环境变量并更改 Redis 配置。
  2. 通过命令行启动 Redis,并将环境变量作为参数发送。

0

Redis不支持此功能,但可以通过使用envsubst(几乎所有现代发行版都默认安装)在运行redis-server之前替换环境变量的值来实现。

envsubst '$HOME:$MY_HOME' < ~/.tmpl_redis.conf >  ~/.redis.conf && redis-server ~/.redis.conf
# or
envsubst '$MY_HOME' < ~/.tmpl_redis.conf >  ~/.redis.conf && redis-server !#:5 # 5th argument from the previous command


这个想法是在运行时动态注入环境变量,而不是静态地注入。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接