SpringBoot项目配置多数据源实现一主多从

滴滴转载这里

首先使用idea创建springboot项目
导入所需jar包

<dependencies>
    <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>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <!--mybatis-plus-->
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.3.0</version>
    </dependency>
    <!--mysql连接-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.15</version>
    </dependency>

</dependencies>

配置src/main/resources/application.properties文件

one 数据源配置

spring.datasource.one.url=jdbc:mysql://localhost:3306/mytest?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
spring.datasource.one.username=root
spring.datasource.one.password=123456
spring.datasource.one.driverClassName=com.mysql.cj.jdbc.Driver

two 数据源配置

spring.datasource.two.url=jdbc:mysql://localhost:3306/mytest2?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
spring.datasource.two.username=root
spring.datasource.two.password=123456
spring.datasource.two.driverClassName=com.mysql.cj.jdbc.Driver
在项目文件com.example下创建mapper文件夹里面新增数据源配置再次新增文件夹one文件夹和two文件夹
具体如下图所示
20230714/5d3e064de9c4.png

在项目文件com.example下创建config文件夹里面新增数据源配置
新建class OneDataSourceConfig
package com.example.config.datasource;

import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**

  • 这里是第一数据源 其他数据源配置同第二数据源配置
    */

@Configuration
@MapperScan(basePackages = “com.example.mapper.one”, sqlSessionFactoryRef = “oneSqlSessionFactory”)
public class OneDataSourceConfig {

//获取配置信息 记得设置时区&serverTimezone=Asia/Shanghai
@Value("${spring.datasource.one.url}")
private String url;
@Value("${spring.datasource.one.username}")
private String username;
@Value("${spring.datasource.one.password}")
private String password;
@Value("${spring.datasource.one.driverClassName}")
private String driverClassName;

@Primary
@Bean(name = "oneDataSource")
public DataSource dataSource() {//创建连接数据信息配置
    return DataSourceBuilder.create()
            .url(url)
            .username(username)
            .password(password)
            .driverClassName(driverClassName).build();
}
@Primary
@Bean(name = "oneSqlSessionFactory")//配置工厂(配置数据扫描服务)
public SqlSessionFactory sqlSessionFactory(@Qualifier("oneDataSource") DataSource dataSource) throws Exception {
    //这里不可使用SqlSessionFactoryBean否则扫描会出很多问题
    MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
    bean.setDataSource(dataSource);
    bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/one/*.xml"));

// bean.setMapperLocations(resolveMapperLocations());
return bean.getObject();
}
public Resource[] resolveMapperLocations() {
ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
List mapperLocations = new ArrayList<>();
mapperLocations.add(“classpath*:mapper/one/*.xml”);
List resources = new ArrayList<>();
for (String mapperLocation : mapperLocations) {
try {
Resource[] mappers = resourceResolver.getResources(mapperLocation);
resources.addAll(Arrays.asList(mappers));
} catch (IOException e) {
// ignore
}
}
return resources.toArray(new Resource[0]);
}
@Primary
@Bean(name = “oneTransactionManager”)//创建事务
public DataSourceTransactionManager transactionManager(@Qualifier(“oneDataSource”) DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Primary
@Bean(name = “oneSqlSessionTemplate”)//创建模板
public SqlSessionTemplate sqlSessionTemplate(@Qualifier(“oneSqlSessionFactory”) SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
新建class TwoDataSourceConfig
package com.example.config.datasource;

import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = “com.example.mapper.two”,sqlSessionFactoryRef = “twoSqlSessionFactory”)
public class TwoDataSourceConfig {

@Value("${spring.datasource.two.url}")
private String url;
@Value("${spring.datasource.two.username}")
private String username;
@Value("${spring.datasource.two.password}")
private String password;
@Value("${spring.datasource.two.driverClassName}")
private String driverClassName;

@Bean(name = "twoDataSource")
public DataSource twoDataSource(){
    return DataSourceBuilder.create()
            .url(url)
            .username(username)
            .password(password)
            .driverClassName(driverClassName).build();
}

@Bean(name = "twoSqlSessionFactory")
public SqlSessionFactory sqlSessionFactory(@Qualifier("twoDataSource") DataSource dataSource) throws Exception {
    MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
    bean.setDataSource(dataSource);

// bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(“classpath:mapper/two/*.xml”));
return bean.getObject();
}

@Bean(name = "twoTransactionManager")
public DataSourceTransactionManager transactionManager(@Qualifier("twoDataSource") DataSource dataSource) {
    return new DataSourceTransactionManager(dataSource);
}

@Bean(name = "twoSqlSessionTemplate")
public SqlSessionTemplate sqlSessionTemplate(@Qualifier("twoSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
    return new SqlSessionTemplate(sqlSessionFactory);
}

}
在数据库创建两个库 一个(mytest) 一个(mytest2) 新增表
/*
Navicat Premium Data Transfer

Source Server : 本地MySQL
Source Server Type : MySQL
Source Server Version : 80027
Source Host : localhost:3306
Source Schema : mytest2

Target Server Type : MySQL
Target Server Version : 80027
File Encoding : 65001

Date: 23/02/2023 09:18:04
*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;


– Table structure for data_one


DROP TABLE IF EXISTS data_one;
CREATE TABLE data_one (
id int NOT NULL AUTO_INCREMENT,
data varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (id) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

SET FOREIGN_KEY_CHECKS = 1;
创建class DataBean
package com.example.bean;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

@Data
@TableName(“data_one”)
public class DataBean {

@TableId(type = IdType.AUTO)
private Integer id;
private String data;

}
创建interface com.example.mapper.one.DataOneMapper
package com.example.mapper.one;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.bean.DataBean;
import org.springframework.stereotype.Repository;

@Repository
public interface DataOneMapper extends BaseMapper {
}
创建interface com.example.mapper.two.DataTwoMapper
package com.example.mapper.two;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.bean.DataBean;
import org.springframework.stereotype.Repository;

@Repository
public interface DataTwoMapper extends BaseMapper {
}
创建interface com.example.service.DataService
package com.example.service;

import com.example.bean.DataBean;

import java.util.List;

public interface DataService {
//one数据插入
String addOneData(String name);
//two数据查询
List getTwoData();
}
创建class com.example.service.impl.DataServiceImpl
package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.bean.DataBean;
import com.example.mapper.one.DataOneMapper;
import com.example.mapper.two.DataTwoMapper;
import com.example.service.DataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DataServiceImpl implements DataService {

@Autowired
public DataServiceImpl(DataOneMapper oneMapper, DataTwoMapper twoMapper) {
    this.oneMapper = oneMapper;
    this.twoMapper = twoMapper;
}

DataOneMapper oneMapper;
DataTwoMapper twoMapper;

@Override
public String addOneData(String name) {
    DataBean dataBean = new DataBean();
    dataBean.setData(name);
    int insert = oneMapper.insert(dataBean);
    return insert>0?"插入成功":"插入失败";
}

@Override
public List<DataBean> getTwoData() {
    return twoMapper.selectList(new QueryWrapper<DataBean>());
}

}
创建class com.example.controller.DataController
package com.example.controller;

import com.example.bean.DataBean;
import com.example.service.DataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping(“/data”)
public class DataController {

@Autowired
public DataController(DataService dataService) {
    this.dataService = dataService;
}
DataService dataService;

@GetMapping("/add")
public String add(String name){
    return dataService.addOneData(name);
}

@GetMapping("/list")
public List<DataBean> getList(){
    return dataService.getTwoData();
}

}
运行com.example.Application 访问接口即可

最重要的是如果config里面配置了
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(“classpath*:mapper/one/*.xml”));
则需要在src/main/resources/mapper/one/DataOneMapper.xml的项目创建one和two文件夹 —上面图片有创建的所有文件示例

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Spring Boot项目配置多个数据源可以通过以下步骤实现: 1. 禁用Spring Boot数据源自动配置类。在@SpringBootApplication注解中添加exclude属性,值为DataSourceAutoConfiguration.class,如下所示: ```java @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class}) public class DatasourceDomeApplication { public static void main(String[] args) { SpringApplication.run(DatasourceDomeApplication.class, args); } } ``` 2. 创建自定义的数据源配置类。在该类中使用@Configuration注解,并定义多个@Bean方法,每个方法返回一个DataSource对象,用于初始化不同的数据源。可以使用@ConfigurationProperties(prefix = "spring.datasource.mysql-datasourceX")注解来指定每个数据源的属性配置,如下所示: ```java @Configuration public class DataSourceConfig { @Bean(name = "mysqlDataSource1") @ConfigurationProperties(prefix = "spring.datasource.mysql-datasource1") public DataSource dataSource1(){ DruidDataSource build = DruidDataSourceBuilder.create().build(); return build; } @Bean(name = "mysqlDataSource2") @ConfigurationProperties(prefix = "spring.datasource.mysql-datasource2") public DataSource dataSource2(){ DruidDataSource build = DruidDataSourceBuilder.create().build(); return build; } } ``` 3. 在application.yml配置文件中配置数据源相关的属性。可以根据需要配置每个数据源的连接信息、用户名、密码等,如下所示: ```yaml spring: datasource: mysql-datasource1: url: jdbc:mysql://localhost:3306/db1 username: root password: password1 mysql-datasource2: url: jdbc:mysql://localhost:3306/db2 username: root password: password2 ``` 通过以上步骤,你可以成功配置多个数据源,并在项目中使用对应的数据源进行数据库操作。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [Spring Boot配置多数据源的四种方式](https://blog.csdn.net/qq_45515182/article/details/126330084)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* [SpringBoot多数据源配置](https://blog.csdn.net/u012060033/article/details/123759694)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值