MYSQL 데이터를 Redis 저장
Redis를 서비스 운영할때 캐시 형태로 많이 사용하고 있습니다.
Redis장애 발생시 DB에 있는 데이터를 올려야 할경우 있습니다.
Python Script를 이용하여 Mysql 데이터를 Redis에 넣어 보겠습니다.
환경 Ubuntu (Linux)
패키지
unixodbc (https://steemit.com/mysql/@jaerakson/linux-mysql-odbc)
, pip ,python ,redis
참고 URL
https://pypi.python.org/pypi/redis
http://mkleehammer.github.io/pyodbc/
pip3설치
sudo pip3 install redis
sudo pip3 install pyodbc
DNS 이름추가
vi /usr/local/etc/odbc.ini
Name: qa3
Driver: MySQL ODBC 5.3 Driver
Server: localhost
Uid: xxx
Pwd: xxx
Database: dba
Socket: /database/log/test_mysql02.sock
Port: 13306
Python source
import redis
import pyodbc
dsn ='qa3'
#user=xxx
#password = xxx
#database = xxx
con_string = 'DSN=%s' %(dsn)
cnxn=pyodbc.connect(con_string)
cur = cnxn.cursor()
r = redis.Redis(host='localhost',port=6379,db=0)
query= ' select nUserIndex,nPaypossible from tb_profile;'
print (query)
cur.execute(query)
while 1:
row = cur.fetchone()
if not row:
break
r.zadd('prize' , row[0], row[1])
print ('zadd prize {0}, {1}'.format(row[1], row[0]))
주의
pip 의 redis zadd 와 redis cmd zadd 사용순서 다릅니다.
zadd 저장할때 userid 와 값이 서로 변경 되어야 합니다.
r.zadd('prize' , row[0], row[1])
def zadd(self, name, *args, **kwargs):
"""
Set any number of score, element-name pairs to the key ``name``. Pairs
can be specified in two ways:
As *args, in the form of: score1, name1, score2, name2, ....
or as **kwargs, in the form of: name1=score1, name2=score2, ....
The following example would add four values to the 'my-key' key:
redis.zadd('my-key', 1.1, 'name1', 2.2, 'name2', name3=3.3, name4=4.4)
"""
pieces = []
if args:
if len(args) % 2 != 0:
raise RedisError("ZADD requires an equal number of "
"values and scores")
pieces.extend(args)
for pair in iteritems(kwargs):
pieces.append(pair[1])
pieces.append(pair[0])
return self.execute_command('ZADD', name, *pieces)