shell实现redis数据同步mysql|shell|redis|mysql|crontab

原创
2016/11/08 14:56
阅读数 699
#!/bin/bash
client="/usr/redis/redis-cli"
host="10.10.28.10"
port="6379"
left=0
offset=10
split=","
colon=":"
key="queue"


mysql="/usr/bin/mysql"
user="root"
pass="123"
data="test"
table="loginLog"


LLEN=$($client -h $host -p $port LLEN $key)
if [ $LLEN -gt $offset ]
then
	BEGIN=$(($LLEN - $offset))
	LRANGE=$($client -h $host -p $port LRANGE $key $BEGIN $LLEN)
else
	echo "This data of [$key] not long enough with offset[$offset]"
	exit
fi

#==========================================================================================================#
function parseStringJson() {
	result=$(echo ${1} | sed 's/\"//g')
	string=${result#\{}
	string=${string%\}}
	echo $string
}

function someStringCount() {
	string=${1}
	split=${2}
	length=${#string}
	for((i = 0; i < $length; i ++))
	do
		str=${string:$i:1}
		if [ $str = $split ]
		then
			j=$(($j+1))
		fi
	done
	echo $j
}
function createMysql() {
	string=${1}
	count=${2}
	flag=${3}
	length=$(($count + 2))
	if [ $flag = true ]
	then
		for((i = 1; i < $length; i ++))
		do
			result=$(echo $string | cut -d $split -f $i)
			name=$(echo $result | cut -d $colon -f 1)
			echo "\`$name\`,"
		done
		exit
	fi
	for((i = 1; i < $length; i ++))
	do
		result=$(echo $string | cut -d $split -f $i)
		value=$(echo $result | cut -d $colon -f 2)
		echo "\"$value\","
	done
}

function parseSql() {
	ARR=($@)
	for val in ${ARR[@]}
	do
		echo $val
	done
}
#==========================================================================================================#

while [ $left -lt $offset ]
do
	left=$(($left + 1))
	result=$(echo $LRANGE | cut -d " " -f $left)
	parseJson=$(parseStringJson $result)
	someCount=$(someStringCount $parseJson $split)
	sql=$(createMysql $parseJson $someCount false)
	sql=${sql%\,}
	sql="($sql),"
        ARR[$left]=$sql
	sql=$(parseSql ${ARR[@]})
done
name=$(createMysql $parseJson $someCount true)
name=${name%\,}
sql=${sql%\,}
last="use $data;INSERT INTO $table($name)VALUE$sql"
echo $last
query=$($mysql -h$host -u$user -p$pass -e"$last") 
echo $query

echo $($client -h $host -p $port LTRIM $key 0 $[$BEGIN - 1])

 

展开阅读全文
打赏
0
2 收藏
分享
加载中
更多评论
打赏
0 评论
2 收藏
0
分享
返回顶部
顶部