There are two issues to consider when using Redis as a MySQL database cache:
1. Determine what data structure is used to store the information from MySQL;
2. After determining the data structure, what identity is used as the key of the data structure .
Visually, the data in MySQL is stored on a table, and more microscopically, the tables are stored on a row. Each time a select query is executed, MySQL returns a result set that consists of several rows. So, a natural idea is to find a data structure in Redis that corresponds to a MySQL row. There are five basic data structures available in Redis, namely, string, list, hash (hash), collection (set), and ordered set (sorted set). After investigation, it is found that there are two kinds of data structures suitable for storing rows, namely, string and hash.
To put the MySQL row data into a string, you first need to format the row data. In fact, each row of the result set can be seen as a collection of key-value pairs consisting of field names and their corresponding values. This kind of key-value pair structure makes it easy to think of JSON format. Therefore, the JSON format is chosen as the format template for each row of the result set. Based on this idea, we can implement the code that formats the result set as several JSON objects and converts the JSON object into a string that is stored in Redis.
Using Redis as a MySQL database cache