Home Backend Development PHP Tutorial mysql Proxy read-write separation configuration and php mysql read-write separation class

mysql Proxy read-write separation configuration and php mysql read-write separation class

Jul 25, 2016 am 08:56 AM

  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 of this Website
    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

    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

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

    JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

    How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

    Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

    How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

    How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

    Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

    The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

    How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

    How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

    Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

    Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

    How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

    Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

    See all articles