最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python使用MySQL8.2讀寫分離實現(xiàn)示例詳解

 更新時間:2023年11月21日 11:04:28   作者:愛可生開源社區(qū)  
在這篇文章中,我們將了解如何將?MySQL?8.2?的讀寫分離功能與?MySQL-Connector/Python?一起使用的方法示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪

引言

如您所知,MySQL 8.2 發(fā)布了最令人期待的功能之一:讀寫分離。

在這篇文章中,我們將了解如何將它與 MySQL-Connector/Python 一起使用。

架構

為了使用我們的 Python 程序,我們將使用 InnoDB Cluster。

以下是在 MySQL Shell 中查詢 Cluster 的狀態(tài):

JS > cluster.status()
{
    "clusterName": "fred", 
    "defaultReplicaSet": {
        "name": "default", 
        "primary": "127.0.0.1:3310", 
        "ssl": "REQUIRED", 
        "status": "OK", 
        "statusText": "Cluster is ONLINE and can tolerate up to ONE failure.", 
        "topology": {
            "127.0.0.1:3310": {
                "address": "127.0.0.1:3310", 
                "memberRole": "PRIMARY", 
                "mode": "R/W", 
                "readReplicas": {}, 
                "replicationLag": "applier_queue_applied", 
                "role": "HA", 
                "status": "ONLINE", 
                "version": "8.2.0"
            }, 
            "127.0.0.1:3320": {
                "address": "127.0.0.1:3320", 
                "memberRole": "SECONDARY", 
                "mode": "R/O", 
                "readReplicas": {}, 
                "replicationLag": "applier_queue_applied", 
                "role": "HA", 
                "status": "ONLINE", 
                "version": "8.2.0"
            }, 
            "127.0.0.1:3330": {
                "address": "127.0.0.1:3330", 
                "memberRole": "SECONDARY", 
                "mode": "R/O", 
                "readReplicas": {}, 
                "replicationLag": "applier_queue_applied", 
                "role": "HA", 
                "status": "ONLINE", 
                "version": "8.2.0"
            }
        }, 
        "topologyMode": "Single-Primary"
    }, 
    "groupInformationSourceMember": "127.0.0.1:3310"
}

JS > cluster.listRouters()
{
    "clusterName": "fred", 
    "routers": {
        "dynabook::system": {
            "hostname": "dynabook", 
            "lastCheckIn": "2023-11-09 17:57:59", 
            "roPort": "6447", 
            "roXPort": "6449", 
            "rwPort": "6446", 
            "rwSplitPort": "6450", 
            "rwXPort": "6448", 
            "version": "8.2.0"
        }
    }
}

MySQL Connector/Python

Python 程序使用 MySQL-Connector/Python 8.2.0。

初始化測試腳本代碼:

import mysql.connector
cnx = mysql.connector.connect(user='python',
                              passowrd='Passw0rd!Python',
                              host='127.0.0.1',
                              port='6450')
cursor = cnx.cursor()
query = ("""select member_role, @@port port
            from performance_schema.replication_group_members
            where member_id=@@server_uuid""")
for (role, port) in cursor:
    print("{} - {}".format(role, port))
cursor.close()
cnx.close()

我們可以測試一下:

$ python test_router.py
PRIMARY - 3310

很好,我們可以使用讀/寫分離端口(6540)連接到集群并執(zhí)行查詢……。哦 ?!但為什么我們會直達主實例呢?

我們不應該是去訪問只讀實例(副本實例)之一嗎?

autocommit

Connector/Python 默認禁用自動提交(請參閱 MySQLConnection.autocommit 屬性)。并且讀寫分離功能必須啟用自動提交才能正常工作。

在第 8 行上方添加以下代碼:

cnx.autocommit = True

然后我們可以再次運行該程序:

$ python test_router.py
SECONDARY - 3320
$ python test_router.py
SECONDARY - 3330

太棒了,達到預期效果工作!

查詢屬性

現(xiàn)在讓我們看看如何在主節(jié)點上強制執(zhí)行查詢。

MySQL Router 提供了使用查詢屬性來強制執(zhí)行讀/寫拆分決策的可能性:router.access_mode。

在執(zhí)行查詢 ( cursor.execute(query) ) 之前添加以下行:

cursor.add_attribute("router.access_mode", "read_write")

讓我們再執(zhí)行一次:

$ python test_router.py
PRIMARY - 3310

router.access_mode 可接受的值為:

  • auto
  • read_only
  • read_write

測試 DML 語句

讓我們嘗試一些不同的東西,我們將向表中插入行。

我們將使用下表:

CREATE TABLE `t1` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `port` int DEFAULT NULL,
  `role` varchar(15) DEFAULT NULL,
  `timestamp` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB ;

我們將使用以下 Python 腳本:

import mysql.connector
cnx = mysql.connector.connect(user='python',
                              password='Passw0rd!Python',
                              host='127.0.0.1',
                              port='6450',
                              database='test')
cnx.autocommit = True
cursor = cnx.cursor()
for i in range(3):
    query = ("""insert into t1 values(0, @@port, (
          select member_role
            from performance_schema.replication_group_members
            where member_id=@@server_uuid), now())""")
    cursor.execute(query)
cursor.close()
cnx.close()
for i in range(3):
    cnx = mysql.connector.connect(user='python',
                              password='Passw0rd!Python',
                              host='127.0.0.1',
                              port='6450',
                              database='test')
    cnx.autocommit = True
    cursor = cnx.cursor()
    query = ("""select *, @@port port_read from t1""")
    cursor.execute(query)
    for (id, port, role, timestamp, port_read) in cursor:
             print("{} : {}, {}, {} : read from {}".format(id,
                                             port,
                                             role,
                                             timestamp,
                                             port_read))
    cursor.close()
    cnx.close()

讓我們執(zhí)行它:

$ python test_router2.py
1 : 3310, PRIMARY, 2023-11-09 17:44:00 : read from 3330
2 : 3310, PRIMARY, 2023-11-09 17:44:00 : read from 3330
3 : 3310, PRIMARY, 2023-11-09 17:44:00 : read from 3330
1 : 3310, PRIMARY, 2023-11-09 18:44:00 : read from 3320
2 : 3310, PRIMARY, 2023-11-09 18:44:00 : read from 3320
3 : 3310, PRIMARY, 2023-11-09 18:44:00 : read from 3320
1 : 3310, PRIMARY, 2023-11-09 17:44:00 : read from 3330
2 : 3310, PRIMARY, 2023-11-09 17:44:00 : read from 3330
3 : 3310, PRIMARY, 2023-11-09 17:44:00 : read from 3330

我們可以看到?jīng)]有錯誤,并且我們寫入了主節(jié)點并從所有輔助節(jié)點讀取。

請小心,如果在寫入之前將 router.access_mode 的查詢屬性設置為 read_only(第 16 行),您將收到錯誤,因為副本節(jié)點上不允許寫入:

_mysql_connector.MySQLInterfaceError: The MySQL server is running with the --super-read-only option so it cannot execute this statement

事務

現(xiàn)在我們要玩一下事務。我們創(chuàng)建一個新腳本來執(zhí)行多個事務:

  • 自動提交中的讀操作
  • 事務中的讀操作(默認情況下,這是讀/寫事務)
  • 只讀事務中的讀操作
  • 具有多次插入和回滾的事務

這是程序的源碼:

import mysql.connector
cnx = mysql.connector.connect(user='python',
                              password='Passw0rd!Python',
                              host='127.0.0.1',
                              port='6450',
                              database='test')
cnx.autocommit = True
cursor = cnx.cursor()
query = ("""select member_role, @@port port
            from performance_schema.replication_group_members
            where member_id=@@server_uuid""")
cursor.execute(query)
for (role, port) in cursor:
    print("{} - {}".format(role, port))
cnx.start_transaction()
query = ("""select member_role, @@port port
            from performance_schema.replication_group_members
            where member_id=@@server_uuid""")
cursor.execute(query)
for (role, port) in cursor:
    print("{} - {}".format(role, port))
cnx.commit()
cnx.start_transaction(readonly=True)
query = ("""select member_role, @@port port
            from performance_schema.replication_group_members
            where member_id=@@server_uuid""")
cursor.execute(query)
for (role, port) in cursor:
    print("{} - {}".format(role, port))
cnx.commit()
cnx.start_transaction()
for i in range(3):
    query = ("""insert into t1 values(0, @@port, (
          select member_role
            from performance_schema.replication_group_members
            where member_id=@@server_uuid), now())""")
    cursor.execute(query)
cnx.rollback()
cursor.close()
cnx.close()

讓我們執(zhí)行腳本:

$ python test_router3.py
SECONDARY - 3320
PRIMARY - 3310
SECONDARY - 3320

我們可以看到,第一個操作到達了副本實例,第二個操作(即事務)到達了主節(jié)點。

只讀事務到達副本節(jié)點。

對于作為我們回滾事務一部分的多次寫入,我們沒有收到任何錯誤。

結論

我們已經(jīng)看到將 MySQL Connector/Python 與 MySQL 8.2 讀寫分離一起用于 InnoDB Cluster 是多么容易。

享受通過 MySQL Connector / Python 使用 MySQL 讀寫分離!更多關于Python MySQL8.2讀寫分離的資料請關注腳本之家其它相關文章!

相關文章

最新評論

平遥县| 镇原县| 和龙市| 平山县| 潼关县| 潜江市| 开远市| 子长县| 涿鹿县| 德清县| 开化县| 济南市| 浦城县| 久治县| 夏津县| 海原县| 桐乡市| 河间市| 长子县| 漾濞| 长宁区| 绵阳市| 宜城市| 乌什县| 瓦房店市| 铁岭县| 昌黎县| 合山市| 图们市| 民和| 澄城县| 荥阳市| 湘西| 渭源县| 南皮县| 鹤山市| 铜山县| 咸宁市| 阿克| 汾阳市| 镇赉县|