Java基于ShardingSphere實現(xiàn)分庫分表的實例詳解
一、簡介
Apache ShardingSphere 是一套開源的分布式數(shù)據(jù)庫解決方案組成的生態(tài)圈,它由 JDBC、Proxy 和 Sidecar(規(guī)劃中)這 3 款既能夠獨立部署,又支持混合部署配合使用的產(chǎn)品組成。 它們均提供標(biāo)準(zhǔn)化的數(shù)據(jù)水平擴展、分布式事務(wù)和分布式治理等功能,可適用于如 Java 同構(gòu)、異構(gòu)語言、云原生等各種多樣化的應(yīng)用場景。
Apache ShardingSphere 旨在充分合理地在分布式的場景下利用關(guān)系型數(shù)據(jù)庫的計算和存儲能力,而并非實現(xiàn)一個全新的關(guān)系型數(shù)據(jù)庫。 關(guān)系型數(shù)據(jù)庫當(dāng)今依然占有巨大市場份額,是企業(yè)核心系統(tǒng)的基石,未來也難于撼動,我們更加注重在原有基礎(chǔ)上提供增量,而非顛覆。
Apache ShardingSphere 5.x 版本開始致力于可插拔架構(gòu),項目的功能組件能夠靈活的以可插拔的方式進(jìn)行擴展。 目前,數(shù)據(jù)分片、讀寫分離、數(shù)據(jù)加密、影子庫壓測等功能,以及 MySQL、PostgreSQL、SQLServer、Oracle 等 SQL 與協(xié)議的支持,均通過插件的方式織入項目。 開發(fā)者能夠像使用積木一樣定制屬于自己的獨特系統(tǒng)。Apache ShardingSphere 目前已提供數(shù)十個 SPI 作為系統(tǒng)的擴展點,仍在不斷增加中。
ShardingSphere 已于2020年4月16日成為 Apache 軟件基金會的頂級項目。
二、項目使用
1、引入依賴
<dependency> <groupId>org.apache.shardingsphere</groupId> <artifactId>sharding-jdbc-spring-boot-starter</artifactId> <version>4.0.0-RC2</version> </dependency>
2、數(shù)據(jù)庫
3、實體類
@Data public class User { private Integer id; private String name; private Integer age; }
4、mapper
這里用的Mybatis-plus 3.4版本。
@Mapper public interface UserMapper extends BaseMapper<User> { }
5、yml配置
spring: shardingsphere: datasource: #數(shù)據(jù)庫分庫名 names: ds0,ds1 ds0: #type為數(shù)據(jù)源,如果是Druid數(shù)據(jù)庫連接池,可以去改 type: com.zaxxer.hikari.HikariDataSource driver-class-name: com.mysql.cj.jdbc.Driver jdbc-url: jdbc:mysql://localhost:3306/test0?characterEncoding=utf-8&serverTimezone=UTC username: root password: root ds1: type: com.zaxxer.hikari.HikariDataSource driver-class-name: com.mysql.cj.jdbc.Driver jdbc-url: jdbc:mysql://localhost:3306/test1?characterEncoding=utf-8&serverTimezone=UTC username: root password: root # 分片規(guī)則 sharding: default-database-strategy: inline: algorithm-expression: ds$->{id%2} sharding-column: id tables: user: actual-data-nodes: ds${0..1}.user_${0..2} table-strategy: inline: algorithm-expression: user_${age%2} sharding-column: age # 在日志中SQL語句 props: sql: show: true
6、測試類
@SpringBootTest class DemoApplicationTests { @Resource private UserMapper userMapper; @Test void contextLoads() { User user = new User(); user.setId(1); user.setName("666"); user.setAge(16); userMapper.insert(user); } @Test void contextLoads2() { User user = new User(); user.setId(2); user.setName("666"); user.setAge(17); userMapper.insert(user); } }
7、數(shù)據(jù)
到此這篇關(guān)于ShardingSphere實現(xiàn)分庫分表的文章就介紹到這了,更多相關(guān)ShardingSphere分庫分表內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java使用common-fileupload實現(xiàn)文件上傳
這篇文章主要為大家詳細(xì)介紹了java使用common-fileupload實現(xiàn)文件上傳的相關(guān)資料,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-10-10@Scheduled fixedDelayString 加載properties配置方式
這篇文章主要介紹了@Scheduled fixedDelayString 加載properties配置方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-10-10mybatis中oracle實現(xiàn)分頁效果實例代碼
實現(xiàn)分頁的方式有很多,但常用的是通過SQL來顯示分頁。這篇文章主要介紹了mybatis中oracle實現(xiàn)分頁效果實例代碼,有興趣的可以了解一下。2017-04-04