[SQL SERVER][HA]資料庫鏡像#實作同步資料庫鏡像

[SQL SERVER][HA]資料庫鏡像#實作同步資料庫鏡像

這次我將實作沒有Domain環境的同步資料庫鏡像,整個過程將使用TSQL來示範。

 

Primary Server:RICO-WIN2K8VM Standby Server:RICO-NBVM

 

零、事前確認作業

a.相同的 SQL Server 版本。

b. 資料庫復原模式需為完整模式。

c. 正確無錯誤的完整主體資料庫和交易記錄檔的備份檔案。

d.確認兩台Server間網路通訊是正常的(如port:1433)。

 

一、建立主體資料庫及備份主體資料庫

--primary
USE [master]
GO
CREATE DATABASE [DBDEMO] ON  PRIMARY 
( NAME = N'DBDEMO', FILENAME = N'C:\sqldata\DBDEMO.mdf',
    SIZE = 10240KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
 LOG ON 
( NAME = N'DBDEMO_log', FILENAME = N'C:\sqldata\DBDEMO_log.LDF', 
    SIZE = 2048KB , MAXSIZE = 1GB , FILEGROWTH = 10%)
GO

 

 

 

 

--primary
USE [master]
go
Backup database DBDEMO to disk =N'C:\Backups\DBDEMO.bak' with init
go
Backup log DBDEMO to disk =N'C:\Backups\DBDEMO.trn' with init
go

 

二、使用主體資料庫備份檔,建立鏡像資料庫。(將完整備份檔(含交易紀錄檔)傳送給Standby Server)

將備份還原至鏡像資料庫時,必須一律使用 WITH NORECOVERY 來進行每一項還原作業。

--standby
use [master]
go
restore database DBDEMO from disk =N'C:\backups\DBDEMO.bak' with norecovery
go
restore log DBDEMO  from disk ='C:\backups\DBDEMO.trn' with norecovery
go

 

image

image 

鏡像資料庫狀態:正在還原。

 

三、建立通訊端點

--primary 
--建立端點
CREATE ENDPOINT [Mirroring] 
AS TCP (LISTENER_PORT = 5023)
FOR DATA_MIRRORING (ROLE = PARTNER, ENCRYPTION=DISABLED)
GO
--啟動端點
ALTER ENDPOINT [Mirroring]
STATE = STARTED 
AS TCP (LISTENER_PORT = 5023)
FOR database_mirroring (ROLE = PARTNER);
GO
--查看端點
SELECT type_desc, port FROM sys.tcp_endpoints;
SELECT name,role,state_desc FROM sys.database_mirroring_endpoints;
GO

 

 

 

image

 Primary確認無誤後,請也在Standby建立相同端點(名稱和PORT須相同)。

 

image

確定端點狀態:STARTED。

 

四、設定鏡像夥伴

--standby
ALTER DATABASE [DBDEMO]
SET PARTNER ='TCP://RICO-WIN2K8VM:5023'

 

image

--primary
ALTER DATABASE [DBDEMO]
SET PARTNER ='TCP://RICO-NBVM:5023'

 

image

 

--primary

clip_image002

--standby

clip_image004

到這裡就完成了整個同步資料庫鏡像過程。

 

現在來測試看看資料是否真能同步。

 

Primary 建立Table並Insert New Data

use DBDEMO
go
create table test1
(col1 int,
col2 int,
col3 varchar(30))
go
insert into test1 values
                  (1,11,'ricoisme'),
                  (2,22,'ricoisme'),
                  (3,33,'ricoisme')
go                  

 

image

 

查看鏡像資料庫

--Standby

傳回在前兩個小時期間記錄的資料列,而不會更新資料庫的狀態

USE msdb;
 
EXEC sp_dbmmonitorresults DBDEMO, 2, 0;

 

image

image

確認同步完後,再來就是執行角色轉換,驗證資料是否可用。

 

角色轉換

--primary
 
use master
 
ALTER DATABASE DBDEMO SET PARTNER FAILOVER

 

image

image

 

--Standby

image

image

剛剛在主體資料庫所建立的資料,果然真的Commit了。

 

現在我再來新增幾筆資料,然後再來測試看看,角色再度轉換後的結果。

image

新增3筆資料。

 

--standby
use master
ALTER DATABASE DBDEMO SET PARTNER FAILOVER

 

image

image

資料果然又正常Commit了。

 

參考

同步資料庫鏡像 (高安全性模式)

設定資料庫鏡像