search
HomeBackend DevelopmentPHP Tutorialmysql Proxy read-write separation configuration and php mysql read-write separation class

  1. mysql-proxy
  2. –proxy-backend-addresses=narcissus:3306
  3. –proxy-backend-addresses=nostromo:3306
Copy code

3. Database read and write separation, 192.168.18.11 0 is responsible for writing Enter, 192.168.18.107 is responsible for reading data. Of course, you can also add a server for reading data.

  1. mysql-proxy
  2. –proxy-backend-addresses=192.168.18.110:3306
  3. –proxy-read-only-backend-addresses=192.168.18.107:3306
Copy code

This method does not separate reading and writing. mysql-proxy cannot distinguish which ones are sent to the slave server, and you need to use script control yourself. See the fourth method.

4. Lua script can well control the connection and distribution, as well as the query and returned result set. When using Lua scripts, you must use –proxy-lua-script to specify the name of the script. The script will not be read until a connection is generated, that is, there is no need to restart the service after modifying the script. mysql-proxy –proxy-lua-script=rw-splitting.lua –proxy-backend-addresses=192.168.18.110:3306 –proxy-read-only-backend-addresses=192.168.18.107:3306

Note: 1. The read-write separation mechanism of proxy is to first send the first few queries to the master to establish a connection. When the number of queries sent to the master exceeds the minimum value of the connection pool, the query begins

2. LAST_INSERT_ID cannot be sent to the main server. Just change line 226 to the following. elseif not is_insert_id and token.token_name == “TK_FUNCTION” then

3. When using the default rw-splitting.lua, it will prompt that the proxy-command cannot be found. I set the path of mysql-proxy to the system path, and then run it in the share directory and everything is OK. Enter cmd during operation. , then Then cd C:toolsmysql-proxyshare.

4. Garbled characters After connecting to the database through proxy, the string found is always garbled, even if set names ‘utf8’ is manually executed, it has no effect. Solution, mysql server must be set

  1. class mysql_rw_php {
  2. //Number of queries
  3. var $querynum = 0;
  4. //Database connection for current operation
  5. var $link = null;
  6. //Character set
  7. var $charset ;
  8. //Current database
  9. var $cur_db = '';
  10. //Whether there is a valid read-only database connection
  11. var $ro_exist = false;
  12. //Read-only database connection
  13. var $link_ro = null;
  14. // Read and write database connection
  15. var $link_rw = null;
  16. function mysql_rw_php(){
  17. }
  18. function connect($dbhost, $dbuser, $dbpw, $dbname = '', $pconnect = 0, $halt = TRUE) {
  19. if($pconnect) {
  20. if(!$this->link = @mysql_pconnect($dbhost, $dbuser, $dbpw)) {
  21. $halt && $this->halt('Can not connect to MySQL server');
  22. }
  23. } else {
  24. if(!$this->link = @mysql_connect($dbhost, $dbuser, $dbpw)) {
  25. $halt && $this->halt('Can not connect to MySQL server');
  26. }
  27. }
  28. //Read-only connection failed
  29. if(!$this->link && !$halt) return false;
  30. //When rw is not initialized, the first connection is as rw
  31. if($this->link_rw == null)
  32. $this->link_rw = $this->link;
  33. if($this->version() > '4.1') {
  34. if ($this->charset) {
  35. @mysql_query("SET character_set_connection=$this->charset, character_set_results=$this->charset, character_set_client=binary", $this->link);
  36. }
  37. if ($this->version() > '5.0.1') {
  38. @mysql_query("SET sql_mode=''", $this->link);
  39. }
  40. }
  41. if($dbname) {
  42. $this->select_db($dbname);
  43. }
  44. }
  45. //Connect a read-only mysql database
  46. function connect_ro($dbhost, $dbuser, $dbpw, $dbname = '', $pconnect = 0) {
  47. if($this->link_rw == null)
  48. $this->link_rw = $this->link;
  49. $this->link = null;
  50. //No halt error
  51. $this- >connect($dbhost, $dbuser, $dbpw, $dbname, $pconnect, false);
  52. if($this->link){
  53. //Connection successful
  54. //echo "link ro sussess!
    $this->ro_exist = true;
  55. $this->link_ro = $this->link;
  56. if($this->cur_db){
  57. //If the database has been selected, operation is required Once
  58. @mysql_select_db($this->cur_db, $this->link_ro);
  59. }
  60. }else{
  61. //Connection failed
  62. //echo "link ro failed!
    ";
  63. $this- >link = &$this->link_rw;
  64. }
  65. }
  66. //Set up a series of read-only databases and connect to one of them
  67. function set_ro_list($ro_list){
  68. if(is_array($ro_list)){
  69. / /Randomly select one of them
  70. $link_ro = $ro_list[array_rand($ro_list)];
  71. $this->connect_ro($link_ro['dbhost'], $link_ro['dbuser'], $link_ro['dbpw'] ; $dbname, $this->link_ro);
  72. }
  73. return @mysql_select_db($dbname, $this->link_rw);
  74. }
  75. function fetch_array($query, $result_type = MYSQL_ASSOC) {
  76. return mysql_fetch_array($ query, $result_type);
  77. }
  78. function fetch_one_array($sql, $type = '') {
  79. $qr = $this->query($sql, $type);
  80. return $this->fetch_array( $qr);
  81. }
  82. function query($sql, $type = '') {
  83. $this->link = &$this->link_rw;
  84. //Judge whether to select statement
  85. if($this- >ro_exist && preg_match ("/^(s*)select/i", $sql)){
  86. $this->link = &$this->link_ro;
  87. }
  88. $func = $type == ' UNBUFFERED' && @function_exists('mysql_unbuffered_query') ?
  89. 'mysql_unbuffered_query' : 'mysql_query';
  90. if(!($query = $func($sql, $this->link)) && $type != 'SILENT' ) {
  91. $this->halt('MySQL Query Error', $sql);
  92. }
  93. $this->querynum++;
  94. return $query;
  95. }
  96. function affected_rows() {
  97. return mysql_affected_rows($this->link);
  98. }
  99. function error() {
  100. return (($this->link) ? mysql_error($this->link) : mysql_error());
  101. }
  102. function errno() {
  103. return intval(($this->link) ? mysql_errno($this->link) : mysql_errno());
  104. }
  105. function result($query, $row) {
  106. $query = @mysql_result($query, $row);
  107. return $query;
  108. }
  109. function num_rows($query) {
  110. $query = mysql_num_rows($query);
  111. return $query;
  112. }
  113. function num_fields($query) {
  114. return mysql_num_fields($query);
  115. }
  116. function free_result($query) {
  117. return mysql_free_result($query);
  118. }
  119. function insert_id() {
  120. return ($id = mysql_insert_id($this->link)) >= 0 ? $id : $this->result($this->query("SELECT last_insert_id()"), 0);
  121. }
  122. function fetch_row($query) {
  123. $query = mysql_fetch_row($query);
  124. return $query;
  125. }
  126. function fetch_fields($query) {
  127. return mysql_fetch_field($query);
  128. }
  129. function version() {
  130. return mysql_get_server_info($this->link);
  131. }
  132. function close() {
  133. return mysql_close($this->link);
  134. }
  135. function halt($message = '', $sql = '') {
  136. $dberror = $this->error();
  137. $dberrno = $this->errno();
  138. echo "
  139. MySQL Error
  140. Message: $message
  141. SQL: $sql
  142. Error: $dberror
  143. Errno.: $dberrno
";
  • exit();
  • }
  • }
  • ?>
  • 复制代码

    调用示例:

    1. /****************************************
    2. *** mysql-rw-php version 0.1
    3. *** http://bbs.it-home.org
    4. *** http://code.google.com/p/mysql-rw-php/
    5. *** code modify from class_mysql.php (uchome)
    6. ****************************************/
    7. require_once('mysql_rw_php.class.php');
    8. //rw info
    9. $db_rw = array(
    10. 'dbhost'=>'bbs.it-home.org',
    11. 'dbuser'=>'jbxue',
    12. 'dbpw'=>'bbs.it-home.org',
    13. 'dbname'=>'test'
    14. );
    15. $db_ro = array(
    16. array(
    17. 'dbhost'=>'bbs.it-home.org:4306',
    18. 'dbuser'=>'jbxue',
    19. 'dbpw'=>'bbs.it-home.org'
    20. )
    21. );
    22. $DB = new mysql_rw_php;
    23. //connect Master
    24. $DB->connect($db_rw[dbhost], $db_rw[dbuser], $db_rw[dbpw], $db_rw[dbname]);
    25. //Method 1: connect one server
    26. $DB->connect_ro($db_ro[0][dbhost], $db_ro[0][dbuser], $db_ro[0][dbpw]);
    27. //Method 2: connect one server from a list by rand
    28. $DB->set_ro_list($db_ro);
    29. //send to rw
    30. $sql = "insert into a set a='test'";
    31. $DB->query($sql);
    32. //send to ro
    33. $sql = "select * from a";
    34. $qr = $DB->query($sql);
    35. while($row = $DB->fetch_array($qr)){
    36. echo $row[a];
    37. }
    38. ?>
    复制代码


    Statement
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    PHP's Purpose: Building Dynamic WebsitesPHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AM

    PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

    PHP: Handling Databases and Server-Side LogicPHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AM

    PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

    How do you prevent SQL Injection in PHP? (Prepared statements, PDO)How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AM

    Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

    PHP and Python: Code Examples and ComparisonPHP and Python: Code Examples and ComparisonApr 15, 2025 am 12:07 AM

    PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

    PHP in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AM

    PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

    PHP: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

    PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

    PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AM

    PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

    The Enduring Relevance of PHP: Is It Still Alive?The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AM

    PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Best Graphic Settings
    4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. How to Fix Audio if You Can't Hear Anyone
    4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    WWE 2K25: How To Unlock Everything In MyRise
    1 months agoBy尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    SublimeText3 Linux new version

    SublimeText3 Linux new version

    SublimeText3 Linux latest version

    SAP NetWeaver Server Adapter for Eclipse

    SAP NetWeaver Server Adapter for Eclipse

    Integrate Eclipse with SAP NetWeaver application server.

    VSCode Windows 64-bit Download

    VSCode Windows 64-bit Download

    A free and powerful IDE editor launched by Microsoft

    Dreamweaver Mac version

    Dreamweaver Mac version

    Visual web development tools

    Atom editor mac version download

    Atom editor mac version download

    The most popular open source editor