菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
252
0

redis 根据模板批量生成使用不同端口的配置文件并运行运行服务

原创
05/13 14:22
阅读数 993422

今天学了下Redis 集群,需要创建 n 多个配置文件,由于只是本地测试,这些文件配置几乎一样,只是配置使用的端口不同。于是,我想写个函数,帮我生成。

 

模板文件 cluster.tpl

port {port}
cluster-enabled yes
cluster-config-file {port}-nodes.conf
cluster-node-timeout 5000
appendonly yes

 

function mk.file(){

    eval "set -- `getopt -o t:e:r:dh -l help -- \"$@\"`"

    local _tpl=''
    local _ext='conf'
    local _run=''
    local _dir=false

    for i in "$@"
    do
        case "$1" in
        -t)  _tpl="$2"; shift 1;; #处理了带值参数,所以多跳一下.
        -e)  _ext="$2"; shift 1;;
        -r)  _run="$2"; shift 1;;
        -d)  _dir=true;;

        -h|--help)
echo "mk.file [option] port1 [port2 ...]
功能:根据模板批量创建配置文件, 模板文件中的 {port} 会被替换
用法:
    mk.file -t cluster.tpl 32768 32769 32770
    mk.file -t cluster.tpl -r "redis-serer :file --daemonize yes" 32768 32769 32770

选项:
    -t          模板文件
    -e          文件扩展名如 ini conf
    -r          运行的命令
    -d          是否生成二级目录
    -h, --help  帮助"; return 0
;;

        --)    shift 1; break;;#终止时,最后跳一下
         *)    echo "无效选项:$1"; return 0 ;;
        esac
        shift 1 #每次处理完一个参数,跳一下
    done

    local file=''
    local command=''
    for port in "$@"
    do

        if [ $_dir == 'true' ];then
            mkdir -p $port
            file="$port/$port.$_ext"
        else
            file="$port.$_ext"
        fi

        cat "$_tpl" > $file
        sed -i -e "s/{port}/$port/" $file
      
        if [ -n "$_run" ];then
            command=${_run/':file'/$file};
            echo "$command";
            eval "$command"
        else
            echo $file
        fi 
   
    done

}

 

发表评论

0/200
252 点赞
0 评论
收藏
为你推荐 换一批