監(jiān)控SQL Server數(shù)據(jù)庫(kù)異常鏡像狀態(tài)發(fā)告警郵件
普陀網(wǎng)站建設(shè)公司成都創(chuàng)新互聯(lián),普陀網(wǎng)站設(shè)計(jì)制作,有大型網(wǎng)站制作公司豐富經(jīng)驗(yàn)。已為普陀上千提供企業(yè)網(wǎng)站建設(shè)服務(wù)。企業(yè)網(wǎng)站搭建\外貿(mào)網(wǎng)站制作要多少錢,請(qǐng)找那個(gè)售后服務(wù)好的普陀做網(wǎng)站的公司定做!
在部署了數(shù)據(jù)庫(kù)鏡像之后,我們需要監(jiān)控參與鏡像的主數(shù)據(jù)庫(kù)和鏡像數(shù)據(jù)庫(kù)的狀態(tài),如果狀態(tài)異常,發(fā)送告警郵件。那么這個(gè)腳本需要在主和鏡像服務(wù)器上都運(yùn)行。
目錄視圖sys.database_mirroring對(duì)SQL Server實(shí)例上的每個(gè)數(shù)據(jù)庫(kù)都包含一行(包括系統(tǒng)數(shù)據(jù)庫(kù)和未配置鏡像的數(shù)據(jù)庫(kù)),當(dāng)然也包含所有鏡像數(shù)據(jù)庫(kù)的狀態(tài)信息。我們可以查詢?cè)撃夸浺晥D,對(duì)于每個(gè)異常狀態(tài)的鏡像數(shù)據(jù)庫(kù)觸發(fā)告警郵件。筆者的環(huán)境配置的是異步鏡像,依賴于手動(dòng)故障轉(zhuǎn)移。
前提條件:
1. 配置好數(shù)據(jù)庫(kù)郵件,有正確的Profile。
2. 有權(quán)限發(fā)送郵件的有效Login,需要是msdb數(shù)據(jù)庫(kù)中DatabaseMailUserRole角色成員。
3. 一對(duì)用于監(jiān)控的鏡像數(shù)據(jù)庫(kù)。
DECLARE @state VARCHAR(30) DECLARE @DbMirrored INT DECLARE @DbId INT DECLARE @String VARCHAR(100) DECLARE @databases TABLE (DBid INT, mirroring_state_desc VARCHAR(30)) -- get status for mirrored databases INSERT @databases SELECT database_id, mirroring_state_desc FROM sys.database_mirroring WHERE mirroring_role_desc IN ('PRINCIPAL','MIRROR') AND mirroring_state_desc NOT IN ('SYNCHRONIZED','SYNCHRONIZING') -- iterate through mirrored databases and send email alert WHILE EXISTS (SELECT TOP 1 DBid FROM @databases WHERE mirroring_state_desc IS NOT NULL) BEGIN SELECT TOP 1 @DbId = DBid, @State = mirroring_state_desc FROM @databases SET @string = 'Host: '+@@servername+'.'+CAST(DB_NAME(@DbId) AS VARCHAR)+ ' - DB Mirroring is '+@state +' - notify DBA' EXEC msdb.dbo.sp_send_dbmail 'valid_mail_profile', 'DBA@xxx.com', @body = @string, @subject = @string DELETE FROM @databases WHERE DBid = @DbId END --also alert if there is no mirroring just in case there should be mirroring :) SELECT @DbMirrored = COUNT(*) FROM sys.database_mirroring WHERE mirroring_state IS NOT NULL IF @DbMirrored = 0 BEGIN SET @string = 'Host: '+@@servername+' - No databases are mirrored on this server - notify DBA' EXEC msdb.dbo.sp_send_dbmail 'valid_mail_profile', 'DBA@xxx.com', @body = @string, @subject = @string END
依賴于手動(dòng)故障轉(zhuǎn)移。將以上腳本放到主服務(wù)器和鏡像服務(wù)器上的作業(yè)里,每5分鐘執(zhí)行一次。
收到郵件效果如下: