MongoDb4.x集群

脚本

port="28017 28018 28019 28020"

dir=/usr/local/mongodb/shard
exec=/usr/local/mongodb/bin/mongod


function create(){

    for  i in $port
        do 
          mkdir -p $dir/$i/conf  
          mkdir -p $dir/$i/data  
          mkdir -p $dir/$i/log
    done


cat >>$dir/28017/conf/mongod.conf<<'EOF'
systemLog:
  destination: file
  path: /usr/local/mongodb/shard/28017/log/mongodb.log
  logAppend: true
storage:
  journal:
    enabled: true
  dbPath: /usr/local/mongodb/shard/28017/data
  directoryPerDB: true
  #engine: wiredTiger
  wiredTiger:
    engineConfig:
      # cacheSizeGB: 1
      directoryForIndexes: true
    collectionConfig:
      blockCompressor: zlib
    indexConfig:
      prefixCompression: true
processManagement:
  fork: true
  pidFilePath: /usr/local/mongodb/shard/28017/mongod.pid
net:
  port: 28017
replication:
  oplogSizeMB: 2048
  replSetName: my_repl
EOF

    for i in 28018 28019 28020
      do  
       \cp  $dir/28017/conf/mongod.conf  $dir/$i/conf/
       sed  -i '' "s#28017#$i#g" $dir/$i/conf/mongod.conf
    done

}


function start(){
    for i in $port
      do  
        $exec -f $dir/$i/conf/mongod.conf 
    done
}

function stop(){
    
    for i in $port
      do
        kill -9 `cat ${dir}/$i/mongod.pid`
    done
}


if [[ $1 == 'start' ]];then
    echo "Service Start"
    start
elif [[ $1 == 'create' ]];then
    echo "Service Create"
    create
elif [[ $1 == 'stop' ]];then
    echo "Service Stop"
    stop
elif [[ $1 == 'restart' ]];then
    stop
    start
else
   echo "Only Can use (create|start|stop|restart)"
fi

加入集群

mongo --port 28017
config = {_id: 'my_repl', members: [
                          {_id: 0, host: '127.0.0.1:28017'},
                          {_id: 1, host: '127.0.0.1:28018'},
                          {_id: 2, host: '127.0.0.1:28019'}]
          }
rs.initiate(config)

分片(额外)

mongod --port 29021

config = {_id: 'sh1', members: [
                          {_id: 0, host: '127.0.0.1:29021'},
                          {_id: 1, host: '127.0.0.1:29022'},
                          {_id: 2, host: '127.0.0.1:29023',"arbiterOnly":true}]
}  
rs.initiate(config)

mongod --port 29024
config = {_id: 'sh2', members: [
                          {_id: 0, host: '127.0.0.1:29024'},
                          {_id: 1, host: '127.0.0.1:29025'},
                          {_id: 2, host: '127.0.0.1:29026',"arbiterOnly":true}]
}  
rs.initiate(config)

mongod --port 29018

config = {_id: 'configReplSet', members: [
                          {_id: 0, host: '127.0.0.1:29018'},
                          {_id: 1, host: '127.0.0.1:29019'},
                          {_id: 2, host: '127.0.0.1:29020'}]
}

rs.initiate(config)

db.runCommand( { addshard : "sh1/127.0.0.1:29021,127.0.0.1:29022,127.0.0.1:29023",name:"shard1"})

db.runCommand( { addshard : "sh2/127.0.0.1:29024,127.0.0.1:29025,127.0.0.1:29026",name:"shard2"} )

相关推荐