Skip to content

Instantly share code, notes, and snippets.

@nicStuff
Last active October 17, 2023 07:30
Show Gist options
  • Star 18 You must be signed in to star a gist
  • Fork 11 You must be signed in to fork a gist
  • Save nicStuff/ee7feb8eed00174a46db42812545b403 to your computer and use it in GitHub Desktop.
Save nicStuff/ee7feb8eed00174a46db42812545b403 to your computer and use it in GitHub Desktop.
Comfort tool for migrating redis keys among instances. Supports KEYS syntax matching, authentication and TTL
#!/bin/bash
######
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
# TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
# CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
######
######
### Migrates the keys responding to the pattern specified on the command line, using DUMP/RESTORE, supports authentication differently from MIGRATE
######
KEYS_MATCHER=$1
SOURCE_PASSWORD=foobared
SOURCE_PORT=6379
SOURCE_SCHEMA=24
TARGET_PASSWORD=foobared
TARGET_PORT=6379
TARGET_SCHEMA=16
LOG_FILE="redis-migrate.log"
if [[ -z "$KEYS_MATCHER" ]]; then
echo -e "Please provide a KEYS matcher, like *~cache"
exit 1
fi
echo "*** Migrating keys matching $KEYS_MATCHER"
redis-cli -a $SOURCE_PASSWORD -p $SOURCE_PORT keys "$KEYS_MATCHER" | while read key; do
# Preparing TTL
key_ttl=`redis-cli -a $SOURCE_PASSWORD -p $SOURCE_PORT ttl "$key"`
if [[ $key_ttl -lt 1 ]]; then
key_ttl=0
else
# TTL must be in milliseconds when specifying it
key_ttl+=000
fi
echo "Dump/Restore \"$key\", ttl $key_ttl" &>> $LOG_FILE
redis-cli --raw -p $SOURCE_PORT -n $SOURCE_SCHEMA -a $SOURCE_PASSWORD DUMP "$key" | head -c -1 | redis-cli -x -p $TARGET_PORT -n $TARGET_SCHEMA -a $TARGET_PASSWORD RESTORE "$key" $key_ttl &>> $LOG_FILE
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment