本文共 11287 字,大约阅读时间需要 37 分钟。
本篇文章将详细讲述如何在SpringBoot项目中实现多数据源配置、Druid数据库连接池的使用以及PageHelper分页插件的应用。通过本文的内容,读者可以了解如何在一个SpringBoot项目中高效地管理多个数据库,并通过Druid实现数据库连接池的监控和管理,同时利用PageHelper实现分页功能。
在使用Druid之前,先来简单了解一下Druid是什么。
Druid 是一个功能强大、高效且可扩展性的数据库连接池,其核心功能包括:
Druid 的主要功能包括:
在SpringBoot项目中使用Druid,需要在application.properties文件中添加以下配置:
# master数据源配置master.datasource.url=jdbc:mysql://localhost:3306/springBoot?useUnicode=true&characterEncoding=utf8&allowMultiQueries=truemaster.datasource.username=rootmaster.datasource.password=123456master.datasource.driverClassName=com.mysql.jdbc.Driver# cluster数据源配置cluster.datasource.url=jdbc:mysql://localhost:3306/springBoot_test?useUnicode=true&characterEncoding=utf8cluster.datasource.username=rootcluster.datasource.password=123456cluster.datasource.driverClassName=com.mysql.jdbc.Driver# 连接池配置spring.datasource.type=com.alibaba.druid.pool.DruidDataSourcespring.datasource.initialSize=5spring.datasource.minIdle=5spring.datasource.maxActive=20spring.datasource.maxWait=60000spring.datasource.timeBetweenEvictionRunsMillis=60000spring.datasource.minEvictableIdleTimeMillis=300000spring.datasource.validationQuery=SELECT 1 FROM DUALspring.datasource.testWhileIdle=truespring.datasource.testOnBorrow=falsespring.datasource.testOnReturn=falsespring.datasource.poolPreparedStatements=truespring.datasource.maxPoolPreparedStatementPerConnectionSize=20spring.datasource.filters=stat,wall,log4jspring.datasource.connectionProperties=druid.stat.mergeSql=true; druid.stat.slowSqlMillis=5000
在SpringBoot项目中使用Druid,需要编写MasterDataSourceConfig.java和ClusterDataSourceConfig.java类来配置数据源。
@Configuration@MapperScan(basePackages = "com.pancm.dao.master", sqlSessionFactoryRef = "masterSqlSessionFactory")public class MasterDataSourceConfig { static final String PACKAGE = "com.pancm.dao.master"; static final String MAPPER_LOCATION = "classpath:mapper/master/*.xml"; @Value("${master.datasource.url}") private String url; @Value("${master.datasource.username}") private String username; @Value("${master.datasource.password}") private String password; @Value("${master.datasource.driverClassName}") private String driverClassName; @Value("${spring.datasource.initialSize}") private int initialSize; @Value("${spring.datasource.minIdle}") private int minIdle; @Value("${spring.datasource.maxActive}") private int maxActive; @Value("${spring.datasource.maxWait}") private int maxWait; @Value("${spring.datasource.timeBetweenEvictionRunsMillis}") private int timeBetweenEvictionRunsMillis; @Value("${spring.datasource.minEvictableIdleTimeMillis}") private int minEvictableIdleTimeMillis; @Value("${spring.datasource.validationQuery}") private String validationQuery; @Value("${spring.datasource.testWhileIdle}") private boolean testWhileIdle; @Value("${spring.datasource.testOnBorrow}") private boolean testOnBorrow; @Value("${spring.datasource.testOnReturn}") private boolean testOnReturn; @Value("${spring.datasource.poolPreparedStatements}") private boolean poolPreparedStatements; @Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}") private int maxPoolPreparedStatementPerConnectionSize; @Value("${spring.datasource.filters}") private String filters; @Value("{spring.datasource.connectionProperties}") private String connectionProperties; @Bean(name = "masterDataSource") @Primary public DataSource masterDataSource() { DruidDataSource dataSource = new DruidDataSource(); dataSource.setUrl(url); dataSource.setUsername(username); dataSource.setPassword(password); dataSource.setDriverClassName(driverClassName); 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(testOnBorrow); dataSource.setTestOnReturn(testOnReturn); dataSource.setPoolPreparedStatements(poolPreparedStatements); dataSource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize); try { dataSource.setFilters(filters); } catch (SQLException e) { e.printStackTrace(); } dataSource.setConnectionProperties(connectionProperties); return dataSource; } @Bean(name = "masterTransactionManager") public DataSourceTransactionManager masterTransactionManager() { return new DataSourceTransactionManager(masterDataSource()); } @Bean(name = "masterSqlSessionFactory") public SqlSessionFactory masterSqlSessionFactory(@Qualifier("masterDataSource") DataSource masterDataSource) throws Exception { SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(); sessionFactory.setDataSource(masterDataSource); sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPER_LOCATION)); return sessionFactory.getObject(); }} 在SpringBoot项目中实现多数据源,需要分别配置主数据源和副数据源,并确保它们可以正常通信。
在SpringBoot和SpringBoot_test数据库中执行以下SQL脚本:
-- springBoot库的脚本CREATE TABLE `t_user` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '自增id', `name` varchar(10) DEFAULT NULL COMMENT '姓名', `age` int(2) DEFAULT NULL COMMENT '年龄', PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8;-- springBoot_test库的脚本CREATE TABLE `t_student` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(16) DEFAULT NULL, `age` int(11) DEFAULT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
在MasterDataSourceConfig.java和ClusterDataSourceConfig.java类中,分别配置主数据源和副数据源。
@Configuration@MapperScan(basePackages = "com.pancm.dao.cluster", sqlSessionFactoryRef = "clusterSqlSessionFactory")public class ClusterDataSourceConfig { static final String PACKAGE = "com.pancm.dao.cluster"; static final String MAPPER_LOCATION = "classpath:mapper/cluster/*.xml"; @Value("${cluster.datasource.url}") private String url; @Value("${cluster.datasource.username}") private String username; @Value("${cluster.datasource.password}") private String password; @Value("${cluster.datasource.driverClassName}") private String driverClass; @Bean(name = "clusterDataSource") public DataSource clusterDataSource() { DruidDataSource dataSource = new DruidDataSource(); dataSource.setUrl(url); dataSource.setUsername(username); dataSource.setPassword(password); dataSource.setDriverClassName(driverClass); return dataSource; } @Bean(name = "clusterTransactionManager") public DataSourceTransactionManager clusterTransactionManager() { return new DataSourceTransactionManager(clusterDataSource()); } @Bean(name = "clusterSqlSessionFactory") public SqlSessionFactory clusterSqlSessionFactory(@Qualifier("clusterDataSource") DataSource clusterDataSource) throws Exception { SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(); sessionFactory.setDataSource(clusterDataSource); sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPER_LOCATION)); return sessionFactory.getObject(); }} PageHelper 是 MyBatis 的一个优秀分页插件,使用起来非常方便。
在Maven中添加PageHelper的依赖:
com.github.pagehelper pagehelper-spring-boot-starter 1.2.3
在application.properties文件中添加PageHelper的配置:
pagehelper: helperDialect: mysqloffsetAsPageNum: truerowBoundsWithCount: truereasonable: false
在MasterDataSourceConfig.java类中,修改masterSqlSessionFactory方法,添加PageHelper插件:
@Bean(name = "masterSqlSessionFactory")public SqlSessionFactory masterSqlSessionFactory(@Qualifier("masterDataSource") DataSource masterDataSource) throws Exception { SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(); sessionFactory.setDataSource(masterDataSource); sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPER_LOCATION)); // 添加PageHelper插件 Interceptor interceptor = new PageInterceptor(); Properties properties = new Properties(); properties.setProperty("helperDialect", "mysql"); properties.setProperty("offsetAsPageNum", "true"); properties.setProperty("rowBoundsWithCount", "true"); properties.setProperty("reasonable", "false"); interceptor.setProperties(properties); sessionFactory.setPlugins(new Interceptor[] { interceptor }); return sessionFactory.getObject();} 在DAO接口中使用PageHelper进行分页查询:
public ListfindByListEntity(T entity) { List list = null; try { Page page = PageHelper.startPage(1, 2); System.out.println("User设置第一页两条数据!"); list = getMapper().findByListEntity(entity); System.out.println("总共有:" + page.getTotal() + "条数据,实际返回:" + list.size() + "两条数据!"); } catch (Exception e) { logger.error("查询" + getClassName(entity) + "失败!原因是:", e); } return list;}
Druid提供了一个Web监控界面,可以实时监控数据库访问情况。为了实现Druid监控,在SpringBoot项目中添加DruidConfiguration.java类,注册StatViewServlet和WebStatFilter。
@Configurationpublic class DruidConfiguration { @Bean public ServletRegistrationBean druidStatViewServle() { ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*"); servletRegistrationBean.addInitParameter("allow", "127.0.0.1"); servletRegistrationBean.addInitParameter("deny", "127.0.0.2"); servletRegistrationBean.addInitParameter("loginUsername", "pancm"); servletRegistrationBean.addInitParameter("loginPassword", "123456"); servletRegistrationBean.addInitParameter("resetEnable", "false"); return servletRegistrationBean; } @Bean public FilterRegistrationBean druidStatFilter() { FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter()); filterRegistrationBean.addUrlPatterns("/*"); filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"); System.out.println("druid初始化成功!"); return filterRegistrationBean; }} 通过本文的内容,读者可以了解如何在SpringBoot项目中实现多数据源配置、Druid数据库连接池的使用以及PageHelper分页插件的应用。Druid 的监控功能可以帮助开发人员更好地了解数据库的使用情况,而PageHelper 的分页功能则能够提高应用的性能和用户体验。
如果需要了解更多关于Druid和PageHelper的使用方法,可以参考以下资源:
更多关于SpringBoot项目的源码,可以参考以下仓库:
如果对本文有任何疑问或建议,欢迎在评论区留言交流!
转载地址:http://qsqfk.baihongyu.com/