当前位置:   article > 正文

java项目配置双数据源,对两个不同服务器上的数据库中的数据进行CRUD_java双数据源

java双数据源

基于springboot+mybatisPlus,对两个不同服务器上的数据库中的数据进行CRUD,我自己使用的两个都是mysql数据库;db1为我自己的本地库,db2为阿里云服务器上的库,首先我们创建两张表;

在db1库中创建user表,建表语句如下:

  1. CREATE TABLE `user` (
  2. `id` int(11) NOT NULL AUTO_INCREMENT,
  3. `name` varchar(64) DEFAULT NULL,
  4. `age` tinyint(2) DEFAULT NULL,
  5. `sex` tinyint(1) DEFAULT NULL COMMENT '0:女 1:男',
  6. PRIMARY KEY (`id`)
  7. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4

然后在db2库中创建product表,建表语句如下:

  1. CREATE TABLE `product` (
  2. `id` int(10) NOT NULL,
  3. `phone` bigint(11) DEFAULT NULL,
  4. `address` varchar(64) DEFAULT NULL,
  5. `email` varchar(32) DEFAULT NULL,
  6. `birth` date DEFAULT NULL,
  7. PRIMARY KEY (`id`)
  8. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4

创建完成后,新建一个springboot项目,创建好后导入Mybatis Plus Generator和mysql依赖

  1. <dependency>
  2. <groupId>com.baomidou</groupId>
  3. <artifactId>mybatis-plus-generator</artifactId>
  4. <version>3.4.1</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.apache.velocity</groupId>
  8. <artifactId>velocity</artifactId>
  9. <version>1.7</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>mysql</groupId>
  13. <artifactId>mysql-connector-java</artifactId>
  14. <version>8.0.25</version>
  15. </dependency>

除了导入 mybatis-plus-generator依赖外,还需要导入velocity模板,因为MP是按照这个模板来生成代码的。接着新建一个Generator类来生成我们所需要的文件:

  1. public class Generator {
  2. public static void main(String[] args) {
  3. //1.创建generator对象
  4. AutoGenerator autoGenerator = new AutoGenerator();
  5. //2.配置数据源db1
  6. DataSourceConfig dataSourceConfig = new DataSourceConfig();
  7. dataSourceConfig.setDbType(DbType.MYSQL); //数据源类型为mysql
  8. dataSourceConfig.setUrl("jdbc:mysql://localhost:3306/db1?useSSL=false&useUnicode=true&characterEncoding=utf-8");
  9. dataSourceConfig.setUsername("root");
  10. dataSourceConfig.setPassword("密码");
  11. dataSourceConfig.setDriverName("com.mysql.cj.jdbc.Driver");
  12. //配置数据源db2 ,
  13. dataSourceConfig.setDbType(DbType.MYSQL); //数据源类型为mysql
  14. dataSourceConfig.setUrl("jdbc:mysql://8.142.139.26:3306/db2?useSSL=false&useUnicode=true&characterEncoding=utf-8");
  15. dataSourceConfig.setUsername("用户名");
  16. dataSourceConfig.setPassword("你的密码");
  17. dataSourceConfig.setDriverName("com.mysql.cj.jdbc.Driver");
  18. autoGenerator.setDataSource(dataSourceConfig);
  19. //3.全局配置(指明这些类生成的具体位置以及作者....)
  20. GlobalConfig globalConfig = new GlobalConfig();
  21. //这里填写要成的位置
  22. globalConfig.setOutputDir("D:\\javaProject\\sprng2db"+"/src/main/java");
  23. globalConfig.setOpen(false);//不打开文件
  24. globalConfig.setAuthor("gaoyj");
  25. //让service名字前面没有I
  26. globalConfig.setServiceName("%Service");
  27. autoGenerator.setGlobalConfig(globalConfig);
  28. //4.设置包信息(生成的类放在哪个包里面)
  29. PackageConfig packageConfig = new PackageConfig();
  30. packageConfig.setParent("com.solongyj");
  31. packageConfig.setModuleName("generator");
  32. packageConfig.setController("controller");
  33. packageConfig.setService("service");
  34. packageConfig.setServiceImpl("service.impl");
  35. packageConfig.setEntity("entity");
  36. autoGenerator.setPackageInfo(packageConfig);
  37. //5.配置策略
  38. StrategyConfig strategyConfig = new StrategyConfig();
  39. //提供lombok
  40. strategyConfig.setEntityLombokModel(true);
  41. //支持驼峰
  42. strategyConfig.setNaming(NamingStrategy.underline_to_camel);
  43. strategyConfig.setColumnNaming(NamingStrategy.underline_to_camel);
  44. autoGenerator.setStrategy(strategyConfig);
  45. //6.执行
  46. autoGenerator.execute();
  47. }

 先执行db1,然后把数据库配置修改为db2的内容,再操作一次,执行完毕后结构如下:

然后是两个数据源的配置类,db1的配置类代码如下:

  1. @Configuration
  2. @MapperScan(basePackages = "com.solongyj.demo.mapper.db1", sqlSessionTemplateRef = "db1SqlSessionTemplate")
  3. public class DataSourceDb1config {
  4. /**
  5. * 获取映射文件所在的路径
  6. */
  7. @Value("${mybatis.db1.mapper-locations}")
  8. private String db1tMapperPath;
  9. /**
  10. * 数据源加载
  11. *
  12. * @return
  13. */
  14. @Bean(name = "db1DataSource")
  15. @ConfigurationProperties(prefix = "spring.datasource.db1.druid")
  16. public DataSource test1DataSource() {
  17. return DataSourceBuilder.create().build();
  18. }
  19. /**
  20. * 注入SqlSessionFactory,指定数据源和映射文件路径
  21. *
  22. * @param dataSource
  23. * @return
  24. * @throws Exception
  25. */
  26. @Bean(name = "db1SqlSessionFactory")
  27. public SqlSessionFactory testSqlSessionFactory(@Qualifier("db1DataSource") DataSource dataSource) throws Exception {
  28. MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
  29. bean.setDataSource(dataSource);
  30. Resource[] resources = new PathMatchingResourcePatternResolver().getResources(db1tMapperPath);
  31. bean.setMapperLocations(resources);
  32. return bean.getObject();
  33. }
  34. /**
  35. * 注入DataSourceTransactionManager事物管理器
  36. *
  37. * @param dataSource
  38. * @return
  39. */
  40. @Bean(name = "db1TransactionManager")
  41. public DataSourceTransactionManager testTransactionManager(@Qualifier("db1DataSource") DataSource dataSource) {
  42. return new DataSourceTransactionManager(dataSource);
  43. }
  44. /**
  45. * @param sqlSessionFactory
  46. * @return
  47. * @throws Exception
  48. */
  49. @Bean(name = "db1SqlSessionTemplate")
  50. public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("db1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
  51. return new SqlSessionTemplate(sqlSessionFactory);
  52. }
  53. }

db2配置类代码

  1. @Configuration
  2. @MapperScan(basePackages = "com.solongyj.demo.mapper.db2", sqlSessionTemplateRef = "db2SqlSessionTemplate")
  3. public class DataSourceDb2Config {
  4. /**
  5. * 获取映射文件所在的路径
  6. */
  7. @Value("${mybatis.db2.mapper-locations}")
  8. private String db2tMapperPath;
  9. /**
  10. * 数据源加载
  11. *
  12. * @return
  13. */
  14. @Bean(name = "db2DataSource")
  15. @ConfigurationProperties(prefix = "spring.datasource.db2.druid")
  16. public DataSource test1DataSource() {
  17. return DataSourceBuilder.create().build();
  18. }
  19. /**
  20. * 注入SqlSessionFactory,指定数据源和映射文件路径
  21. *
  22. * @param dataSource
  23. * @return
  24. * @throws Exception
  25. */
  26. @Bean(name = "db2SqlSessionFactory")
  27. public SqlSessionFactory testSqlSessionFactory(@Qualifier("db2DataSource") DataSource dataSource) throws Exception {
  28. MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
  29. bean.setDataSource(dataSource);
  30. Resource[] resources = new PathMatchingResourcePatternResolver().getResources(db2tMapperPath);
  31. bean.setMapperLocations(resources);
  32. return bean.getObject();
  33. }
  34. /**
  35. * 注入DataSourceTransactionManager事物管理器
  36. *
  37. * @param dataSource
  38. * @return
  39. */
  40. // @Bean(name = "db2TransactionManager")
  41. public DataSourceTransactionManager testTransactionManager(@Qualifier("db2DataSource") DataSource dataSource) {
  42. return new DataSourceTransactionManager(dataSource);
  43. }
  44. /**
  45. * @param sqlSessionFactory
  46. * @return
  47. * @throws Exception
  48. */
  49. @Bean(name = "db2SqlSessionTemplate")
  50. public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("db2SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
  51. return new SqlSessionTemplate(sqlSessionFactory);
  52. }

application.yml中配置

  1. server:
  2. port: 8089
  3. #配置数据源,db1&db2
  4. spring:
  5. datasource:
  6. db1:
  7. druid:
  8. driver-class-name: com.mysql.cj.jdbc.Driver
  9. jdbc-url: jdbc:mysql://localhost:3306/db1?autoReconnect=true&useUnicode=true&characterEncoding=utf8&useSSL=true
  10. username: root
  11. password: root
  12. db2:
  13. druid:
  14. driver-class-name: com.mysql.cj.jdbc.Driver
  15. jdbc-url: jdbc:mysql://ip:port/db2?autoReconnect=true&useUnicode=true&characterEncoding=utf8&useSSL=true
  16. username: 你的用户名
  17. password: 你的密码
  18. # xml文件映射路径
  19. mybatis:
  20. db1:
  21. mapper-locations: classpath:mapper/db1/*.xml
  22. db2:
  23. mapper-locations: classpath:mapper/db2/*.xml
  24. logging:
  25. level:
  26. com.solongyj.demo: debug

配置完成后进行一个简单的测试,在user表数据插入成功后再执行product表数据的插入

  1. @Service
  2. @Slf4j
  3. @Transactional(rollbackFor = Exception.class)
  4. public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
  5. @Autowired
  6. private UserMapper userMapper;
  7. @Autowired
  8. private ProductMapper productMapper;
  9. @Override
  10. public void addUser(User user) {
  11. log.info("db1数据开始插入");
  12. int userRow = userMapper.insert(user);
  13. //这里在插入user成功后进行db2中的product的插入,这些数据全都随机生成
  14. if (userRow != 0) {
  15. log.info("db1数据插入成功");
  16. Product product = new Product();
  17. product.setPhone(RandomUtil.getPhone());
  18. product.setAddress(RandomUtil.getAddress());
  19. product.setEmail(RandomUtil.getEmail(6, 9));
  20. product.setBirth(new Date());
  21. log.info("db2数据开始插入");
  22. int prodRow = productMapper.insert(product);
  23. if (prodRow != 0) {
  24. log.info("db1和db2数据插入成功");
  25. }
  26. }
  27. }
  28. }

其中user数据我们以json格式传进来,product数据我写了一个随机生成中文姓名,性别,Email,手机号,住址的工具类,其代码如下:

  1. /**
  2. * 随机生成中文姓名,性别,Email,手机号,住址
  3. *
  4. * @author solongyj
  5. * @date 2022/3/29
  6. */
  7. public class RandomUtil {
  8. public static String base = "abcdefghijklmnopqrstuvwxyz0123456789";
  9. private static String firstName = "赵钱孙李周吴郑王冯陈褚卫蒋沈韩杨朱秦尤许何吕施张孔曹严华金魏陶姜戚谢邹郜喻柏水窦章云苏潘葛奚范彭郎鲁韦昌马苗凤花方俞任袁柳酆鲍史唐费廉岑薛雷贺倪汤滕殷罗毕郝邬安常乐于时傅皮卞齐康伍余元卜顾孟平黄和穆萧尹姚邵湛汪祁毛禹狄米贝明臧计伏成戴谈宋茅庞熊纪舒屈项祝董梁杜阮蓝闵席季麻强贾路娄危江童颜郭梅盛林刁钟徐邱骆高夏蔡田樊胡凌霍虞万支柯咎管卢莫经房裘缪干解应宗宣丁贲邓郁单杭洪包诸左石崔吉钮龚程嵇邢滑裴陆荣翁荀";
  10. private static String girl = "珍贞莉桂娣叶璧璐娅琦晶妍茜秋珊莎锦黛青倩婷姣婉娴瑾颖露瑶怡婵雁蓓纨仪荷丹蓉眉君琴蕊薇姬舒影荔枝思丽 ";
  11. private static String boy = "杰彦涛昌强成康星光天达安岩中茂进林有坚和彪博诚先敬震振壮会思群豪心邦承乐绍功松善厚庆磊民友裕河哲江超浩亮政谦亨奇固之轮翰朗伯宏言若鸣朋斌梁栋维启克伦翔旭鹏泽晨辰士以建家致树炎德行时泰盛雄琛钧冠策腾楠榕风航弘";
  12. private static String[] address = "北京路,南京路,上海路,郑州路,杭州路,福州路,兰州路,哈尔滨路,长春路,沈阳路,成都路,重庆路,济南路,西安路,银川路,太原路,合肥路,南昌路,广州路,海南路,台北路,贵州路,昆明路".split(",");
  13. private static final String[] email_suffix = "@gmail.com,@qq.com,@163.com,@sina.com,@sohu.com".split(",");
  14. public static int getNum(int start, int end) {
  15. return (int) (Math.random() * (end - start + 1) + start);
  16. }
  17. /**
  18. * 返回Email
  19. *
  20. * @param lMin 最小长度
  21. * @param lMax 最大长度
  22. * @return
  23. */
  24. public static String getEmail(int lMin, int lMax) {
  25. int length = getNum(lMin, lMax);
  26. StringBuffer sb = new StringBuffer();
  27. for (int i = 0; i < length; i++) {
  28. int number = (int) (Math.random() * base.length());
  29. sb.append(base.charAt(number));
  30. }
  31. sb.append(email_suffix[(int) (Math.random() * email_suffix.length)]);
  32. return sb.toString();
  33. }
  34. /**
  35. * 返回手机号码
  36. */
  37. private static String[] telFirst = "135,136,138,139,150,151,152,159,156,133,153".split(",");
  38. public static Long getPhone() {
  39. int index = getNum(0, telFirst.length - 1);
  40. String first = telFirst[index];
  41. String second = String.valueOf(getNum(1, 888) + 10000).substring(1);
  42. String third = String.valueOf(getNum(1, 9100) + 10000).substring(1);
  43. return Long.valueOf(first + second + third);
  44. }
  45. /**
  46. * 返回中文姓名
  47. */
  48. private static String name_sex = "";
  49. public static String getChineseName() {
  50. int index = getNum(0, firstName.length() - 1);
  51. String first = firstName.substring(index, index + 1);
  52. int sex = getNum(0, 1);
  53. String str = boy;
  54. int length = boy.length();
  55. if (sex == 0) {
  56. str = girl;
  57. length = girl.length();
  58. name_sex = "女";
  59. } else {
  60. name_sex = "男";
  61. }
  62. index = getNum(0, length - 1);
  63. String second = str.substring(index, index + 1);
  64. int hasThird = getNum(0, 1);
  65. String third = "";
  66. if (hasThird == 1) {
  67. index = getNum(0, length - 1);
  68. third = str.substring(index, index + 1);
  69. }
  70. return first + second + third;
  71. }
  72. /**
  73. * 返回地址
  74. *
  75. * @return
  76. */
  77. public static String getAddress() {
  78. int index = getNum(0, address.length - 1);
  79. String first = address[index];
  80. String second = String.valueOf(getNum(11, 150)) + "号";
  81. String third = "-" + getNum(1, 20) + "-" + getNum(1, 10);
  82. return first + second + third;
  83. }
  84. }

总体结构如下图

 

在controller层调用UserService的addUser方法,然后启动该项目,因为配置的端口号是8089,所以在测试时地址为http://localhost:8089/addUser 

如图

经测试,db1和db2都可以成功插入数据。

        以上就是关于java对两个不同服务器上的数据库中的数据进行的简单的数据新增,同理,三个以及多个数据源操作也可按照该方法进行配置;

代码我已上传到gitee,感兴趣的小伙伴可以看一看:https://gitee.com/solongyj/spring2db.git

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/52336
推荐阅读
相关标签
  

闽ICP备14008679号