一步到位同步同时更新Redis中的数据(同时更新redis中数据)

和MySQL

Within recent years more and more companies use Redis and MySQL to store data. Most people use it simultaneously because each of them has advantages. It will be more convenient if both of them can update data in same time.

For this situation, we can use Lock&Write-back to synchronize data between Redis and MySQL. When the data becomes dirty, we can lock the data in Redis. After the result is persist in MySQL, we can unlock the data in Redis.

Here is one example to illustrate this. Firstly, we need include a few packages for our program.

require 'redis'
require 'mysql2'

Secondly, we must build connections between redis and mysql. Firstly, we can create a new redis client by connect to our redis server. It can provide access to redis from mysql.

redis = Redis.new

Then we connect to mysql using the data source.

client = Mysql2::Client.new(:host => "localhost", :username => "username", :password => "password", :database => "database")

Thirdly, we write operations to synchronize the data between Redis and MySQL. Firstly, we lock the data in redis to ensure that data cannot be modified by other requests.

redis.lock(data)

Then we write and persist the data in MySQL.

sql_query = "UPDATE table SET data = #{data} WHERE id = #{id}"
client.query(sql_query)

Finally, we need unlock the data that has been changed in redis.

redis.unlock(data)

It is easy to synchronize data between Redis and MySQL using Lock&Write-back development processes. We can use the same steps for other data bases. It will save more time and developing more efficiently.


数据运维技术 » 一步到位同步同时更新Redis中的数据(同时更新redis中数据)