springboot+shardingjdbc+mybatis+oracle与mysql坑

2023-11-25 16:30

本文主要是介绍springboot+shardingjdbc+mybatis+oracle与mysql坑,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

随着公司的业务增长,从一个工厂单表对应的数据量到达为2个亿数据量,现在引入4个工厂数据估计数量到达10个亿数据量,考虑后期数据量导致数据表崩溃。想引入现在比较流行的分库分表shardingjdbc技术,由于只分表不库的功能,按照厂site进行分成四张表。

步骤如下;

第一步 引入包

<!--Oracle驱动 11.2.0.3  --><dependency><groupId>com.oracle</groupId><artifactId>ojdbc6</artifactId><version>11.1.0.6.0</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.23</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.1.3</version></dependency><!-- sharding-sphere --><dependency><groupId>org.apache.shardingsphere</groupId><artifactId>sharding-jdbc-spring-boot-starter</artifactId><version>4.1.1</version></dependency>

第二步 配置yml文件

spring:#配置Sharding-jdbcshardingsphere:datasource:names: ds1,ds2ds1:type: com.alibaba.druid.pool.DruidDataSourcedriver-class-name: oracle.jdbc.driver.OracleDriverurl: jdbc:oracle:thin:@172.127.17.249:1521:d1rptdb1username: rootpassword: 123456ds2:type: com.alibaba.druid.pool.DruidDataSourcedriver-class-name: oracle.jdbc.driver.OracleDriverurl: jdbc:oracle:thin:@172.127.17.249:1521:d1rptdb1username: rootpassword: 123456sharding:props:sql.show: truetables:T_ORDER:  #t_user表actual-data-nodes: ds${1..2}.T_ORDER${1..2}    #数据节点,均匀分布table-strategy:  #分表策略inline: #行表达式sharding-column: ORDER_IDalgorithm-expression: T_ORDER$->{ORDER_ID % 2+1}  #按模运算分配# 默认数据源,未分片的表默认执行库default-database-strategy:inline:sharding-column:  ORDER_IDalgorithm-expression: ds$->{ORDER_ID % 2+1}props:sql:show: true

注意点:由于目前业务需求只考虑分表,不考虑分库。我第一反应的只要一个数据源就可以没有必要搞两个或者两个以数据源。但是问题来了:如果只在yml配置一个数据源启动报:

13:43:37.213 [main] INFO ShardingSphere-metadata - Loading 1 logic tables' meta data.
13:43:48.733 [main] INFO ShardingSphere-metadata - Loading 527 tables' meta data.
java.sql.SQLSyntaxErrorException: ORA-00942: 表或视图不存在

而且为什么出现Loading 527 tables' meta data  527表。 反反复复看官文文档:https://shardingsphere.apache.org/document/4.1.1/cn/manual/sharding-jdbc/configuration/config-spring-boot/配置也没有错,由于自己在本地电脑上重新安装mysql数据库,同样的代码

package com.shardingjdb.shardingjdbc.Controller;import com.alibaba.druid.pool.DruidDataSource;
import org.apache.shardingsphere.api.config.sharding.ShardingRuleConfiguration;
import org.apache.shardingsphere.api.config.sharding.TableRuleConfiguration;
import org.apache.shardingsphere.api.config.sharding.strategy.InlineShardingStrategyConfiguration;
import org.apache.shardingsphere.shardingjdbc.api.ShardingDataSourceFactory;import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Random;public class Test {public static void main(String[] args) {Map<String, DataSource> dataSourceMap = new HashMap<>();// 配置第一个数据源DruidDataSource druidDataSource = new DruidDataSource();druidDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");//druidDataSource.setUrl("jdbc:mysql://10.108.243.87:3306/order");druidDataSource.setUrl("jdbc:mysql://127.0.0.1:3306/order?useUnicode=yes&characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC");druidDataSource.setUsername("root");druidDataSource.setPassword("123456");dataSourceMap.put("ds0",druidDataSource);//在EDU_LDA库中创建了三张表:T_ORDER,T_ORDER1,T_ORDER2// 配置orders表规则  ds0.t_user${0..1}orders_${1..2}TableRuleConfiguration orderTableRuleConfig = new TableRuleConfiguration("t_order","ds0.t_order${1..2}");// 配置分库+分表策略//orderTableRuleConfig.setDatabaseShardingStrategyConfig(new InlineShardingStrategyConfiguration("order_id","ds${customer_id%2+1}"));orderTableRuleConfig.setTableShardingStrategyConfig(new InlineShardingStrategyConfiguration("ORDER_ID","t_order$->{ORDER_ID % 2+1}"));// 配置分片规则ShardingRuleConfiguration shardingRuleConfiguration = new ShardingRuleConfiguration();shardingRuleConfiguration.getTableRuleConfigs().add(orderTableRuleConfig);// 获取数据源对象try {DataSource dataSource = ShardingDataSourceFactory.createDataSource(dataSourceMap,shardingRuleConfiguration,new Properties());Connection connection = dataSource.getConnection();PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO t_order(ORDER_ID, USER_ID, STATUS) values(?,?,?)");for (int i = 420; i <430 ; i++) {preparedStatement.setInt(1,i);preparedStatement.setInt(2,i);preparedStatement.setInt(3,i);preparedStatement.execute();}} catch (Exception exception) {exception.printStackTrace();}}
}

mysql是进行起到分表的作用,我就纳闷啊 为什么mysql一个数据源可以 而oralce一个数据源不可以总是报表或者视图不存在,

启动项目报错如下:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'artificialNodeHistoryController': Unsatisfied dependency expressed through field 'service'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'artificialNodeHistoryServiceImpl': Unsatisfied dependency expressed through field 'olFirstruneqflagMapper'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'olFirstruneqflagMapper' defined in file [D:\code\ims-switchline-service\ims-switchline-service-svc\target\classes\com\csot\ims\mapper\OlFirstruneqflagMapper.class]: Unsatisfied dependency expressed through bean property 'sqlSessionFactory'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [com/baomidou/mybatisplus/autoconfigure/MybatisPlusAutoConfiguration.class]: Unsatisfied dependency expressed through method 'sqlSessionFactory' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'shardingDataSource' defined in class path resource [org/apache/shardingsphere/shardingjdbc/spring/boot/SpringBootConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'shardingDataSource' threw exception; nested exception is java.sql.SQLSyntaxErrorException: ORA-00942: 表或视图不存在

at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:643) at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:130) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1420) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:593) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:516) at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:324) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:226) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:322) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:897) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:879) at org.springframework.context.support.AbstractApplicationContext.__refresh(AbstractApplicationContext.java:551) at org.springframework.context.support.AbstractApplicationContext.jrLockAndRefresh(AbstractApplicationContext.java:40002) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:41008) at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:143) at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:758) at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:750) at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) at org.springframework.boot.SpringApplication.run(SpringApplication.java:1237) at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) at com.csot.ims.Application.main(Application.java:30) Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'artificialNodeHistoryServiceImpl': Unsatisfied dependency expressed through field 'olFirstruneqflagMapper'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'olFirstruneqflagMapper' defined in file [D:\code\ims-switchline-service\ims-switchline-service-svc\target\classes\com\csot\ims\mapper\OlFirstruneqflagMapper.class]: Unsatisfied dependency expressed through bean property 'sqlSessionFactory'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [com/baomidou/mybatisplus/autoconfigure/MybatisPlusAutoConfiguration.class]: Unsatisfied dependency expressed through method 'sqlSessionFactory' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'shardingDataSource' defined in class path resource [org/apache/shardingsphere/shardingjdbc/spring/boot/SpringBootConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'shardingDataSource' threw exception; nested exception is java.sql.SQLSyntaxErrorException: ORA-00942: 表或视图不存在

由于我在oracle中搞两个相同的数据源就可以启动项目,我不知道是我自己那里配置问题还是shardingjdbc支持oracle一个bug呢,总之解决自己困惑好几天的问题今天终于解决还是挺开心的。 本来想不能用shardingjdb分表,想用oracel的分区表来实现,但是领导对应这个做法不太满意,怕10个亿扛不住,由于我又不断的在测试环境测压数据量是否能扛住10亿的数据。

总结上面问题:如果你也出现上面问题是否考虑配置两个数据源,虽然只用到一个数据源那就配置两个相同的数据源。

第三步 创建数据库表:

 CREATE TABLE "EDU_LDA"."T_ORDER" (	"ORDER_ID" NUMBER(*,0) NOT NULL ENABLE, "USER_ID" NUMBER(*,0) NOT NULL ENABLE, "STATUS" NUMBER(*,0), PRIMARY KEY ("ORDER_ID")USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)TABLESPACE "BD_LDA_DAT"  ENABLE) SEGMENT CREATION IMMEDIATE PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS LOGGINGSTORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)TABLESPACE "BD_LDA_DAT" 

分别创建三个表:T_ORDER 、T_ORDER​​​​​​​1、T_ORDER2

 第四步:写sql 插入语句

  <!-- 保存order信息--><insert id="insertOrder" parameterType="com.csot.ims.entity.Order">INSERT INTO T_ORDER (ORDER_ID, USER_ID, STATUS)VALUES(#{orderId}, #{userId},#{status})</insert>

代码:
 

  @ApiOperation("testshardingjdbc")@GetMapping("/testshardingjdbc")public RestResponse testshardingjdbc(@Valid @NotBlank @ApiParam("InstanceNo") String instanceNo) {try {Order order = new Order();order.setStatus(6);order.setUserId(6);order.setOrderId(24);orderService.insertOrder(order);//orderService.saveFactoryList();return RestResponse.ok("");} catch (Exception e) {log.error("=="+e);return RestResponse.failed(500, "testshardingjdbc信息发生异常" + e.getMessage());}}

调用接口后

 赶紧试试吧 祝你也成功!

 

这篇关于springboot+shardingjdbc+mybatis+oracle与mysql坑的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/424131

相关文章

Mysql虚拟列的使用场景

《Mysql虚拟列的使用场景》MySQL虚拟列是一种在查询时动态生成的特殊列,它不占用存储空间,可以提高查询效率和数据处理便利性,本文给大家介绍Mysql虚拟列的相关知识,感兴趣的朋友一起看看吧... 目录1. 介绍mysql虚拟列1.1 定义和作用1.2 虚拟列与普通列的区别2. MySQL虚拟列的类型2

详解Java如何向http/https接口发出请求

《详解Java如何向http/https接口发出请求》这篇文章主要为大家详细介绍了Java如何实现向http/https接口发出请求,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 用Java发送web请求所用到的包都在java.net下,在具体使用时可以用如下代码,你可以把它封装成一

mysql数据库分区的使用

《mysql数据库分区的使用》MySQL分区技术通过将大表分割成多个较小片段,提高查询性能、管理效率和数据存储效率,本文就来介绍一下mysql数据库分区的使用,感兴趣的可以了解一下... 目录【一】分区的基本概念【1】物理存储与逻辑分割【2】查询性能提升【3】数据管理与维护【4】扩展性与并行处理【二】分区的

SpringBoot使用Apache Tika检测敏感信息

《SpringBoot使用ApacheTika检测敏感信息》ApacheTika是一个功能强大的内容分析工具,它能够从多种文件格式中提取文本、元数据以及其他结构化信息,下面我们来看看如何使用Ap... 目录Tika 主要特性1. 多格式支持2. 自动文件类型检测3. 文本和元数据提取4. 支持 OCR(光学

Java内存泄漏问题的排查、优化与最佳实践

《Java内存泄漏问题的排查、优化与最佳实践》在Java开发中,内存泄漏是一个常见且令人头疼的问题,内存泄漏指的是程序在运行过程中,已经不再使用的对象没有被及时释放,从而导致内存占用不断增加,最终... 目录引言1. 什么是内存泄漏?常见的内存泄漏情况2. 如何排查 Java 中的内存泄漏?2.1 使用 J

JAVA系统中Spring Boot应用程序的配置文件application.yml使用详解

《JAVA系统中SpringBoot应用程序的配置文件application.yml使用详解》:本文主要介绍JAVA系统中SpringBoot应用程序的配置文件application.yml的... 目录文件路径文件内容解释1. Server 配置2. Spring 配置3. Logging 配置4. Ma

MySQL中时区参数time_zone解读

《MySQL中时区参数time_zone解读》MySQL时区参数time_zone用于控制系统函数和字段的DEFAULTCURRENT_TIMESTAMP属性,修改时区可能会影响timestamp类型... 目录前言1.时区参数影响2.如何设置3.字段类型选择总结前言mysql 时区参数 time_zon

Python MySQL如何通过Binlog获取变更记录恢复数据

《PythonMySQL如何通过Binlog获取变更记录恢复数据》本文介绍了如何使用Python和pymysqlreplication库通过MySQL的二进制日志(Binlog)获取数据库的变更记录... 目录python mysql通过Binlog获取变更记录恢复数据1.安装pymysqlreplicat

Java 字符数组转字符串的常用方法

《Java字符数组转字符串的常用方法》文章总结了在Java中将字符数组转换为字符串的几种常用方法,包括使用String构造函数、String.valueOf()方法、StringBuilder以及A... 目录1. 使用String构造函数1.1 基本转换方法1.2 注意事项2. 使用String.valu

使用SQL语言查询多个Excel表格的操作方法

《使用SQL语言查询多个Excel表格的操作方法》本文介绍了如何使用SQL语言查询多个Excel表格,通过将所有Excel表格放入一个.xlsx文件中,并使用pandas和pandasql库进行读取和... 目录如何用SQL语言查询多个Excel表格如何使用sql查询excel内容1. 简介2. 实现思路3