1. 首先,需要在项目中添加 sharding-jdbc 的依赖,例如:
<dependency>
    <groupId>io.shardingsphere</groupId>
    <artifactId>sharding-jdbc-core</artifactId>
    <version>${sharding-jdbc.version}</version>
</dependency>
  1. 在项目中添加 sharding-jdbc 的配置文件,例如:
spring.shardingsphere.datasource.names=ds0, ds1

spring.shardingsphere.datasource.ds0.jdbcUrl=jdbc:mysql://localhost:3306/db
spring.shardingsphere.datasource.ds0.username=root
spring.shardingsphere.datasource.ds0.password=root

spring.shardingsphere.datasource.ds1.jdbcUrl=jdbc:mysql://localhost:3306/db
spring.shardingsphere.datasource.ds1.username=root
spring.shardingsphere.datasource.ds1.password=root

spring.shardingsphere.sharding.tables.user.actualDataNodes=ds$->{0..1}.user_${2019..2020}_$->{1..12}
spring.shardingsphere.sharding.tables.user.tableStrategy.inline.shardingColumn=create_time
spring.shardingsphere.sharding.tables.user.tableStrategy.inline.algorithmExpression=user_${DateTimeUtil.MONTH_FORMAT}.intValue()%24

spring.shardingsphere.sharding.defaultDatabaseStrategy.inline.shardingColumn=create_time
spring.shardingsphere.sharding.defaultDatabaseStrategy.inline.algorithmExpression=ds${user_${DateTimeUtil.MONTH_FORMAT}.intValue()%2}
  1. 在项目中编写 mapper 和 service 层的代码,例如:
@Mapper
public interface UserMapper {
    void addUser(User user);
}

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    
    @Override
    public void addUser(User user) {
        userMapper.addUser(user);
    }
}
  1. 在项目中定义一个工具类 DateTimeUtil,用于获取当前时间的月份,例如:
public class DateTimeUtil {
    public static final String MONTH_FORMAT = 'yyyy_MM';
    
    public static String getCurrentMonth() {
        return new SimpleDateFormat(MONTH_FORMAT).format(new Date());
    }
}
  1. 在 service 层的代码中,调用 DateTimeUtil.getCurrentMonth() 方法获取当前月份,然后调用 userMapper 的 addUser 方法,例如:
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    
    @Override
    public void addUser(User user) {
        user.setCreateTime(DateTimeUtil.getCurrentMonth());
        userMapper.addUser(user);
    }
}

通过以上步骤,就可以实现按月份分表的功能了。在每次新增用户时,根据当前时间的月份来确定数据应该存放在哪张表中。每张表的表名为 user_年份_月份,例如 user_2019_01 表示存放 2019 年 1 月份的用户数据。同时,数据源也会根据当前时间的月份来切换。在这个例子中,每个月会使用两个数据源,分别为 ds0 和 ds1。如果当前时间的月份为奇数,则会使用 ds1 数据源;如果当前时间的月份为偶数,则会使用 ds0 数据源。

Maven 项目中使用 Sharding-JDBC 按月份分表步骤

原文地址: https://www.cveoy.top/t/topic/nHN1 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录