Mark Ku's Blog
首頁 關於我
Powershell automatically syncs docker redis data
PowerShell
Powershell automatically syncs docker redis data
Mark Ku
Mark Ku
November 11, 2022
1 min

Powershell automatically syncs docker redis data

Problem

Because our development sever is in USA.
So In front-end development often many network delays and instability.

Solution concept

Use Windows Task Scheduler and Powershell to sync data with USA’s redis

First. You need create auto-sync.ps1 script and put Powershell to D:\Powershell\ folder

## auto-sync.ps1
$masterRedisIp = 192.168.40.30 // usa redis 
$masterRedisPort = 6399
$slaveRedisIp = 192.168.0.39  // taiwan redis 
slaveRedisPort = 6400

$Logfile = "D:\Logs\proc_$env:computername.log"

function WriteLog
{
Param ([string]$LogString)
$Stamp = (Get-Date).toString("yyyy/MM/dd HH:mm:ss")
$LogMessage = "$Stamp $LogString"
Add-content $LogFile -value $LogMessage
}

WriteLog "The script is run"
docker exec -u 0 -it f08e2fc8c5a4 redis-cli -h $slaveRedisIp -p $slaveRedisPort slaveof $masterRedisIp $masterRedisPort

# Initial state
$syncCompleted = $false

# Monitor the replication status
while($syncCompleted -eq $false){
    Write-Host "Waiting for replication sync..."
    Start-Sleep -Seconds 10
    $replicaSyncStatus = docker exec -u 0 -it $containerId redis-cli -h $localRedis -p $localPort info replication | Select-String -Pattern "master_sync_in_progress:0"
    if($null -ne $replicaSyncStatus){
        $syncCompleted = $true
    }
}

docker exec -u 0 -it f08e2fc8c5a4 redis-cli -h $slaveRedisIp -p $laveRedisPort slaveof no one
WriteLog "The script is successfully executed"

Second, Create create-sync-redis-task.ps1 and run this power shell

$account='admin'
$password='password'
$Action = New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument '-ExecutionPolicy Bypass -File D:\Powershell\sync-redis.ps1"'

$Trigger = New-ScheduledTaskTrigger -Daily -At 3am

$Settings = New-ScheduledTaskSettingsSet

$Task = New-ScheduledTask -Action $Action -Trigger $Trigger -Settings $Settings

Register-ScheduledTask -TaskName 'RedisSync' -InputObject $Task -User $account -Password $password

Open the Windows Task Scheduler. You will see the task you just created.

P.S. In during the synchronization process, the slave redis cannot modify any redis data.


Tags

Mark Ku

Mark Ku

Software Developer

8年以上豐富網站開發經驗,直播系統、POS系統、電子商務、平台網站、SEO、金流串接、DevOps、Infra 出身,帶過幾次團隊,目前專注於北美及德國市場電商網站開發團隊。

Expertise

前端(React)
後端(C#)
網路管理
DevOps
溝通
領導

Social Media

facebook github website

Related Posts

使用Powershell 備份及還原 Windows docker 容器
使用Powershell 備份及還原 Windows docker 容器
November 18, 2023
1 min

Quick Links

關於我

Social Media