Springboot使用sharding進行分庫分表
pom.xml檔案加入sharing引用和druid引用
<dependency> <groupId>com.dangdang</groupId> <artifactId>sharding-jdbc-core</artifactId> <version>1.5.4</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.12</version> </dependency> |
application-data.properties中配置資料庫資訊
spring.jpa.show-sql=true other.datasource.driver-class-name = com.mysql.jdbc.Driver TradeStationYear.datasource.driver-class-name = com.mysql.jdbc.Driver |
在application.properties中加data的配置
spring.profiles.active=data |
建domain
import java.io.Serializable; import javax.persistence.Column; import io.swagger.annotations.ApiModelProperty; @Entity /** @Id @Column(name = "card_id", length = 20) @Column(name = "trade_address", length = 10) @Column(name = "trade_date") public TradeStationYear() { public String getTradeSN() { public void setTradeSN(String tradeSN) { public String getCardId() { public void setCardId(String cardId) { public String getStationAddress() { public void setStationAddress(String stationAddress) { public Date getTradeDate() { public void setTradeDate(Date tradeDate) { } |
repository類
public interface DataEntryRepositoryStationYear extends JpaRepository<TradeStationYear, Long> { Page<TradeStationYear> findAll(Specification<TradeStationYear> specification, Pageable pageable); } |
分庫分表的配置
@Configuration // 資料庫配置 @Autowired @Bean(TSSUtil.TRANSACTION_MANAGER_1) @Bean(TSSUtil.ENTITY_MANAGER_FACTORY_1) @Bean(TSSUtil.DATA_SOURCE_1) // 設定分庫對映 //如果是兩個資料庫 /** dataSourceMap.put("ds_0", createDataSource()); */ //設定預設資料庫 // 設定分表對映 /* // 設定分表對映 */ // 設定分表策略,按什麼規則來分 //按這兩個欄位來分TSSUtil.COLUMN_OF_TABLE_SHARDING_1_1, TSSUtil.COLUMN_OF_TABLE_SHARDING_1_2 DataSource dataSource = null; return dataSource; private DataSource createDataSource() { |
兩個條件的具體策略演算法
import java.util.Calendar; import com.dangdang.ddframe.rdb.sharding.api.ShardingValue; public final class StationAndYearTableShardingAlgorithm implements MultipleKeysTableShardingAlgorithm { private String column_1 = "tradeaddress";// 欄位1名,預設為tradeaddress,即交易地點 /** @Override Collection<String> result_1 = null; private Collection<String> doSharding(final ShardingValue<?> shardingValue){ private Collection<String> doEqualSharding4Date(Date value) { @SuppressWarnings("unchecked") private Collection<String> doInSharding4Date(Collection<Date> values) { @SuppressWarnings("unchecked") private Collection<String> doBetweenSharding4Date(Range<Date> range) { |
單個條件的具體分表策略
import java.util.Collection; import com.dangdang.ddframe.rdb.sharding.api.ShardingValue; public final class StationTableShardingAlgorithm implements SingleKeyTableShardingAlgorithm<String> { private String prefix = ""; @Override @Override @Override |
分表符串工具類
public static final String DATA_SOURCE_PREFIX = "dataSource"; // ***********************************第一個資料來源********************************************************* public static final String LABEL_1 = "TradeStationYear";// 標籤 } |
分表要自己建立表