I am trying to write values to 2 databases (need not be simultaneously) when the saveAll function is called. This does not apply to all tables but only 4 out of the 10 tables in the 2 databases.
My current logic, in Pseudocode:
$updateOk = $model->saveAll(...);
if (!开发者_StackOverflow$updateOk)
return error;
/* start second source synchronizing */
$model->changeDataSource('second');
$updateOk = $model->saveAll(...);
$model->changeDataSource('default');
if (!$updateOk)
return error;
return;
The issue with this is that sometimes it does not write to the second source, resulting in inconsistencies.
I need some advice on how to best solve this issue. I have 3 possible ideas:
- Follow the code above and add checks to make sure things get saved and if it doest, rollback the default to maintain consistency
- Write a server script that does a replication every time a saveAll() is called. (Resource intensive and not really scalable)
- Use a combo of both. Do a check for consistency before saving and do a script replication once a day
Which is the best way or are there better ways of implementing this requirement? Any ways to ensure consistencies?
The solution possibly lies in database table replication (set up your second database as a slave, configured to replicate only specific tables).
Also, how will you ever scale this?
This way, you only need to worry about writing to the DB once (your models are going to get very bloated if you need all this extra code to write to two every time), plus you are allowing your app to scale horizontally in the future (think if your app was so big you required 20 x database servers?).
Another solution would be to create a shell task, scheduled on a cron job to move the data, but I would consider replication first.
Good luck!
精彩评论