mysql主從復制配置見: http://www.aygfsteel.com/howard-he/
項目中使用mysql 主從復制,但是用程序實現的讀寫分離,代碼片段如下:
1
public DataSource getDataSource(MethodType methodType)
{
2
if (methodType == MethodType.WRITE)
{
3
return getDataSource(MasterDataSources);
4
} else
{
5
return getDataSource(SlaveDataSources);
6
}
7
}



2



3

4



5

6

7

獲取數據源,首先你要確定MethodType 類型,一個是讀,一個是寫
1
public enum MethodType
{
2
READ, WRITE
3
}



2

3

讀是獲取從庫數據源,寫是獲取主庫數據源。
這樣,就需要在jdbc配置配置兩個數據源(一主一從)
還有另一種實現方式,不用程序來控制。mysql 驅動包提供相應的實現 com.mysql.jdbc.ReplicationDriver.
我寫了一個簡單的例子:
1
package com.howard.loadbalance;
2
3
import java.sql.Connection;
4
import java.sql.ResultSet;
5
import java.sql.SQLException;
6
import java.sql.Statement;
7
import java.util.Properties;
8
import java.util.concurrent.ExecutorService;
9
import java.util.concurrent.Executors;
10
11
import org.slf4j.Logger;
12
import org.slf4j.LoggerFactory;
13
14
import com.mysql.jdbc.ReplicationDriver;
15
16
public class MysqlTest
{
17
18
public static class QueryRunnable implements Runnable
{
19
20
protected final static Logger logger = LoggerFactory
21
.getLogger(QueryRunnable.class);
22
23
@Override
24
public void run()
{
25
logger.info("user size: " + this.query());
26
}
27
28
public int query()
{
29
int count = 0;
30
try
{
31
ReplicationDriver driver = new ReplicationDriver();
32
Properties props = new Properties();
33
props.put("roundRobinLoadBalance", "true");
34
props.put("autoReconnect", "true");
35
props.put("user", "core");
36
props.put("password", "core");
37
Connection conn = null;
38
Statement stat = null;
39
ResultSet res = null;
40
try
{
41
conn = driver
42
.connect(
43
//注意url串中間不要有空格,因為mysql源碼對多個地址split時沒有trim.
44
"jdbc:mysql:replication://127.0.0.1:3309,127.0.0.1:3306/core",
45
props);
46
//讀寫分離標記
47
//當設置true時,只會在從庫查詢數據
48
//當設置false時,會在主庫做更新刪除操作
49
// conn.setReadOnly(true);
50
stat = conn.createStatement();
51
res = stat.executeQuery("select count(1) from c_user");
52
while (res.next())
53
count = res.getInt(1);
54
} finally
{
55
if (res != null)
56
res.close();
57
if (stat != null)
58
stat.close();
59
if (conn != null)
60
conn.close();
61
}
62
} catch (SQLException e)
{
63
e.printStackTrace();
64
}
65
return count;
66
}
67
}
68
69
public static void main(String[] args)
{
70
// 創建線程池測試負載軍衡
71
ExecutorService service = Executors.newCachedThreadPool();
72
for (int i = 0; i < 10; i++)
{
73
service.execute(new QueryRunnable());
74
}
75
service.shutdown();
76
}
77
78
}
79

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16



17

18



19

20

21

22

23

24



25

26

27

28



29

30



31

32

33

34

35

36

37

38

39

40



41

42

43

44

45

46

47

48

49

50

51

52

53

54



55

56

57

58

59

60

61

62



63

64

65

66

67

68

69



70

71

72



73

74

75

76

77

78

79
