Cobar 是阿里巴巴早期開源的數據庫中間件,定位於透明化分庫分表:應用通過 MySQL 協議連接 Cobar,Cobar 根據分片規則將 SQL 路由至後端多個 MySQL 實例。本文記錄技術驗證全過程,含架構原理、部署配置、JDBC/iBatis 接入、查詢限制、擴容痛點及約束總結。
| 維度 | 說明 |
|---|---|
| 角色 | Client ↔ Cobar Proxy ↔ MySQL Shards |
| 透明性 | 應用無感知物理分片,標準 JDBC 訪問 |
| 核心能力 | 讀寫分離、負載均衡、高可用、SQL 過濾、路由、結果合併 |
| 優點 | 配置簡單、擴展靈活(Proxy 橫向擴展)、客戶端零改造 |
| 缺點 | 跨分片查詢效率低/不支援、Join/子查詢/跨分片分頁受限、擴容需人工數據遷移 |
cobar_1 ~ cobar_128),端口 3306,root/passwordcobar,用戶 root/12345q_reportkeywordsum,分片鍵 custid (INT)String url = "jdbc:mysql://10.20.130.119:8066/cobar"; String driver = "com.mysql.jdbc.Driver"; // 5.1.6 版本 Connection con = DriverManager.getConnection(url, "root", "12345"); // 正常執行 Statement / PreparedStatement
<bean id="sqlMapClientTemplate" class="com.alibaba.cobar.client.CobarSqlMapClientTemplate">
<property name="sqlMapClient" ref="sqlMapClient"/>
</bean>
<bean id="transactionManager" class="com.alibaba.cobar.client.transaction.MultipleDataSourcesTransactionManager">
<!-- 替換標準 DataSourceTransactionManager -->
</bean>
WHERE custid = 123(只能用 =,不可範圍/子查詢)VALUES (..., 123, ...) 對應位置必須為具體值select count(*) from q_reportkeywordsum; -- 返回 128 行結果,極慢,生產嚴禁
custid < 10 會報錯或結果錯誤F(x):單元或多元,但自變量必須來自同一張邏輯表的分片字段場景:初始 64 分片,單表 20GB 觸頂,需擴至 128/256 分片。
現狀:Cobar 無內建平滑擴容方案,只能:
rule.xml 重載建議:初始規劃預留足夠分片數(如 1024),或遷移至支援 Online DDL/Resharding 的中間件(ShardingSphere、MyCat、TDDL)。
// Redis 原子遞增生成全局唯一 ID
long nextId = redisTemplate.opsForValue().increment("global_id_seq");
// 插入時顯式指定 ID,避免分片間主鍵衝突
INSERT INTO q_reportkeywordsum (id, custid, ...) VALUES (?, ?, ...);