赞
踩
1、先查询Redis是否存在目标数据,存在即输出,不存在则查询Mysql;
2、从mysql取出目标数据存入Redis后设置过期时间,输出目标数据。
- CREATE DATABASE hyy_db;
-
- CREATE TABLE hyy_tab(
- id INT NOT NULL AUTO_INCREMENT COMMENT 'id',
- NAME VARCHAR(20) COMMENT '名字',
- create_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
- PRIMARY KEY (`id`)
- )ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
-
- INSERT INTO hyy_tab(NAME) VALUES ('Tom'),('Jerry');
- # -*- coding: utf-8 -*-
-
- import pymysql
- import redis
- import sys
- import os
-
- def main():
- args = sys.argv
- input_name = args[1] #传入值
- pool = redis.ConnectionPool(host='192.168.1.100',port=6379,password=123456)
- r = redis.Redis(connection_pool=pool)
- name = r.lindex(input_name,1)
- if name != None: #如果该值存在redis,则输出结果
- for i in range(3):
- print(r.lindex(input_name,i).decode("utf-8"))
- else: #该值不存在redis,从mysql获取,并输出结果
- r.expire("list_info",0) #删除临时list
- conn=pymysql.connect(host="192.168.1.100",port=3306, user="hyy",passwd="123456",db="hyy_db")
- cursor = conn.cursor()
- cursor.execute('select * from hyy_tab where name = %s',(input_name))
- cur_all = cursor.fetchall() #返回mysql结果集
- if cur_all == ():
- print('%s does not exist in the target table!' %input_name)
- os._exit(0) #如果值不存在于mysql即退出
- for cur in cur_all:
- for c in cur:
- r.rpush("list_info",str(c)) #创建临时list
- list_name = r.lindex("list_info",1).decode("utf-8")
- for i in range(3):
- r.rpush(list_name,r.lindex("list_info",i).decode("utf-8"))
- print(r.lindex("list_info",i).decode("utf-8"))
- r.expire(input_name,10) #设置过期时间
-
- if __name__ == "__main__":
- main()
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。