springboot整合Mybatis配置多資料來源
阿新 • • 發佈:2018-11-08
springboot配置多資料來源有好幾種方式
1.application.properties配置
## 埠 server.port=8080 # 資料庫訪問配置 spring.datasource.type=com.alibaba.druid.pool.DruidDataSource spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.first-url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&zeroDateTimeBehavior=convertToNull&useSSL=false spring.datasource.first-username=root spring.datasource.first-password=123456 spring.datasource.historyUrl=jdbc:mysql://localhost:3306/test_history?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&zeroDateTimeBehavior=convertToNull&useSSL=false spring.datasource.historyUsername=root spring.datasource.historyPassword=123456 # 下面為連線池的補充設定,應用到上面所有資料來源中 spring.datasource.druid.initialSize=5 spring.datasource.druid.minIdle=5 spring.datasource.druid.maxActive=20 # 配置獲取連線等待超時的時間 spring.datasource.druid.maxWait=60000 # 配置間隔多久才進行一次檢測,檢測需要關閉的空閒連線,單位是毫秒 spring.datasource.druid.timeBetweenEvictionRunsMillis=60000 # 配置一個連線在池中最小生存的時間,單位是毫秒 spring.datasource.druid.minEvictableIdleTimeMillis=300000 spring.datasource.druid.validationQuery=SELECT 1 FROM DUAL spring.datasource.druid.testWhileIdle=true spring.datasource.druid.testOnBorrow=false spring.datasource.druid.testOnReturn=false # 配置監控統計攔截的filters,去掉後監控介面sql無法統計,'wall'用於防火牆 spring.datasource.druid.filter.stat.enabled=true
2.建立兩個資料來源配置DataSourceConfiguration和HistoryDataSourceConfiguration
@Configuration @MapperScan(basePackages = "com.example.demo.dao", sqlSessionTemplateRef = "sqlSessionTemplate") public class DataSourceConfiguration { public final static org.slf4j.Logger logger = LoggerFactory.getLogger(DataSourceConfiguration.class); @Value("${spring.datasource.first-url}") private String url; @Value("${spring.datasource.first-username}") private String username; @Value("${spring.datasource.first-password}") private String password; @Value("${spring.datasource.historyUrl}") private String historyUrl; @Value("${spring.datasource.historyUsername}") private String historyUsername; @Value("${spring.datasource.historyPassword}") private String historyPassword; @Value("${spring.datasource.driver-class-name}") private String driverClassName; @Value("${spring.datasource.druid.initialSize}") private int initialSize; @Value("${spring.datasource.druid.minIdle}") private int minIdle; @Value("${spring.datasource.druid.maxActive}") private int maxActive; @Value("${spring.datasource.druid.maxWait}") private int maxWait; @Value("${spring.datasource.druid.timeBetweenEvictionRunsMillis}") private int timeBetweenEvictionRunsMillis; @Value("${spring.datasource.druid.minEvictableIdleTimeMillis}") private int minEvictableIdleTimeMillis; @Value("${spring.datasource.druid.validationQuery}") private String validationQuery; @Value("${spring.datasource.druid.testWhileIdle}") private boolean testWhileIdle; @Value("${spring.datasource.druid.testOnBorrow}") private boolean testOnBorrow; @Value("${spring.datasource.druid.testOnReturn}") private boolean testOnReturn; @Bean(name = "dataSource") @Primary public DataSource dataSource(){ logger.info("初始化資料庫連線池"); DruidDataSource datasource = new DruidDataSource(); datasource.setUrl(url); datasource.setUsername(username); datasource.setPassword(password); datasource.setDriverClassName(driverClassName); //configuration datasource.setInitialSize(initialSize); datasource.setMinIdle(minIdle); datasource.setMaxActive(maxActive); datasource.setMaxWait(maxWait); datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis); datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis); datasource.setValidationQuery(validationQuery); datasource.setTestWhileIdle(testWhileIdle); datasource.setTestOnBorrow(testOnReturn); datasource.setTestOnReturn(testOnReturn); logger.info("初始化資料庫連線池完成"); return datasource; } @Bean(name = "transactionManager") @Primary public DataSourceTransactionManager transactionManager(@Qualifier("dataSource")DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } @Bean(name = "sqlSessionFactory") @Primary public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml")); bean.setTypeAliasesPackage("com.example.demo.model"); return bean.getObject(); } @Bean(name = "sqlSessionTemplate") @Primary public SqlSessionTemplate sqlSessionTemplate(@Qualifier("sqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception { return new SqlSessionTemplate(sqlSessionFactory); } }
@Configuration @MapperScan(basePackages = "com.example.demo.historyDao", sqlSessionTemplateRef = "historySqlSessionTemplate") public class HistoryDataSourceConfiguration { public final static org.slf4j.Logger logger = LoggerFactory.getLogger(HistoryDataSourceConfiguration.class); @Value("${spring.datasource.first-url}") private String url; @Value("${spring.datasource.first-username}") private String username; @Value("${spring.datasource.first-password}") private String password; @Value("${spring.datasource.historyUrl}") private String historyUrl; @Value("${spring.datasource.historyUsername}") private String historyUsername; @Value("${spring.datasource.historyPassword}") private String historyPassword; @Value("${spring.datasource.driver-class-name}") private String driverClassName; @Value("${spring.datasource.druid.initialSize}") private int initialSize; @Value("${spring.datasource.druid.minIdle}") private int minIdle; @Value("${spring.datasource.druid.maxActive}") private int maxActive; @Value("${spring.datasource.druid.maxWait}") private int maxWait; @Value("${spring.datasource.druid.timeBetweenEvictionRunsMillis}") private int timeBetweenEvictionRunsMillis; @Value("${spring.datasource.druid.minEvictableIdleTimeMillis}") private int minEvictableIdleTimeMillis; @Value("${spring.datasource.druid.validationQuery}") private String validationQuery; @Value("${spring.datasource.druid.testWhileIdle}") private boolean testWhileIdle; @Value("${spring.datasource.druid.testOnBorrow}") private boolean testOnBorrow; @Value("${spring.datasource.druid.testOnReturn}") private boolean testOnReturn; @Bean(name = "historyDataSource") public DataSource historyDataSource(){ logger.info("初始化歷史庫資料庫連線池"); DruidDataSource datasource = new DruidDataSource(); datasource.setUrl(historyUrl); datasource.setUsername(historyUsername); datasource.setPassword(historyPassword); datasource.setDriverClassName(driverClassName); //configuration datasource.setInitialSize(initialSize); datasource.setMinIdle(minIdle); datasource.setMaxActive(maxActive); datasource.setMaxWait(maxWait); datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis); datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis); datasource.setValidationQuery(validationQuery); datasource.setTestWhileIdle(testWhileIdle); datasource.setTestOnBorrow(testOnReturn); datasource.setTestOnReturn(testOnReturn); logger.info("初始化歷史庫資料庫連線池完成"); return datasource; } @Bean(name = "historyTransactionManager") public DataSourceTransactionManager historyTransactionManager(@Qualifier("historyDataSource")DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } @Bean(name = "historySqlSessionFactory") public SqlSessionFactory historySqlSessionFactory(@Qualifier("historyDataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml")); bean.setTypeAliasesPackage("com.example.demo.model"); return bean.getObject(); } @Bean(name = "historySqlSessionTemplate") public SqlSessionTemplate historySqlSessionTemplate(@Qualifier("historySqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception { return new SqlSessionTemplate(sqlSessionFactory); } }
3.建兩個不同的DAO
package com.example.demo.dao; import java.util.List; import org.apache.ibatis.annotations.Mapper; import com.example.demo.model.User; @Mapper public interface UserDao { List<User> findAll(); }
package com.example.demo.historyDao; import java.util.List; import org.apache.ibatis.annotations.Mapper; import com.example.demo.model.User; @Mapper public interface UserHistoryDao { List<User> findAll(); }
4.service
@Service public class UserService { @Autowired private UserDao userDao; @Autowired private UserHistoryDao userHistoryDao; public List<User> findList(){ return userDao.findAll(); } @Transactional public List<User> findHistoryList(){ return userHistoryDao.findAll(); } }
5.測試程式碼
@RestController public class TestController { @Autowired private UserService userService; @RequestMapping("/query") public List<User> query(HttpSession session) { return userService.findList(); } @RequestMapping("/queryHistory") public List<User> queryHistory(HttpSession session) { return userService.findHistoryList(); } }
6.輸入http://127.0.0.1:8080/query 和http://127.0.0.1:8080/queryHistory,會發現兩個請求訪問了不同的資料庫
原始碼地址:https://gitee.com/zhuyuehua/springboot-multi-database