redis做mysql缓存操作步骤
时间: 2023-12-30 20:22:35 浏览: 125
以下是使用Redis作为MySQL缓存的操作步骤:
1. 安装redis-py库
```shell
pip install redis
```
2. 连接Redis
```python
import redis
redis_conn = redis.Redis(host='localhost', port=6379, db=0)
```
3. 连接MySQL
```python
import mysql.connector
mysql_conn = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
```
4. 查询MySQL数据
```python
cursor = mysql_conn.cursor()
cursor.execute("SELECT * FROM yourtable")
result = cursor.fetchall()
```
5. 将MySQL数据存入Redis
```python
for row in result:
redis_conn.hmset(row[0], {'column1': row[1], 'column2': row[2], ...})
```
6. 从Redis中获取MySQL数据
```python
result = redis_conn.hgetall(your_key)
```
7. 如果MySQL数据更新,需要手动更新Redis缓存
```python
cursor.execute("UPDATE yourtable SET column1 = 'new_value' WHERE id = 'your_id'")
redis_conn.hmset(your_id, {'column1': 'new_value'})
```
阅读全文