<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:media="http://search.yahoo.com/mrss/">
  <channel>
    <title>Replication｜林鼎淵 Dean Lin</title>
    <link>https://deanlin.net/tags/replication/</link>
    <image><url>https://deanlin.net/images/author_hu_aa256fc934e9a932.jpg</url><title>Replication｜林鼎淵 Dean Lin</title><link>https://deanlin.net/tags/replication/</link><width>144</width><height>144</height></image>
    <description>林鼎淵（Dean Lin）的部落格：生成式 AI 企業內訓講師、外商資安公司軟體專家、7 本書作者。400 多篇文章用白話分享生成式 AI 實戰、Claude Code 與 Vibe Coding 教學、團隊合作與職場成長。</description>
    <generator>Hugo</generator>
    <language>zh-tw</language>
    <copyright>© 2020–2026 林鼎淵 Dean Lin</copyright>
    <lastBuildDate>Sun, 03 Oct 2021 07:33:32 +0800</lastBuildDate>
    <atom:link href="https://deanlin.net/tags/replication/index.xml" rel="self" type="application/rss+xml" />
    <item>
      <title>[面試][資料庫]面對高流量的的系統，會採取哪些措施？</title>
      <link>https://deanlin.net/blog/202110/fullstack-career-notes-day-18/</link>
      <pubDate>Sun, 03 Oct 2021 07:33:32 +0800</pubDate>
      <guid>https://deanlin.net/blog/202110/fullstack-career-notes-day-18/</guid>
      <dc:creator>林鼎淵</dc:creator>
      <category>職涯成長</category>
      <description>除非你的實戰經驗超級豐富，不然在面試時一定會遇到不熟悉的議題；面對無法回答的問題，我個人會老實向面試官表明自己沒有這方面的經驗，會持續學習，瞎掰答案容易讓對方覺得你以後進來公司也會這樣做事。</description>
      <media:content url="https://deanlin.net/blog/202110/fullstack-career-notes-day-18/images/cover_hu_1dbb5eb5480f50de.jpg" medium="image" type="image/jpeg" width="1200" height="675" />
      <content:encoded><![CDATA[<blockquote>
<p>經驗不夠，讀書來湊。</p>
</blockquote>
<p>除非你的實戰經驗超級豐富，不然在面試時一定會遇到不熟悉的議題；面對無法回答的問題，我個人會老實向面試官<mark>表明自己沒有這方面的經驗，會持續學習</mark>，瞎掰答案容易讓對方覺得你以後進來公司也會這樣做事。</p>
<p>不過有些議題雖然實際碰過的人不多，但網路上有很多資源可以學習；如果剛好有研究過相關資料，筆者會回答：「<mark>雖然沒有在工作上使用過，但在下班後我有特別研究這個議題，如果思路上有不對的部分還請各位面試官批評指教。</mark>」</p>
<h2 id="大綱">大綱<a class="h-anchor" href="#%e5%a4%a7%e7%b6%b1" aria-label="這個段落的連結"></a></h2>
<ol>
<li><strong>面對高流量的的系統，會採取哪些措施？</strong>
<ul>
<li>1.1 面試官為什麼會問？</li>
<li>1.2 面試官想從答案確認什麼？</li>
<li>1.3 筆者提供的簡答</li>
</ul>
</li>
<li><strong>回答問題所需具備的知識</strong>
<ul>
<li>2.1 負載平衡（Load Balance）</li>
<li>2.2 主從式架構（Master Slave Repliaction）</li>
<li>2.3 資料庫讀寫分離（read/write splitting）</li>
<li>2.4 垂直切分（vertical-partition）</li>
<li>2.5 水平切分（horizontal-partition）</li>
<li>2.6 分表（Partition Table）</li>
</ul>
</li>
<li><strong>衍伸問題</strong>
<ul>
<li>3.1 有遇過主從複製延遲問題嗎？怎麼解決？</li>
<li>3.2 分散式資料庫（Distributed Database）有哪些優點跟缺點？</li>
</ul>
</li>
</ol>
<hr>
<h2 class="h-nomark" id="1-面對高流量的的系統會採取哪些措施">1. 面對高流量的的系統，會採取哪些措施？<a class="h-anchor" href="#1-%e9%9d%a2%e5%b0%8d%e9%ab%98%e6%b5%81%e9%87%8f%e7%9a%84%e7%9a%84%e7%b3%bb%e7%b5%b1%e6%9c%83%e6%8e%a1%e5%8f%96%e5%93%aa%e4%ba%9b%e6%8e%aa%e6%96%bd" aria-label="這個段落的連結"></a></h2>
<h3 class="h-nomark" id="11-面試官為什麼會問">1.1 面試官為什麼會問？<a class="h-anchor" href="#11-%e9%9d%a2%e8%a9%a6%e5%ae%98%e7%82%ba%e4%bb%80%e9%ba%bc%e6%9c%83%e5%95%8f" aria-label="這個段落的連結"></a></h3>
<p>如果面試的公司在做<mark>金融、電商、社交、媒體</mark>的系統，那這題算是該<mark>職缺所需具備的技術</mark>；儘管也可以透過後天培養，但如果有現成的人才，誰會想要花時間做訓練。</p>
<hr>
<h3 class="h-nomark" id="12-面試官想從答案確認什麼">1.2 面試官想從答案確認什麼？<a class="h-anchor" href="#12-%e9%9d%a2%e8%a9%a6%e5%ae%98%e6%83%b3%e5%be%9e%e7%ad%94%e6%a1%88%e7%a2%ba%e8%aa%8d%e4%bb%80%e9%ba%bc" aria-label="這個段落的連結"></a></h3>
<ul>
<li>要如何設計才能讓前後端伺服器承受大流量情境</li>
<li>資料庫為了處理大流量，可以做哪些調整</li>
<li>這些處理的方式在實務上是否有遇到問題，如何去驗證你的想法是否正確</li>
</ul>
<hr>
<h3 class="h-nomark" id="13-筆者提供的簡答">1.3 筆者提供的簡答<a class="h-anchor" href="#13-%e7%ad%86%e8%80%85%e6%8f%90%e4%be%9b%e7%9a%84%e7%b0%a1%e7%ad%94" aria-label="這個段落的連結"></a></h3>
<p>前後端我會用 <code>Load Balance</code> 緩解 Server 的壓力；在資料庫方面則採取<mark>主從式架構</mark>、<mark>讀寫分離</mark>來降低壓力。</p>
<p>如果經過上面的設計後，資料庫還是無法負荷，可以先用業務種類作為切分條件；以電商系統來說我會先做<mark>垂直切分（vertical-partition）</mark>，像是將商品、訂單、明細拆成 3 個資料庫，以此大幅降低單一資料庫被存取的流量。</p>
<p>如果垂直切分後還是在某個資料庫遇到瓶頸，像是訂單的的資料庫內容遠大於其他資料庫；此時會再做<mark>水平切分（horizontal-partition</mark>），可能會依照訂單的地區再切分成幾個資料庫。</p>
<hr>
<h2 class="h-nomark" id="2-回答問題所需具備的知識">2. 回答問題所需具備的知識<a class="h-anchor" href="#2-%e5%9b%9e%e7%ad%94%e5%95%8f%e9%a1%8c%e6%89%80%e9%9c%80%e5%85%b7%e5%82%99%e7%9a%84%e7%9f%a5%e8%ad%98" aria-label="這個段落的連結"></a></h2>
<h3 class="h-nomark" id="21-負載平衡load-balance">2.1 負載平衡（Load Balance）<a class="h-anchor" href="#21-%e8%b2%a0%e8%bc%89%e5%b9%b3%e8%a1%a1load-balance" aria-label="這個段落的連結"></a></h3>
<p>無論是電商還是媒體的系統，幾乎長時間都要面臨大流量的議題，想當然<mark>一台伺服器是無法承受高流量的</mark>。</p>
<p>而負載平衡（Load Balance）就是為了解決這個問題而誕生的，既然 1 台 Server 無法承受 10 萬流量；那我們就用 100 台 Server 來分散流量吧！</p>
<p>早期做法是先預估流量，然後開啟對應數量的 Server 來作分流；這樣的做法多開頂多浪費錢，但如果估計錯誤少開就可能導致系統當機。</p>
<p>所以像是 <code>GCP、AWS</code> 這類雲端廠商所提供的負載平衡（Load Balance），就有<mark>依照伺服器健康程度來做自動擴展（auto-scaling）</mark>的服務，讓大家不需要去猜要開多少台才合適；如果有使用 <code>Kubernetes</code> 並設定好相關參數，在遇到大流量時也會<mark>自動擴展 Pod</mark> 來應付。</p>
<blockquote>
<p>有時會被問到你的系統過去遇到最高的 QPS 是多少，QPS 指的是每秒查詢率（Queries Per Second）。</p>
</blockquote>
<hr>
<h3 class="h-nomark" id="22-主從式架構master-slave-replication">2.2 主從式架構（Master Slave Replication）<a class="h-anchor" href="#22-%e4%b8%bb%e5%be%9e%e5%bc%8f%e6%9e%b6%e6%a7%8bmaster-slave-replication" aria-label="這個段落的連結"></a></h3>
<p>上面提到的負載平衡只能做到讓網頁成功打開，如果資料庫 Server 沒有做對應的設計，這樣的大流量跟 <code>DDOS</code> 根本沒兩樣，足以讓資料庫 Server 陣亡；所以有時會發現<mark>進入某個網站後可以看到 UI 佈局，卻沒有資料顯示</mark>。</p>
<p>下面我們先探討主從式架構，目標是<mark>先讓資料庫 Server 能承受大流量的檢索</mark>，接著再來考慮寫入問題。</p>
<ul>
<li>
<p><strong>為什麼需要 Master Slave Replication 的架構？</strong></p>
<ul>
<li><strong>網站需要面對大流量</strong><br>有些網站<mark>無論哪個時段都會被大量檢索</mark>，如果資料庫只用一個 Server 來處理會無法負荷高流量。</li>
<li><strong>資料庫內容需要被分析</strong><br>公司如果有<mark>資料分析</mark>部門，他們也會隨時監控資料庫的變化來產生報表，但如果跟一般使用者一樣 query 同一台 Server，會使這台 Server 增加不必要的負荷，甚至導致使用者體驗下降。</li>
</ul>
</li>
<li>
<p><strong>Master Slave Replication 為什麼能夠解決這些問題？</strong></p>
<ul>
<li><strong>主從式架構</strong><br>將資料庫的 Server 區分成 Master(1 台) 與 Slave(N 台) 兩種，<mark>Master 負責資料寫入，Slave 提供資料檢索</mark>；這樣就把壓力分散到幾台 Server 上面。</li>
<li><strong>資料庫同步</strong><br>Slave 會同步 Master 的資料，這樣除了<mark>分散 Server 壓力外，資料也獲得了備份</mark>。</li>
</ul>
</li>
<li>
<p><strong>Master Slave Replication 的架構</strong></p>
<ul>
<li>在 Master 的 Server 執行的 SQL command 會被記錄在 Binary Log 裡面。</li>
<li>Master 將 Binary Log 傳送到 Slave 的 Relay Log。</li>
<li>Slave 依據 Relay Log 做資料的變更。</li>
</ul>
<p><img src="https://deanlin.net/blog/202110/fullstack-career-notes-day-18/images/fullstack-career-notes-day-18-01.webp" width="1024" height="613" alt="2.2 主從式架構（Master Slave Replication）（圖 1）" fetchpriority="high" decoding="async"></p>
<blockquote>
<p>Relay Log 與 Binary Log 檔案格式、內容都一樣，不同在於 Slave 在執行完 Relay Log 的 SQL 之後，會自己刪除當前的 Relay Log。</p>
</blockquote>
</li>
</ul>
<hr>
<h3 class="h-nomark" id="23-資料庫讀寫分離readwrite-splitting">2.3 資料庫讀寫分離（read/write splitting）<a class="h-anchor" href="#23-%e8%b3%87%e6%96%99%e5%ba%ab%e8%ae%80%e5%af%ab%e5%88%86%e9%9b%a2readwrite-splitting" aria-label="這個段落的連結"></a></h3>
<p>我們知道 Master Server 是用來更新資料，Slave Server 是用來檢索資料；但<mark>它們都是獨立的 ip</mark>，使用者在存取資料庫的時候並不知道要使用哪一台 Server ，除非你的 Slave Server 只用來做資料分析。</p>
<p>因此我們要在中間設計一台 <code>Proxy Server</code>，準確地將 SQL 指令分流到正確的 Server。</p>
<p><img src="https://deanlin.net/blog/202110/fullstack-career-notes-day-18/images/fullstack-career-notes-day-18-02.webp" width="1024" height="652" alt="2.3 資料庫讀寫分離（read/write splitting）（圖 2）" loading="lazy" decoding="async"></p>
<blockquote>
<p>媒體類型的平台在讀的需求很高，寫的需求相對低；因此多會採用主從式架構做讀寫分離。</p>
</blockquote>
<hr>
<h3 class="h-nomark" id="24-垂直切分vertical-partition">2.4 垂直切分（vertical-partition）<a class="h-anchor" href="#24-%e5%9e%82%e7%9b%b4%e5%88%87%e5%88%86vertical-partition" aria-label="這個段落的連結"></a></h3>
<p>在讀寫分離後，儘管讀的部分沒有問題；但把寫入的工作交給一個資料庫負責還是會遇到瓶頸。</p>
<p>此時資料庫的垂直切分（vertical-partition）就派上用場了；以商城舉例，商品、訂單、付款明細<mark>各自的業務量都很大</mark>，所以我們可以先依照業務性質把它<mark>拆分成 3 個資料庫</mark>，如此設計可以分散資料庫被存取的流量，來提升系統穩定度。</p>
<hr>
<h3 class="h-nomark" id="25-水平切分horizontal-partition">2.5 水平切分（horizontal-partition）<a class="h-anchor" href="#25-%e6%b0%b4%e5%b9%b3%e5%88%87%e5%88%86horizontal-partition" aria-label="這個段落的連結"></a></h3>
<p>在垂直切分後，有些資料庫還是會遇到瓶頸，像是訂單的資料庫可能遠遠大於其他資料庫。</p>
<p>這時我們就會需要做水平切分（horizontal-partition），將 DB 中<mark>同一類型的資料依據特定邏輯拆分成多個 DB</mark>；像是訂單可能來自於世界各地，所以我們可能就以地區（ex：亞洲、歐洲、美洲&hellip;）做切分的邏輯。</p>
<hr>
<h3 class="h-nomark" id="26-分區表partition-table">2.6 分區表（Partition Table）<a class="h-anchor" href="#26-%e5%88%86%e5%8d%80%e8%a1%a8partition-table" aria-label="這個段落的連結"></a></h3>
<p>資料庫在經歷了垂直切分與水平切分後，寫入遇到的瓶頸就差不多解決了。</p>
<p>但接下來會遇到另外一個問題，Table 中的資料會隨著時間會不斷增長，如果<mark>資料量龐大到就算建立 Index 都無法提升效能</mark>；此時就要考慮將 Table 依照特定邏輯做切割，通常會選擇<mark>自動產生的 id、日期</mark>這類的欄位作為切割依據，在 Table 被切割後因為資料量變少，所以搜尋效能隨之提升。</p>
<p><strong>特別提醒</strong>：如果這個 Table 有 Primary key 或是 Unique key，<mark>分區鍵（Partition Key）必須是 Primary key 或是 Unique key 組成的一個部分</mark>。</p>
<hr>
<h2 class="h-nomark" id="3-衍伸問題">3. 衍伸問題<a class="h-anchor" href="#3-%e8%a1%8d%e4%bc%b8%e5%95%8f%e9%a1%8c" aria-label="這個段落的連結"></a></h2>
<h3 class="h-nomark" id="31-有遇過主從複製延遲問題嗎怎麼解決">3.1 有遇過主從複製延遲問題嗎？怎麼解決？<a class="h-anchor" href="#31-%e6%9c%89%e9%81%87%e9%81%8e%e4%b8%bb%e5%be%9e%e8%a4%87%e8%a3%bd%e5%bb%b6%e9%81%b2%e5%95%8f%e9%a1%8c%e5%97%8e%e6%80%8e%e9%ba%bc%e8%a7%a3%e6%b1%ba" aria-label="這個段落的連結"></a></h3>
<p><mark>考點：瞭解求職者的實務經驗</mark></p>
<p>當時我使用的是 MySQL 資料庫，用 sysbench 這個測試工具模擬<mark>短時間執行大量的 SQL command</mark>（ex：Table 內容大量更新、Index 建立）；但去 Slave 的資料庫確認同步狀況時，卻發現並沒有完全同步 Master 的資料。</p>
<p>經過研究後發現 MySQL 預設的 Process 只有一個，因此累積了很多尚未同步的 SQL Command；將 MySQL 調整成<code>多 Process</code>後，Slave同步的效率就大幅提升了。</p>
<blockquote>
<p>可透過修改「slave_parallel_type、slave_parallel_workers」這兩個變數來調整 Process數量。</p>
</blockquote>
<hr>
<h3 class="h-nomark" id="32-分散式資料庫distributed-database有哪些優點跟缺點">3.2 分散式資料庫（Distributed Database）有哪些優點跟缺點？<a class="h-anchor" href="#32-%e5%88%86%e6%95%a3%e5%bc%8f%e8%b3%87%e6%96%99%e5%ba%abdistributed-database%e6%9c%89%e5%93%aa%e4%ba%9b%e5%84%aa%e9%bb%9e%e8%b7%9f%e7%bc%ba%e9%bb%9e" aria-label="這個段落的連結"></a></h3>
<p><mark>考點：對分散式資料庫的認知程度</mark></p>
<ul>
<li><strong>優點</strong>
<ul>
<li><strong>穩定度與可用性提升</strong><br>過去靠一個資料庫打天下，如果這個資料庫掛了一切都涼了；但建立 Replication 制度後，Slave 資料庫除了可以<mark>分擔流量</mark>，在 Master 資料庫發生問題也可以讓其他 <mark>Slave 資料庫轉成 Master</mark>，不影響整體系統。</li>
<li><strong>擴充性</strong><br>因為資料分散儲存在多個資料庫，如果有更多的需求只要增加伺服器時設定即可。</li>
</ul>
</li>
<li><strong>缺點</strong>
<ul>
<li><strong>開發困難度</strong><br>因為資料分散在各個資料庫，所以對開發人員的經驗以及技術要求更高；如果設計不良反而會影響到資料安全性。</li>
</ul>
</li>
</ul>
<hr>
<blockquote>
<p>紙上得來終覺淺，絕知此事要躬行。 ── 陸游</p>
</blockquote>
<p>如果大家想要<mark>親手實作</mark>今天的面試題，在參考資源中有分享一些實作流程喔！</p>
<p>感謝大家的閱讀，如果喜歡我的文章可以<code>訂閱</code>接收通知；如果有幫助到你，按<code>Like</code>可以讓我更有寫文的動力，我們明天見～</p>
<h3 id="參考資源">參考資源<a class="h-anchor" href="#%e5%8f%83%e8%80%83%e8%b3%87%e6%ba%90" aria-label="這個段落的連結"></a></h3>
<ol>
<li><a href="https://medium.com/dean-lin/16d0a0fa1d04">MySQL Master Slave Replication 主從式架構設定教學(筆者部落格)</a></li>
<li><a href="https://medium.com/dean-lin/72759b1b1b33">Ubuntu 用 Atlas 實現 MySQL Proxy 讀寫分離(筆者部落格)</a></li>
<li><a href="https://medium.com/dean-lin/ec59acea6052">用 sysbench 測試 MySQL 性能(筆者部落格)</a></li>
<li><a href="https://medium.com/dean-lin/67c2aec6b021">解決 MySQL 主從複製的延遲問題(筆者部落格)</a></li>
<li><a href="https://ithelp.ithome.com.tw/articles/10227066">30-26 之資料庫層的擴展 - 分庫分表架構</a></li>
<li><a href="https://codingnote.cc/zh-tw/p/215115/">MySQL 分區</a></li>
</ol>
<hr>
<hr>
<blockquote>
<p><img src="https://deanlin.net/blog/202110/fullstack-career-notes-day-18/images/fullstack-career-notes-day-18-03.webp" width="1024" height="233" alt="參考資源（圖 3）" loading="lazy" decoding="async"></p>
<p>在許多人的幫助下，本系列文章已成功出版，除了添加新的篇章，更完善了每個案例的應對進退；如果對現在的職涯感到迷茫，也許這本書能帶給你不一樣的觀點～</p>
<p><strong>天瓏書局：</strong> <a href="https://www.tenlong.com.tw/products/9786263334571">https://www.tenlong.com.tw/products/9786263334571</a></p>
</blockquote>
]]></content:encoded>
    </item>
    <item>
      <title>MySQL Master Slave Replication 主從式架構設定教學</title>
      <link>https://deanlin.net/blog/202103/mysql-master-slave-replication/</link>
      <pubDate>Thu, 25 Mar 2021 16:45:58 +0800</pubDate>
      <guid>https://deanlin.net/blog/202103/mysql-master-slave-replication/</guid>
      <dc:creator>林鼎淵</dc:creator>
      <category>技術教學</category>
      <description>Master Slave Replication 是一個 Web 工程師需要具備的基礎概念，我們可以透過這個技術有效的降低 Database server 負荷，同時給使用者提供更穩定順暢的體驗；本文除了讓你了解這個技術的原理外還會以 MySQL…</description>
      <media:content url="https://deanlin.net/blog/202103/mysql-master-slave-replication/images/mysql-master-slave-replication-og_hu_19e34a7748bd18bb.jpg" medium="image" type="image/jpeg" width="1200" height="675" />
      <content:encoded><![CDATA[<p><img src="https://deanlin.net/blog/202103/mysql-master-slave-replication/images/mysql-master-slave-replication-01.webp" width="1400" height="783" alt="MySQL Master Slave Replication 主從式架構設定教學（圖 1）" fetchpriority="high" decoding="async"></p>
<p>Master Slave Replication 是一個 Web 工程師需要具備的基礎概念，我們可以透過這個技術有效的降低 Database server 負荷，同時給使用者提供更穩定順暢的體驗；本文除了讓你了解這個技術的原理外還會以 MySQL 這門資料庫語言一步步透過實作讓你理解如何實現它。</p>
<pre tabindex="0"><code>一、30 秒認識 Master Slave Replication 是什麼
  ∙ 為什麼需要 Master Slave Replication 的架構？
  ∙ Master Slave Replication 為什麼能夠解決這些問題？
  ∙ Master Slave Replication 的架構
二、實作 MySQL Master Slave replication
  ∙ 前置作業
  ∙ 建立MySQL Replication
三、驗證 Master、Slave DB 是否同步
</code></pre><h2 id="一30-秒認識-master-slave-replication-是什麼">一、30 秒認識 Master Slave Replication 是什麼<a class="h-anchor" href="#%e4%b8%8030-%e7%a7%92%e8%aa%8d%e8%ad%98-master-slave-replication-%e6%98%af%e4%bb%80%e9%ba%bc" aria-label="這個段落的連結"></a></h2>
<h3 id="為什麼需要-master-slave-replication-的架構">為什麼需要 Master Slave Replication 的架構？<a class="h-anchor" href="#%e7%82%ba%e4%bb%80%e9%ba%bc%e9%9c%80%e8%a6%81-master-slave-replication-%e7%9a%84%e6%9e%b6%e6%a7%8b" aria-label="這個段落的連結"></a></h3>
<ul>
<li><strong>網站需要面對大流量</strong>：新聞媒體類的網站無論哪個時段都會被大量的檢索，如果資料庫只用一個 server 來處理會無法負荷瞬間的高流量。</li>
<li><strong>資料庫內容需要被分析</strong>：公司如果有資料分析部門，他們也會隨時監控資料庫的變化來產生報表，但如果跟一般使用者一樣 query 同一台 server 會使這台 server 增加不必要的負荷導致使用者體驗下降。</li>
</ul>
<h3 id="master-slave-replication-為什麼能夠解決這些問題">Master Slave Replication 為什麼能夠解決這些問題？<a class="h-anchor" href="#master-slave-replication-%e7%82%ba%e4%bb%80%e9%ba%bc%e8%83%bd%e5%a4%a0%e8%a7%a3%e6%b1%ba%e9%80%99%e4%ba%9b%e5%95%8f%e9%a1%8c" aria-label="這個段落的連結"></a></h3>
<ul>
<li><strong>主從式架構</strong>：將資料庫的 server 區分成 Master(1台) 與 Slave(N台) 兩種，Master 負責資料寫入，Slave 提供資料檢索；這樣就把壓力分散到幾台 Server 上面。</li>
<li><strong>資料庫同步</strong>：Slave 會同步 Master 的資料，這樣除了分散 server 壓力外，資料也獲得了備份。</li>
</ul>
<h3 id="master-slave-replication-的架構">Master Slave Replication 的架構<a class="h-anchor" href="#master-slave-replication-%e7%9a%84%e6%9e%b6%e6%a7%8b" aria-label="這個段落的連結"></a></h3>
<ol>
<li>在 master 的 server 執行的 SQL command 會被記錄在 Binary Log 裡面</li>
<li>master 將 Binary Log 傳送到 slave 的 Relay Log</li>
<li>slave 依據 Relay Log 做資料的變更</li>
</ol>
<figure class="figure"><img src="https://deanlin.net/blog/202103/mysql-master-slave-replication/images/mysql-master-slave-replication-02.webp" width="1194" height="738" alt="Relay Log 與 Binary Log檔案格式、內容都一樣，不同在於 slave 在執行完 Relay Log 的 SQL 之後，會自己刪除當前的 Relay Log" loading="lazy" decoding="async">
  <figcaption>Relay Log 與 Binary Log檔案格式、內容都一樣，不同在於 slave 在執行完 Relay Log 的 SQL 之後，會自己刪除當前的 Relay Log</figcaption>
</figure>

<h2 id="二實作-mysql-master-slave-replication">二、實作 MySQL Master Slave replication<a class="h-anchor" href="#%e4%ba%8c%e5%af%a6%e4%bd%9c-mysql-master-slave-replication" aria-label="這個段落的連結"></a></h2>
<h2 id="前置作業">前置作業<a class="h-anchor" href="#%e5%89%8d%e7%bd%ae%e4%bd%9c%e6%a5%ad" aria-label="這個段落的連結"></a></h2>
<h3 id="-準備兩台-ubuntu-server-自己實驗建議使用-vmware筆者環境配置如下">準備兩台 ubuntu server (自己實驗建議使用 VMWARE)，筆者環境配置如下<a class="h-anchor" href="#-%e6%ba%96%e5%82%99%e5%85%a9%e5%8f%b0-ubuntu-server-%e8%87%aa%e5%b7%b1%e5%af%a6%e9%a9%97%e5%bb%ba%e8%ad%b0%e4%bd%bf%e7%94%a8-vmware%e7%ad%86%e8%80%85%e7%92%b0%e5%a2%83%e9%85%8d%e7%bd%ae%e5%a6%82%e4%b8%8b" aria-label="這個段落的連結"></a></h3>
<blockquote>
<p>硬體配置一定會影響到效能，筆者只是建置一個提供實驗的環境而已</p>
</blockquote>
<ul>
<li>OS version：ubuntu 16.04</li>
<li>RAM：1G</li>
<li>ROM：8G</li>
</ul>
<h3 id="-給兩台-sever-安裝-mysql">給兩台 sever 安裝 MySQL<a class="h-anchor" href="#-%e7%b5%a6%e5%85%a9%e5%8f%b0-sever-%e5%ae%89%e8%a3%9d-mysql" aria-label="這個段落的連結"></a></h3>
<p>安裝指令如下</p>
<div class="highlight"><pre tabindex="0" style="color:#e6edf3;background-color:#0d1117;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-bash" data-lang="bash"><span style="display:flex;"><span>sudo apt update
</span></span><span style="display:flex;"><span>sudo apt install mysql-server
</span></span></code></pre></div><p>安裝完成後你可以先登入 MySQL 看看安裝版本資訊</p>
<div class="highlight"><pre tabindex="0" style="color:#e6edf3;background-color:#0d1117;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-bash" data-lang="bash"><span style="display:flex;"><span>sudo mysql -u root -p
</span></span></code></pre></div><p><img src="https://deanlin.net/blog/202103/mysql-master-slave-replication/images/mysql-master-slave-replication-03.webp" width="1400" height="491" alt="給兩台 sever 安裝 MySQL（圖 3）" loading="lazy" decoding="async"></p>
<h2 id="建立mysql-replication">建立MySQL Replication<a class="h-anchor" href="#%e5%bb%ba%e7%ab%8bmysql-replication" aria-label="這個段落的連結"></a></h2>
<h3 id="-master-server-設定">Master server 設定<a class="h-anchor" href="#-master-server-%e8%a8%ad%e5%ae%9a" aria-label="這個段落的連結"></a></h3>
<p><strong>STEP 1</strong>：設定 Master server 的 my.cnf</p>
<div class="highlight"><pre tabindex="0" style="color:#e6edf3;background-color:#0d1117;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-bash" data-lang="bash"><span style="display:flex;"><span>sudo vi /etc/mysql/my.cnf
</span></span></code></pre></div><pre tabindex="0"><code>[mysqld]
# 在這裡設定已蓋過預設的127.0.0.1(只能連本機)
bind-address = 0.0.0.0

# id為唯一值，每個server不可重覆
server-id = 1

# 指定產生bin log檔案名稱，使MySQL記錄所有DB交易記錄
log-bin=mysql-bin
</code></pre><p class="code-source">原始碼：<a href="https://gist.github.com/dean9703111/a555262a58eb9245c7ffcbcf891791ca" rel="noopener">my.cnf</a>（GitHub Gist）</p>
<p>儲存後，重啟 MySQL 才會生效</p>
<div class="highlight"><pre tabindex="0" style="color:#e6edf3;background-color:#0d1117;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-bash" data-lang="bash"><span style="display:flex;"><span>sudo /etc/init.d/mysql restart
</span></span></code></pre></div><p><strong>STEP 2</strong>：在 Master server 建立給 Slave 複製資料的帳號</p>
<p>登入 MySQL</p>
<div class="highlight"><pre tabindex="0" style="color:#e6edf3;background-color:#0d1117;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-bash" data-lang="bash"><span style="display:flex;"><span>sudo mysql -u root -p
</span></span></code></pre></div><p>建立有 REPLICATION、SLAVE 權限的 user 帳號</p>
<div class="highlight"><pre tabindex="0" style="color:#e6edf3;background-color:#0d1117;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-sql" data-lang="sql"><span style="display:flex;"><span><span style="color:#8b949e;font-style:italic">/*建立使用者*/</span><span style="color:#6e7681">
</span></span></span><span style="display:flex;"><span>mysql<span style="color:#ff7b72;font-weight:bold">&gt;</span><span style="color:#6e7681"> </span><span style="color:#ff7b72">CREATE</span><span style="color:#6e7681"> </span><span style="color:#ff7b72">USER</span><span style="color:#6e7681"> </span><span style="color:#a5d6ff">&#39;account&#39;</span><span style="color:#ff7b72;font-weight:bold">@</span><span style="color:#a5d6ff">&#39;ip&#39;</span><span style="color:#6e7681"> </span>IDENTIFIED<span style="color:#6e7681"> </span><span style="color:#ff7b72">BY</span><span style="color:#6e7681"> </span><span style="color:#a5d6ff">&#39;password&#39;</span>;<span style="color:#6e7681">
</span></span></span><span style="display:flex;"><span><span style="color:#8b949e;font-style:italic">/*給使用者權限*/</span><span style="color:#6e7681">
</span></span></span><span style="display:flex;"><span>mysql<span style="color:#ff7b72;font-weight:bold">&gt;</span><span style="color:#6e7681"> </span><span style="color:#ff7b72">GRANT</span><span style="color:#6e7681"> </span>REPLICATION<span style="color:#6e7681"> </span>SLAVE<span style="color:#6e7681"> </span><span style="color:#ff7b72">ON</span><span style="color:#6e7681"> </span><span style="color:#ff7b72;font-weight:bold">*</span>.<span style="color:#ff7b72;font-weight:bold">*</span><span style="color:#6e7681"> </span><span style="color:#ff7b72">TO</span><span style="color:#6e7681"> </span><span style="color:#a5d6ff">&#39;account&#39;</span><span style="color:#ff7b72;font-weight:bold">@</span><span style="color:#a5d6ff">&#39;ip&#39;</span>;<span style="color:#6e7681">
</span></span></span><span style="display:flex;"><span><span style="color:#8b949e;font-style:italic">/*使權限生效*/</span><span style="color:#6e7681">
</span></span></span><span style="display:flex;"><span>mysql<span style="color:#ff7b72;font-weight:bold">&gt;</span><span style="color:#6e7681"> </span>FLUSH<span style="color:#6e7681"> </span><span style="color:#ff7b72">PRIVILEGES</span>;<span style="color:#6e7681">
</span></span></span></code></pre></div><p class="code-source">原始碼：<a href="https://gist.github.com/dean9703111/68f42b828e24df0209600dee7a7030c7" rel="noopener">create_slave_user.sql</a>（GitHub Gist）</p>
<p><strong>STEP 3</strong>：備份 Master server 的 DB</p>
<blockquote>
<p>執行此步驟時如果系統已經上線，一定要發出公告說明系統維護時間</p>
</blockquote>
<p>在完成 DB Replication 前，為了保證 Master 與 Slave 的資料相同，你需要先把 DB Lock 成 read only：</p>
<pre tabindex="0"><code>mysql&gt; FLUSH TABLES WITH READ LOCK;
</code></pre><p>備份指令：</p>
<pre tabindex="0"><code>mysqldump -uroot -p  --all-databases &gt; master.sql
</code></pre><p>解除 read only：</p>
<pre tabindex="0"><code>mysql&gt; UNLOCK TABLES;
</code></pre><p><strong>STEP 4</strong>：檢查 Master 是否已經啟動</p>
<pre tabindex="0"><code>mysql&gt; SHOW MASTER STATUS \G
</code></pre><p><img src="https://deanlin.net/blog/202103/mysql-master-slave-replication/images/mysql-master-slave-replication-04.webp" width="1142" height="330" alt="Master server 設定（圖 4）" loading="lazy" decoding="async"></p>
<h3 id="-slave-server-設定">Slave server 設定<a class="h-anchor" href="#-slave-server-%e8%a8%ad%e5%ae%9a" aria-label="這個段落的連結"></a></h3>
<p><strong>STEP 1</strong>：將剛剛備份的 <code>master.sql</code> 還原到 Slave server 的 DB</p>
<p>先複製 master.sql 到 Slave server 的目錄下</p>
<div class="highlight"><pre tabindex="0" style="color:#e6edf3;background-color:#0d1117;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-bash" data-lang="bash"><span style="display:flex;"><span>sudo scp master.sql &lt;username&gt;@&lt;IP or hostname&gt;:&lt;Destination&gt;
</span></span></code></pre></div><p>下指令還原 DB</p>
<pre tabindex="0"><code>mysql -u root -p — default-character-set=utf8 &lt; master.sql
</code></pre><h3 id="step-2設定-slave-server-的-mycnf">STEP 2：設定 Slave server 的 my.cnf<a class="h-anchor" href="#step-2%e8%a8%ad%e5%ae%9a-slave-server-%e7%9a%84-mycnf" aria-label="這個段落的連結"></a></h3>
<div class="highlight"><pre tabindex="0" style="color:#e6edf3;background-color:#0d1117;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-bash" data-lang="bash"><span style="display:flex;"><span>sudo vi /etc/mysql/my.cnf
</span></span></code></pre></div><pre tabindex="0"><code>[mysqld]
#注意：不可與剛剛設定的 Master 重複
server-id=2 

#Slave server 的 DB 開啟唯獨避免被寫入
read-only=on
</code></pre><p class="code-source">原始碼：<a href="https://gist.github.com/dean9703111/54144c2099368bfc91f2681a47f9bf94" rel="noopener">slave_my.cnf</a>（GitHub Gist）</p>
<p>儲存後，重啟 MySQL 才會生效</p>
<div class="highlight"><pre tabindex="0" style="color:#e6edf3;background-color:#0d1117;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-bash" data-lang="bash"><span style="display:flex;"><span>sudo /etc/init.d/mysql restart
</span></span></code></pre></div><p><strong>STEP 3</strong>：設定 SlaveDB，指定 Master DB 登入資訊，並啟動 Replication</p>
<div class="highlight"><pre tabindex="0" style="color:#e6edf3;background-color:#0d1117;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-sql" data-lang="sql"><span style="display:flex;"><span><span style="color:#8b949e;font-style:italic">/* 這裡的帳號密碼就上面 Master 設定的那組 */</span><span style="color:#6e7681">
</span></span></span><span style="display:flex;"><span>mysql<span style="color:#ff7b72;font-weight:bold">&gt;</span><span style="color:#6e7681"> </span>CHANGE<span style="color:#6e7681"> </span>MASTER<span style="color:#6e7681"> </span><span style="color:#ff7b72">TO</span><span style="color:#6e7681"> </span>MASTER_HOST<span style="color:#ff7b72;font-weight:bold">=</span><span style="color:#a5d6ff">&#39;master_ip&#39;</span>,<span style="color:#6e7681">
</span></span></span><span style="display:flex;"><span><span style="color:#6e7681">              </span>MASTER_USER<span style="color:#ff7b72;font-weight:bold">=</span><span style="color:#a5d6ff">&#39;account&#39;</span>,<span style="color:#6e7681">
</span></span></span><span style="display:flex;"><span><span style="color:#6e7681">              </span>MASTER_PASSWORD<span style="color:#ff7b72;font-weight:bold">=</span><span style="color:#a5d6ff">&#39;password&#39;</span>;<span style="color:#6e7681">
</span></span></span></code></pre></div><p class="code-source">原始碼：<a href="https://gist.github.com/dean9703111/e09739d509230e0b270f7b374c8ba553" rel="noopener">setting_slave_info.sql</a>（GitHub Gist）</p>
<p>啟動 Slave Replication：</p>
<pre tabindex="0"><code>mysql&gt; START SLAVE;
</code></pre><p><strong>STEP 4</strong>：檢查 replication 狀態</p>
<pre tabindex="0"><code>SHOW SLAVE STATUS \G
</code></pre><p>如果下圖紅框皆顯示 Yes 就代表你成功嚕！</p>
<p><img src="https://deanlin.net/blog/202103/mysql-master-slave-replication/images/mysql-master-slave-replication-05.webp" width="582" height="268" alt="STEP 2：設定 Slave server 的 my.cnf（圖 5）" loading="lazy" decoding="async"></p>
<p>如果你看到下面這個畫面，可能是因為你的 Master MySQL 的設定有問題，最有可能是『使用者帳號、密碼錯誤』、『bind-address 沒有調整』</p>
<p><img src="https://deanlin.net/blog/202103/mysql-master-slave-replication/images/mysql-master-slave-replication-06.webp" width="582" height="268" alt="STEP 2：設定 Slave server 的 my.cnf（圖 6）" loading="lazy" decoding="async"></p>
<h2 id="三驗證-masterslave-db-是否同步">三、驗證 Master、Slave DB 是否同步<a class="h-anchor" href="#%e4%b8%89%e9%a9%97%e8%ad%89-masterslave-db-%e6%98%af%e5%90%a6%e5%90%8c%e6%ad%a5" aria-label="這個段落的連結"></a></h2>
<p>先在 Master 確認是不是真的有跟 Slave 串接成功</p>
<div class="highlight"><pre tabindex="0" style="color:#e6edf3;background-color:#0d1117;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-sql" data-lang="sql"><span style="display:flex;"><span><span style="color:#ff7b72">show</span><span style="color:#6e7681"> </span>slave<span style="color:#6e7681"> </span>hosts;<span style="color:#6e7681">
</span></span></span></code></pre></div><p><img src="https://deanlin.net/blog/202103/mysql-master-slave-replication/images/mysql-master-slave-replication-07.webp" width="1400" height="274" alt="三、驗證 Master、Slave DB 是否同步（圖 7）" loading="lazy" decoding="async"></p>
<p>確認連接成功後我們在 Master server 上面新增一個 DB</p>
<p><img src="https://deanlin.net/blog/202103/mysql-master-slave-replication/images/mysql-master-slave-replication-08.webp" width="342" height="479" alt="三、驗證 Master、Slave DB 是否同步（圖 8）" loading="lazy" decoding="async"></p>
<p>回到 Slave server 就會看到 DB 被同步過來嚕～</p>
<p><img src="https://deanlin.net/blog/202103/mysql-master-slave-replication/images/mysql-master-slave-replication-09.webp" width="342" height="217" alt="三、驗證 Master、Slave DB 是否同步（圖 9）" loading="lazy" decoding="async"></p>
<hr>
<p>這篇文章是針對 MySQL Master Slave Replication 做說明，但你依照上面的做法完成後還需要思考幾個問題：</p>
<ul>
<li>我們知道 Master server 是用來更新資料，Slave server 是用來檢索資料；但他們都是獨立的 ip，總不能每個 api 執行時都連不一樣的 ip 吧？</li>
<li>Slave 的資料是從 Master 上複製過來的，會複製就代表會有延遲，要如何保持資料的一致性呢？</li>
</ul>
<pre tabindex="0"><code>如果你想深入了解上面的問題如何解決可以參考我的文章：
👍 在 MySQL 5.7 解決主從複製的延遲問題
👍 Ubuntu 用 Atlas 實現 MySQL Proxy 讀寫分離 read/write splitting
</code></pre><hr>
<p>參考資源：<a href="https://dotblogs.com.tw/eric_obay_talk/2018/10/24/160017">MySQL Master Slave replication</a>、<a href="https://ithelp.ithome.com.tw/articles/10236724">打造MySQL Replication</a></p>
]]></content:encoded>
    </item>
  </channel>
</rss>
