前置條件html
使用sqlserver的發佈訂閱功能實現讀寫分離,並建立多個讀庫。redis
本文的負載均衡是針對多個讀庫而言的。sql
測試環境數據庫
vmware 10 64位windows
windows server 2008 R2centos
sql server 2008服務器
centOS 6.6負載均衡
haproxy 1.5tcp
虛擬機配置sqlserver
(1)虛擬機1:安裝centos, 並安裝HAProxy。ip爲:172.16.1.1。做爲負載均衡器。
(2)虛擬機2:安裝windows server 2008 R2, 並安裝sql server 2008。ip爲:172.16.1.2,做爲數據庫服務器1。
(3)虛擬機3:克隆虛擬機2。ip爲:172.16.1.6。做爲數據庫服務器2。
以下圖:
haproxy配置
這裏最重要的是對haproxy進行配置,配置文件以下:
global maxconn 5120 chroot /usr/local/haproxy uid 99 gid 99 daemon quiet nbproc 2 pidfile /usr/local/haproxy/haproxy.pid defaults log global mode http option httplog option dontlognull log 127.0.0.1 local3 retries 3 option redispatch maxconn 2000 contimeout 50000 clitimeout 50000 srvtimeout 50000 listen mssql :1433 mode tcp balance roundrobin server mssql1 172.16.1.2:1433 check weight 1 check server mssql2 172.16.1.6:1433 check weight 1 check listen stats :8888 mode http transparent stats uri / haproxy-stats stats realm Haproxy \ statistic
測試
(1) 建立一個測試表:
CREATE TABLE [dbo].[table1]( [f1] [nchar](10) NULL ) ON [PRIMARY]
(2)爲了看到負載均衡的結果,請將兩個讀庫中table1表的數據設置爲不同
(3)鏈接至172.16.1.1(負載均衡器),使用如下查詢語句進行查詢。
SELECT TOP 1000 [f1] FROM [test1].[dbo].[table1]
須要在每次查詢前先斷開鏈接,而後再創建與sql server的鏈接,以下圖所示:
特別說明:
(1)如果不從新創建鏈接的話,則每次獲得的結果是同樣的,由於sqlserver的客戶端採用了數據庫鏈接池技術,在沒有主動地關閉的狀況下,TCP鏈接會一直被保持着。
(2)斷開鏈接以後,再從新鏈接一次的話,則獲得的結果是不同的。
本文的介紹的方法僅在測試環境中經過,還沒有在正式環境中使用。
haproxy的安裝請見:
http://www.cnblogs.com/dehai/p/4885016.html