我应该如何重构我的代码(PHP和MySQL)以更有效地使用主/从数据库配置?

时间:2022-10-05 12:41:01

I have developed a web application using PHP and MySQL which has all been running from a single server. When I come to scale up and need a separate database server and then ultimately need a master / slave configuration of database servers how should I update my code to connect to the correct server? I have the database connection details stored on a separate file so can update this easily enough. What happens though when I have a master (where all writes will go) and slave (for all reads). What is the best way to optimise my PHP code, is there a good resource / examples of how to structure MySQL for master / slave servers?

我使用PHP和MySQL开发了一个Web应用程序,它已经从一台服务器运行。当我扩展并需要一个单独的数据库服务器,然后最终需要数据库服务器的主/从配置时,我应该如何更新我的代码以连接到正确的服务器?我将数据库连接详细信息存储在单独的文件中,因此可以轻松更新。当我有一个主人(所有写入将去)和奴隶(所有读取)时会发生什么。什么是优化我的PHP代码的最佳方法,是否有一个很好的资源/示例如何为主/从服务器构建MySQL?

cheers

1 个解决方案

#1


1  

Personally I would refactor the code to disable access the database directly from the core program, and instead crate a "Data Access" class, which would be responsible for determining which actions were "reads" and which actions were "writes" and sending them to the appropriate server(s).

我个人会重构代码来禁止直接从核心程序访问数据库,而是创建一个“数据访问”类,它将负责确定哪些操作是“读取”,哪些操作是“写入”并将它们发送到适当的服务器。

This way, all the code that is aware of the slave/master setup would be in one place and you wouldn't need to modify your core program, except to have it get the data from the "Data Access" class as opposed from the database directly.

这样,所有知道slave / master设置的代码都在一个地方,你不需要修改你的核心程序,除非让它从“数据访问”类中获取数据,而不是数据库直接。

#1


1  

Personally I would refactor the code to disable access the database directly from the core program, and instead crate a "Data Access" class, which would be responsible for determining which actions were "reads" and which actions were "writes" and sending them to the appropriate server(s).

我个人会重构代码来禁止直接从核心程序访问数据库,而是创建一个“数据访问”类,它将负责确定哪些操作是“读取”,哪些操作是“写入”并将它们发送到适当的服务器。

This way, all the code that is aware of the slave/master setup would be in one place and you wouldn't need to modify your core program, except to have it get the data from the "Data Access" class as opposed from the database directly.

这样,所有知道slave / master设置的代码都在一个地方,你不需要修改你的核心程序,除非让它从“数据访问”类中获取数据,而不是数据库直接。