帮我把代码写一下,定期同步redis和mysql的数据
时间: 2024-04-29 18:26:04 浏览: 11
好的,您需要一个定时任务来定期同步redis和mysql的数据,以下是示例代码:
```python
import redis
import pymysql
import schedule
import time
# 连接redis数据库
redis_client = redis.Redis(host='localhost', port=6379, db=0)
# 连接mysql数据库
mysql_conn = pymysql.connect(host='localhost', port=3306, user='root', password='password', database='testdb')
def sync_data():
# 从redis读取数据
redis_data = redis_client.get('data')
if redis_data:
redis_data = redis_data.decode('utf-8')
# 将数据同步到mysql
with mysql_conn.cursor() as cursor:
sql = "INSERT INTO data_table (data) VALUES (%s)"
cursor.execute(sql, (redis_data,))
mysql_conn.commit()
print('同步数据成功:', redis_data)
else:
print('redis中没有数据')
# 每隔5分钟同步一次数据
schedule.every(5).minutes.do(sync_data)
while True:
schedule.run_pending()
time.sleep(1)
```
这段代码会连接到您本地的redis和mysql数据库,定期从redis获取数据后同步到mysql中。您可以根据自己的需求调整定时任务的间隔时间。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)