1 新建数据库
创建ds_0数据库和ds_1数据库,在两个数据库新建表如下:
CREATE TABLE `t_order` (`order_id` bigint(20) NOT NULL,`user_id` bigint(20) NOT NULL,PRIMARY KEY (`order_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
2 新建maven项目
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.0.3.RELEASE</version><relativePath /> <!-- lookup parent from repository --></parent><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><java.version>1.8</java.version></properties><dependencies><!-- jpa --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>1.3.2</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><!-- 引入shardingjdbc依赖信息 --><dependency><groupId>io.shardingjdbc</groupId><artifactId>sharding-jdbc-core</artifactId><version>2.0.3</version></dependency><dependency><groupId>com.dangdang</groupId><artifactId>sharding-jdbc-self-id-generator</artifactId><version>1.4.2</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.0.12</version></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build>
3 application配置
###数据库访问连接
spring:jdbc:db0:password: 123456className: com.mysql.jdbc.Driverurl: jdbc:mysql://192.168.222.157:3306/%s?characterEncoding=utf-8username: rootjpa:database: mysqlshow-sql: truehibernate:## 自己建表ddl-auto: noneapplication:name: sharding-jdbc-first
4 配置分表算法
4.1 配置数据库连接
package com.example.demo.config;import com.alibaba.druid.pool.DruidDataSource;
import com.dangdang.ddframe.rdb.sharding.api.ShardingDataSourceFactory;
import com.dangdang.ddframe.rdb.sharding.api.rule.DataSourceRule;
import com.dangdang.ddframe.rdb.sharding.api.rule.ShardingRule;
import com.dangdang.ddframe.rdb.sharding.api.rule.TableRule;
import com.dangdang.ddframe.rdb.sharding.api.strategy.database.DatabaseShardingStrategy;
import com.dangdang.ddframe.rdb.sharding.id.generator.IdGenerator;
import com.dangdang.ddframe.rdb.sharding.id.generator.self.CommonSelfIdGenerator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;import javax.sql.DataSource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;// 数据源相关配置信息
@Configuration
public class DataSourceConfig {@Value("${spring.jdbc.db0.className}")private String className;@Value("${spring.jdbc.db0.url}")private String url;@Value("${spring.jdbc.db0.username}")private String username;@Value("${spring.jdbc.db0.password}")private String password;@Beanpublic IdGenerator getIdGenerator() {return new CommonSelfIdGenerator();}@Beanpublic DataSource getDataSource() {return buildDataSource();}private DataSource buildDataSource() {// 1.设置分库映射Map<String, DataSource> dataSourceMap = new HashMap<>(2);dataSourceMap.put("ds_0", createDataSource("ds_0"));dataSourceMap.put("ds_1", createDataSource("ds_1"));// 设置默认db为ds_0,也就是为那些没有配置分库分表策略的指定的默认库// 如果只有一个库,也就是不需要分库的话,map里只放一个映射就行了,只有一个库时不需要指定默认库,// 但2个及以上时必须指定默认库,否则那些没有配置策略的表将无法操作数据DataSourceRule rule = new DataSourceRule(dataSourceMap, "ds_0");// 2.设置分表映射,将t_order_0和t_order_1两个实际的表映射到t_order逻辑表TableRule orderTableRule = TableRule.builder("t_order").dataSourceRule(rule).build();// 3.具体的分库分表策略ShardingRule shardingRule = ShardingRule.builder().dataSourceRule(rule).tableRules(Arrays.asList(orderTableRule)).databaseShardingStrategy(new DatabaseShardingStrategy("user_id", new DatabaseShardingAlgorithm())).build();// 创建数据源DataSource dataSource = ShardingDataSourceFactory.createDataSource(shardingRule);return dataSource;}private DataSource createDataSource(String dataSourceName) {// 使用druid连接数据库DruidDataSource druidDataSource = new DruidDataSource();druidDataSource.setDriverClassName(className);druidDataSource.setUrl(String.format(url, dataSourceName));druidDataSource.setUsername(username);druidDataSource.setPassword(password);return druidDataSource;}
}
4.2 配置分表策略
分库算法类需要实现SingleKeyDatabaseShardingAlgorithm<T>接口
package com.example.demo.config;import com.dangdang.ddframe.rdb.sharding.api.ShardingValue;
import com.dangdang.ddframe.rdb.sharding.api.strategy.database.SingleKeyDatabaseShardingAlgorithm;import java.util.Collection;public class DatabaseShardingAlgorithm implements SingleKeyDatabaseShardingAlgorithm<Long> {@Overridepublic String doEqualSharding(Collection<String> databases, ShardingValue<Long> shardingValue) {for (String tableName : databases) {System.out.println("tableName:" + tableName + ",----" + shardingValue.getValue());if (tableName.endsWith(shardingValue.getValue() % 2 + "")) {return tableName;}}throw new IllegalArgumentException();}@Overridepublic Collection<String> doInSharding(Collection<String> availableTargetNames, ShardingValue<Long> shardingValue) {return null;}@Overridepublic Collection<String> doBetweenSharding(Collection<String> availableTargetNames,ShardingValue<Long> shardingValue) {return null;}}
5 新建实体类
package com.example.demo.entity;import lombok.Data;import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;@Data
@Entity
@Table(name = "t_order")
public class OrderEntity {@Idprivate Long orderId;private Long userId;}
6 OrderRepository
package com.example.demo.repository;import com.example.demo.entity.OrderEntity;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;import java.util.List;public interface OrderRepository extends CrudRepository<OrderEntity, Long> {@Query(value = "SELECT order_id ,user_id FROM t_order where order_id in (?1);", nativeQuery = true)public List<OrderEntity> findExpiredOrderState(List<String> bpIds);
}
7 OrderController
package com.example.demo.controller;import com.example.demo.entity.OrderEntity;
import com.example.demo.repository.OrderRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import java.util.ArrayList;
import java.util.List;@RestController
public class OrderController {@Autowiredprivate OrderRepository orderRepository;// 查询所有的订单信息@RequestMapping("/getOrderAll")public List<OrderEntity> getOrderAll() {return (List<OrderEntity>) orderRepository.findAll();}// 使用in条件查询@RequestMapping("/inOrder")public List<OrderEntity> inOrder() {List<String> ids = new ArrayList<>();ids.add("2");ids.add("3");ids.add("4");ids.add("5");return orderRepository.findExpiredOrderState(ids);}// 增加@RequestMapping("/inserOrder")public String inserOrder(OrderEntity orderEntity) {for (int i = 0; i < 10; i++) {OrderEntity order = new OrderEntity();order.setOrderId((long) i);order.setUserId((long) i);orderRepository.save(order);}return "success";}}
8 新建启动类
package com.example.demo;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;@SpringBootApplication
@EnableJpaRepositories(basePackages = "com.example.demo.repository")
public class AppSharding {public static void main(String[] args) {SpringApplication.run(AppSharding.class, args);}
}
9 启动项目
访问http://localhost:8080/inserOrder
分表测试成功