SpringBoot 双数据源配置

1 项目结构示意图及配置文件

主要关注mapper文件包和Mapper.xml包
SpringBoot 双数据源配置_第1张图片
配置文件ip端口及时替换

server:
  port: 8082

spring:
  application:
    name: product-server
  datasource:
    second:
      driverClassName: oracle.jdbc.driver.OracleDriver
      url: jdbc:oracle:thin:@ip:端口:服务名
      username: username
      password: password
    primary:
      driverClassName: com.mysql.jdbc.Driver
      url: jdbc:mysql://@ip:端口/数据库?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&transformedBitIsBoolean=true
      username: username
      password: password

  jta:
    transaction-manager-id: txManager

#mybatis:
#  mapper-locations: classpath*:/mapper/*Mapper.xml

2 数据库配置conf

主要注意mapper和Mapper.xml配置

  • 主库
package com.kismet.cloud.productserver.conf;

import com.alibaba.druid.pool.DruidDataSource;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import tk.mybatis.spring.annotation.MapperScan;

@Configuration
@MapperScan(basePackages = { "com.kismet.cloud.productserver.manager.model.primary.mapper" },//对应mapper文件所在包
    sqlSessionTemplateRef = "primarySqlSessionTemplate")
public class PrimaryDBConfig {
    @Value("${spring.datasource.primary.driver-class-name}")
    private String driverClassName;

    @Value("${spring.datasource.primary.url}")
    private String url;

    @Value("${spring.datasource.primary.username}")
    private String username;

    @Value("${spring.datasource.primary.password}")
    private String password;
    @Primary
    @Bean(name = "primaryDataSource")
//    @ConfigurationProperties(prefix = "spring.datasource.primary")
    public DataSource cyDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(this.driverClassName);
        dataSource.setUrl(this.url);
        dataSource.setUsername(this.username);
        dataSource.setPassword(this.password);
        return dataSource;
    }
    @Primary
    @Bean(name = "primarySqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("primaryDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(
            //扫描指定目录的Mapper的xml
            new PathMatchingResourcePatternResolver().getResources("classpath:mapper/primary/*Mapper.xml"));
        return bean.getObject();
    }
    @Primary
    @Bean(name = "primarySqlSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate(
        @Qualifier("primarySqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

  • 从库
package com.kismet.cloud.productserver.conf;

import com.alibaba.druid.pool.DruidDataSource;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import tk.mybatis.spring.annotation.MapperScan;

@Configuration
@MapperScan(basePackages = {"com.kismet.cloud.productserver.manager.model.second.mapper"},//对应mapper文件所在包
    sqlSessionTemplateRef = "secondarySqlSessionTemplate")
public class SecondaryDBConfig {

    @Value("${spring.datasource.second.driver-class-name}")
    private String driverClassName;

    @Value("${spring.datasource.second.url}")
    private String url;

    @Value("${spring.datasource.second.username}")
    private String username;

    @Value("${spring.datasource.second.password}")
    private String password;

    @Bean(name = "secondDataSource")
//    @ConfigurationProperties(prefix = "spring.datasource.second")
    public DataSource jyDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(this.driverClassName);
        dataSource.setUrl(this.url);
        dataSource.setUsername(this.username);
        dataSource.setPassword(this.password);
        return dataSource;
    }

    @Bean(name = "secondarySqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("secondDataSource") DataSource dataSource)
            throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        //扫描指定目录的Mapper的xml
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/second/*Mapper.xml"));
        return bean.getObject();
    }

    @Bean(name = "secondarySqlSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate(
            @Qualifier("secondarySqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

3 mapper文件实例

package com.kismet.cloud.productserver.manager.model.primary.mapper;

import com.kismet.cloud.productserver.manager.model.primary.entity.CyOffsetStore;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

/**
 * @author kismet
 * @since 2020/3/26
 */
@Mapper
public interface CyOffsetStoreMapper {
    int deleteByPrimaryKey(Long id);

    int insert(CyOffsetStore record);

    int insertSelective(CyOffsetStore record);

    CyOffsetStore selectByPrimaryKey(Long id);

    int updateByPrimaryKeySelective(CyOffsetStore record);

    int updateByPrimaryKey(CyOffsetStore record);

    /**
     * 通过主题查记录
     * @param topic
     * @return
     */
    CyOffsetStore selectByTopic(String topic);

    /**
     * 更新offset
     * @param id
     * @param offset
     * @return
     */
    int commitOffset(@Param("id") Long id, @Param("offset") Integer offset);
}

4 调用文件实例

/**
 * @author kismet
 * @version V1.0
 * @since 2020-01-11 16:44
 */
@RestController
public class ProductFeignClient  {

    @Autowired
    private DoctorTeamMapper doctorTeamMapper;
    @Autowired
    private CyOffsetStoreMapper cyOffsetStoreMapper;


    @Override
    public List<Product> list() {
        System.out.println(doctorTeamMapper.selectByPrimaryKey("111"));
        System.out.println(cyOffsetStoreMapper.selectByPrimaryKey(11L));
        return null;
    }
}

项目实现连接
资源下载

你可能感兴趣的:(Java)