Sharding-JDBC(四)集成dynamic-datasource
短信预约 -IT技能 免费直播动态提醒
目录
实现原理:
- 通过
DataSourceConfig.java
将ShardingJDBC数据源配置为动态数据源之一。 - 通过
@DS(DataSourceConfig.SHARDING_DATA_SOURCE_NAME)
使用 ShardingJDBC 的数据源进行分表操作。
1.Maven依赖
org.apache.shardingsphere sharding-jdbc-spring-boot-starter ${shardingsphere.version} com.baomidou dynamic-datasource-spring-boot-starter 3.3.2
2.yml配置
server: port: 8081spring: # 多数据源配置 datasource: dynamic: primary: mydb1 datasource: mydb1: url: jdbc:mysql://localhost:3306/mydb1?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver # sharding-jdbc配置 shardingsphere: # 打印sql props: sql: show: true datasource: names: mydb2 mydb2: type: com.alibaba.druid.pool.DruidDataSource url: jdbc:mysql://localhost:3306/mydb2?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai driver-class-name: com.mysql.cj.jdbc.Driver username: root password: root # 数据源其他配置 initialSize: 5 minIdle: 5 maxActive: 20 maxWait: 60000 timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 300000 validationQuery: SELECT 1 FROM DUAL testWhileIdle: true testOnBorrow: false testOnReturn: false poolPreparedStatements: true # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙 #filters: stat,wall,log4j maxPoolPreparedStatementPerConnectionSize: 20 useGlobalDataSourceStat: true connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500 sharding: # 表策略配置 tables: # t_user 是逻辑表 t_user: # 分表节点 可以理解为分表后的那些表 比如 t_user_1 ,t_user_2 actualDataNodes: mydb2.t_user_$->{1..2} tableStrategy: inline: # 根据哪列分表 shardingColumn: age # 分表算法 例如:age为奇数 -> t_user_2; age为偶数 -> t_user_1 algorithmExpression: t_user_$->{age % 2 + 1}# keyGenerator:# type: SNOWFLAKE# # 对id列采用 sharding-jdbc的全局id生成策略# column: id# mybatis-plusmybatis-plus: mapper-locations: classpath*:/mapper@Configuration@AutoConfigureBefore({DynamicDataSourceAutoConfiguration.class, SpringBootConfiguration.class})public class DataSourceConfig { public static final String SHARDING_DATA_SOURCE_NAME = "sharding-data-source"; @Autowired private DynamicDataSourceProperties properties; @Lazy @Resource(name = "shardingDataSource") private AbstractDataSourceAdapter shardingDataSource; @Bean public DynamicDataSourceProvider dynamicDataSourceProvider() { Map datasourceMap = properties.getDatasource(); return new AbstractDataSourceProvider() { @Override public Map loadDataSources() { Map dataSourceMap = createDataSourceMap(datasourceMap); // 将 shardingjdbc 管理的数据源也交给动态数据源管理 dataSourceMap.put(SHARDING_DATA_SOURCE_NAME, shardingDataSource); return dataSourceMap; } }; } @Primary @Bean public DataSource dataSource(DynamicDataSourceProvider dynamicDataSourceProvider) { DynamicRoutingDataSource dataSource = new DynamicRoutingDataSource(); dataSource.setPrimary(properties.getPrimary()); dataSource.setStrict(properties.getStrict()); dataSource.setStrategy(properties.getStrategy()); dataSource.setProvider(dynamicDataSourceProvider); dataSource.setP6spy(properties.getP6spy()); dataSource.setSeata(properties.getSeata()); return dataSource; }}
4.TUserService.java
import com.demo.module.entity.TUser;import com.baomidou.mybatisplus.extension.service.IService;import java.util.List;public interface TUserService extends IService { List listFromDB1();}
5.TUserServiceImpl.java
import com.baomidou.dynamic.datasource.annotation.DS;import com.demo.module.config.DataSourceConfig;import com.demo.module.entity.TUser;import com.demo.module.mapper.TUserMapper;import com.demo.module.service.TUserService;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;import org.springframework.stereotype.Service;import java.util.List;@Service@DS(DataSourceConfig.SHARDING_DATA_SOURCE_NAME)public class TUserServiceImpl extends ServiceImpl implements TUserService { @DS("mydb1") @Override public List listFromDB1() { // 查询 全部用户(mydb1数据库) return this.list(); }}
6.测试代码
@Testvoid saveTest() { List users = new ArrayList<>(3); users.add(new TUser("ACGkaka_1", "123456", 10)); users.add(new TUser("ACGkaka_2", "123456", 11)); users.add(new TUser("ACGkaka_3", "123456", 12)); userService.saveBatch(users);}@Testvoid listTest() { List users1 = userService.listFromDB1(); System.out.println(">>>>>>>>>> 【Result1】<<<<<<<<<< "); users1.forEach(System.out::println); List users2 = userService.list(); System.out.println(">>>>>>>>>> 【Result2】<<<<<<<<<< "); users2.forEach(System.out::println);}
7.测试结果
查询没有数据插入的mydb1,没有查到数据:
查询插入了 3 条数据的mydb2,查询到了 3 条:
测试成功,数据根据动态数据源配置实现了对 mydb1 和 mydb2 两个数据库的操作。
8.源码地址
地址: https://gitee.com/acgkaka/SpringBootExamples/tree/master/springboot-sharding-jdbc-dynamic
整理完毕,完结撒花~
参考地址:
SpringBoot(50) 整合sharding-jdbc和多数据源,https://blog.csdn.net/qq_38225558/article/details/121107962
来源地址:https://blog.csdn.net/qq_33204709/article/details/128406525
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341