springboot配置多数据源详细操作

demo地址
https://github.com/gnq619037/muti-datasource/tree/master
application.properties配置

server.port=8080
server.servlet.context-path=/dataSource
##local-dataSource
spring.datasource.local.url=jdbc:mysql://localhost:3306/local?allowMultiQueries=true&useSSL=false
spring.datasource.local.username=root
spring.datasource.local.password=123456
spring.datasource.local.driver-class-name=com.mysql.jdbc.Driver
##remote-dataSource
spring.datasource.remote.url=jdbc:mysql://localhost:3306/remote?allowMultiQueries=true&useSSL=false
spring.datasource.remote.username=root
spring.datasource.remote.password=123456
spring.datasource.remote.driver-class-name=com.mysql.jdbc.Driver
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
public class MutiDataSourceApp {
    public static void main(String[] args) {
        SpringApplication.run(MutiDataSourceApp.class, args);
    }
}

配置一个本地数据源

package com.gnq.datasource.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
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.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = {"com.gnq.datasource.dao.local"}, sqlSessionTemplateRef = "localSqlSessionTemplate")
public class LocalDataSourceConfig {

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

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

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

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

    @Bean
    /// 根据application.properteis系统配置文件中,对应属性的前缀,指明使用其对应的数据
    @ConfigurationProperties(prefix = "spring.datasource.local")
    public DataSource localDataSource() {
        return DataSourceBuilder.create().url(dbUrl).driverClassName(driverClassName).password(password).username(username).build();
    }

    @Bean
    @DependsOn("localDataSource")
    public SqlSessionFactory localSqlSessionFactory() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(localDataSource());
        return factoryBean.getObject();
    }

    /**
     * DefaultSqlSession和SqlSessionTemplate都实现了SqlSession,但我们
     * 注入线程安全的SqlSessionTemplate,而不使用默认的线程不安全的DefaultSqlSession
     */
    @Bean
    @DependsOn("localSqlSessionFactory")
    public SqlSessionTemplate localSqlSessionTemplate() throws Exception {
        return new SqlSessionTemplate(localSqlSessionFactory());
    }

    /**
     * 事务管理器
     */
    @Bean("localTransactionManager")
    @DependsOn("localDataSource")
    public DataSourceTransactionManager localTransactionManager(@Qualifier("localDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}

配置一个远程数据源

package com.gnq.datasource.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
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.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = {"com.gnq.datasource.dao.remote"}, sqlSessionTemplateRef = "remoteSqlSessionTemplate")
public class RemoteDataSourceConfig {

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

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

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

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

    @Bean
    // 根据application.properteis系统配置文件中,对应属性的前缀,指明使用其对应的数据
    @ConfigurationProperties(prefix = "spring.datasource.remote")
    public DataSource remoteDataSource() {
        return DataSourceBuilder.create().url(dbUrl).username(username).password(password).driverClassName(driverClassName).build();
    }

    @Bean
    @DependsOn("remoteDataSource")
    public SqlSessionFactory remoteSqlSessionFactory() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(remoteDataSource());
        return factoryBean.getObject();
    }

    /**
     * DefaultSqlSession和SqlSessionTemplate都实现了SqlSession,但我们
     * 注入线程安全的SqlSessionTemplate,而不使用默认的线程不安全的DefaultSqlSession
     */
    @Bean
    @DependsOn("remoteSqlSessionFactory")
    public SqlSessionTemplate remoteSqlSessionTemplate() throws Exception {
        return new SqlSessionTemplate(remoteSqlSessionFactory());
    }

    /**
     * 事务管理器
     */
    @Bean("remoteTransactionManager")
    @DependsOn("remoteDataSource")
    public DataSourceTransactionManager remoteTransactionManager(@Qualifier("remoteDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}

@Mapper
public interface UserMapper {

    /**
     * 查询所有用户
     * @return
     */
    @Select("select id, username, password from t_user")
    public List<User> queryUsers();
}
@Mapper
public interface RemoteUserMapper {

    /**
     * 查询所有用户
     * @return
     */
    @Select("select id, username, password from t_user")
    public List<User> queryUsers();
}

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RemoteUserMapper remoteUserMapper;

    @Override
    public List<User> listFromLocal() {
        return userMapper.queryUsers();
    }

    @Override
    public List<User> listFromRemote() {
        return remoteUserMapper.queryUsers();
    }
}
@RestController
@RequestMapping(value = "/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/list/local")
    public Object listUsersFromLocal(){
        return userService.listFromLocal();
    }

    @GetMapping("/list/remote")
    public Object listUsersFromRemote(){
        return userService.listFromRemote();
    }
}

数据库:local

id username password
1 小月 123456
1 大宝 363636

数据库:remote

id username password
1 小明 111111
1 小红 222222

测试
在这里插入图片描述
在这里插入图片描述

你可能感兴趣的:(java)