Skip to content

Instantly share code, notes, and snippets.

@sechiro
Last active August 29, 2015 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sechiro/1a317775711e2dce8ce0 to your computer and use it in GitHub Desktop.
Save sechiro/1a317775711e2dce8ce0 to your computer and use it in GitHub Desktop.
Redisのロックを取るスクリプト
#!/bin/bash
set -ue
node_id=1
lock_key=lock
ttl=10
redis_db=0
redis_host=localhost
redis_port=6379
locked=`redis-cli -h $redis_host -p $redis_port -n $redis_db --raw SETNX $lock_key $node_id`
if [ "$locked" = 1 ];then
echo "Get lock: keyname: $lock_key"
result=`redis-cli -h $redis_host -p $redis_port -n $redis_db --raw EXPIRE $lock_key $ttl`
if [ "$result" = 1 ];then
echo "Set expire: $ttl"
exit 0
elif [ "$result" = 0 ];then
echo "Couldn't set expire!"
exit 1
fi
elif [ "$locked" = 0 ];then
echo "Couldn't get lock"
exit 1
else
echo "Error!"
exit 1
fi
@sechiro
Copy link
Author

sechiro commented Jan 13, 2015

  • 使い方
bash get-redis-lock.sh && echo ok

cronのHAなどに使う想定

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment