本篇文章主要講述的是SpringBoot整合Mybatis、Druid和PageHelper 並實現多數據源和分頁。其中SpringBoot整合Mybatis這塊,在之前的的一篇文章中已經講述了,這裡就不過多說明了。重點是講述在多數據源下的如何配置使用Druid和PageHelper 。
在使用Druid之前,先來簡單的了解下Druid。
Druid是一個資料庫連接池。Druid可以說是目前最好的資料庫連接池!因其優秀的功能、性能和擴展性方面,深受開發人員的青睞。Druid已經在阿里巴巴部署了超過600個應用,經過一年多生產環境大規模部署的嚴苛考驗。Druid是阿里巴巴開發的號稱為監控而生的資料庫連接池!
同時Druid不僅僅是一個資料庫連接池,Druid 核心主要包括三部分:
Druid的主要功能如下:
介紹方面這塊就不再多說,具體的可以看官方文檔。那麼開始介紹Druid如何使用。
首先是Maven依賴,只需要添加druid這一個jar就行了。
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.8</version></dependency>
配置方面,主要的只需要在application.properties或application.yml添加如下就可以了。說明:因為這裡我是用來兩個數據源,所以稍微有些不同而已。Druid 配置的說明在下面中已經說的很詳細了,這裡我就不在說明了。
默認的數據源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.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=5 spring.datasource.minIdle=5 spring.datasource.maxActive=20 配置間隔多久才進行一次檢測,檢測需要關閉的空閒連接,單位是毫秒 spring.datasource.timeBetweenEvictionRunsMillis=60000 打開PSCache,並且指定每個連接上PSCache的大小 spring.datasource.poolPreparedStatements=true spring.datasource.maxPoolPreparedStatementPerConnectionSize=20 39;wall& 通過connectProperties屬性來打開mergeSql功能;慢SQL記錄 spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
成功添加了配置文件之後,我們再來編寫Druid相關的類。首先是MasterDataSourceConfig.java這個類,這個是默認的數據源配置類。
@Configuration@MapperScan(basePackages = MasterDataSourceConfig.PACKAGE, sqlSessionFactoryRef = &34;)public class MasterDataSourceConfig { static final String PACKAGE = &34;; static final String MAPPER_LOCATION = &34;; @Value(&34;) private String url; @Value(&34;) private String username; @Value(&34;) private String password; @Value(&34;) private String driverClassName; @Value(&34;) private int initialSize; @Value(&34;) private int minIdle; @Value(&34;) private int maxActive; @Value(&34;) private int maxWait; @Value(&34;) private int timeBetweenEvictionRunsMillis; @Value(&34;) private int minEvictableIdleTimeMillis; @Value(&34;) private String validationQuery; @Value(&34;) private boolean testWhileIdle; @Value(&34;) private boolean testOnBorrow; @Value(&34;) private boolean testOnReturn; @Value(&34;) private boolean poolPreparedStatements; @Value(&34;) private int maxPoolPreparedStatementPerConnectionSize; @Value(&34;) private String filters; @Value(&34;) private String connectionProperties; @Bean(name = &34;) @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 = &34;) @Primary public DataSourceTransactionManager masterTransactionManager() { return new DataSourceTransactionManager(masterDataSource()); } @Bean(name = &34;) @Primary public SqlSessionFactory masterSqlSessionFactory(@Qualifier(&34;) DataSource masterDataSource) throws Exception { final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(); sessionFactory.setDataSource(masterDataSource); sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver() .getResources(MasterDataSourceConfig.MAPPER_LOCATION)); return sessionFactory.getObject(); }}
其中這兩個註解說明下:
需要注意的是sqlSessionFactoryRef 表示定義一個唯一 SqlSessionFactory 實例。
上面的配置完之後,就可以將Druid作為連接池使用了。但是Druid並不簡簡單單的是個連接池,它也可以說是一個監控應用,它自帶了web監控界面,可以很清晰的看到SQL相關信息。在SpringBoot中運用Druid的監控作用,只需要編寫StatViewServlet和WebStatFilter類,實現註冊服務和過濾規則。這裡我們可以將這兩個寫在一起,使用@Configuration和@Bean。為了方便理解,相關的配置說明也寫在代碼中了,這裡就不再過多贅述了。代碼如下:
@Configurationpublic class DruidConfiguration { @Bean public ServletRegistrationBean druidStatViewServle() { //註冊服務 ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean( new StatViewServlet(), &34;); // 白名單(為空表示,所有的都可以訪問,多個IP的時候用逗號隔開) servletRegistrationBean.addInitParameter(&34;, &34;); // IP黑名單 (存在共同時,deny優先於allow) servletRegistrationBean.addInitParameter(&34;, &34;); // 設置登錄的用戶名和密碼 servletRegistrationBean.addInitParameter(&34;, &34;); servletRegistrationBean.addInitParameter(&34;, &34;); // 是否能夠重置數據. servletRegistrationBean.addInitParameter(&34;, &34;); return servletRegistrationBean; } @Bean public FilterRegistrationBean druidStatFilter() { FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean( new WebStatFilter()); // 添加過濾規則 filterRegistrationBean.addUrlPatterns(&34;); // 添加不需要忽略的格式信息 filterRegistrationBean.addInitParameter(&34;, &34;); System.out.println(&34;); return filterRegistrationBean; }}
編寫完之後,啟動程序,在瀏覽器輸入:http://127.0.0.1:8084/druid/index.html ,然後輸入設置的用戶名和密碼,便可以訪問Web界面了。
在進行多數據源配置之前,先分別在springBoot和springBoot_test的mysql資料庫中執行如下腳本。
-- springBoot庫的腳本CREATE TABLE `t_user` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT &39;, `name` varchar(10) DEFAULT NULL COMMENT &39;, `age` int(2) DEFAULT NULL COMMENT &39;, 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
注:為了偷懶,將兩張表的結構弄成一樣了!不過不影響測試!
在application.properties中已經配置這兩個數據源的信息,上面已經貼出了一次配置,這裡就不再貼了。這裡重點說下 第二個數據源的配置。和上面的MasterDataSourceConfig.java差不多,區別在與沒有使用**@Primary** 註解和名稱不同而已。需要注意的是MasterDataSourceConfig.java對package和mapper的掃描是精確到目錄的,這裡的第二個數據源也是如此。那麼代碼如下:
@Configuration@MapperScan(basePackages = ClusterDataSourceConfig.PACKAGE, sqlSessionFactoryRef = &34;)public class ClusterDataSourceConfig { static final String PACKAGE = &34;; static final String MAPPER_LOCATION = &34;; @Value(&34;) private String url; @Value(&34;) private String username; @Value(&34;) private String password; @Value(&34;) private String driverClass; // 和MasterDataSourceConfig一樣,這裡略 @Bean(name = &34;) public DataSource clusterDataSource() { DruidDataSource dataSource = new DruidDataSource(); dataSource.setUrl(url); dataSource.setUsername(username); dataSource.setPassword(password); dataSource.setDriverClassName(driverClass); // 和MasterDataSourceConfig一樣,這裡略 ... return dataSource; } @Bean(name = &34;) public DataSourceTransactionManager clusterTransactionManager() { return new DataSourceTransactionManager(clusterDataSource()); } @Bean(name = &34;) public SqlSessionFactory clusterSqlSessionFactory(@Qualifier(&34;) DataSource clusterDataSource) throws Exception { final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(); sessionFactory.setDataSource(clusterDataSource); sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(ClusterDataSourceConfig.MAPPER_LOCATION)); return sessionFactory.getObject(); }}
成功寫完配置之後,啟動程序,進行測試。分別在springBoot和springBoot_test庫中使用接口進行添加數據。
t_user
POST http://localhost:8084/api/user{&34;:&34;,&34;:25}{&34;:&34;,&34;:25}{&34;:&34;,&34;:25}
t_student
POST http://localhost:8084/api/student{&34;:&34;,&34;:16}{&34;:&34;,&34;:17}{&34;:&34;,&34;:18}
成功添加數據之後,然後進行調用不同的接口進行查詢。
請求:
GET http://localhost:8084/api/user?name=李四
返回:
{ &34;: 2, &34;: &34;, &34;: 25}
請求:
GET http://localhost:8084/api/student?name=學生C
返回:
{ &34;: 1, &34;: &34;, &34;: 16}
通過數據可以看出,成功配置了多數據源了。
PageHelper是Mybatis的一個分頁插件,非常的好用!這裡強烈推薦!!!
PageHelper的使用很簡單,只需要在Maven中添加pagehelper這個依賴就可以了。Maven的依賴如下:
<dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.2.3</version> </dependency>
註:這裡我是用springBoot版的!也可以使用其它版本的。
添加依賴之後,只需要添加如下配置或代碼就可以了。第一種,在application.properties或application.yml添加
pagehelper: helperDialect: mysql offsetAsPageNum: true rowBoundsWithCount: true reasonable: false
第二種,在mybatis.xml配置中添加
<bean id=&34; class=&34;> <property name=&34; ref=&34; /> <!-- 掃描mapping.xml文件 --> <property name=&34; value=&34;></property> <!-- 配置分頁插件 --> <property name=&34;> <array> <bean class=&34;> <property name=&34;> <value> helperDialect=mysql offsetAsPageNum=true rowBoundsWithCount=true reasonable=false </value> </property> </bean> </array> </property> </bean>
第三種,在代碼中添加,使用@Bean註解在啟動程序的時候初始化。
@Bean public PageHelper pageHelper(){ PageHelper pageHelper = new PageHelper(); Properties properties = new Properties(); //資料庫 properties.setProperty(&34;, &34;); //是否將參數offset作為PageNum使用 properties.setProperty(&34;, &34;); //是否進行count查詢 properties.setProperty(&34;, &34;); //是否分頁合理化 properties.setProperty(&34;, &34;); pageHelper.setProperties(properties); }
因為這裡我們使用的是多數據源,所以這裡的配置稍微有些不同。我們需要在sessionFactory這裡配置。這裡就對MasterDataSourceConfig.java進行相應的修改。在masterSqlSessionFactory方法中,添加如下代碼。
@Bean(name = &34;) @Primary public SqlSessionFactory masterSqlSessionFactory(@Qualifier(&34;) DataSource masterDataSource) throws Exception { final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(); sessionFactory.setDataSource(masterDataSource); sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver() .getResources(MasterDataSourceConfig.MAPPER_LOCATION)); //分頁插件 Interceptor interceptor = new PageInterceptor(); Properties properties = new Properties(); //資料庫 properties.setProperty(&34;, &34;); //是否將參數offset作為PageNum使用 properties.setProperty(&34;, &34;); //是否進行count查詢 properties.setProperty(&34;, &34;); //是否分頁合理化 properties.setProperty(&34;, &34;); interceptor.setProperties(properties); sessionFactory.setPlugins(new Interceptor[] {interceptor}); return sessionFactory.getObject(); }
註:其它的數據源也想進行分頁的時候,參照上面的代碼即可。
這裡需要注意的是reasonable參數,表示分頁合理化,默認值為false。如果該參數設置為 true 時,pageNum<=0 時會查詢第一頁,pageNum>pages(超過總數時),會查詢最後一頁。默認false 時,直接根據參數進行查詢。
設置完PageHelper 之後,使用的話,只需要在查詢的sql前面添加PageHelper.startPage(pageNum,pageSize);,如果是想知道總數的話,在查詢的sql語句後買呢添加 page.getTotal() 就可以了。代碼示例:
public List<T> findByListEntity(T entity) { List<T> list = null; try { Page<?> page =PageHelper.startPage(1,2); System.out.println(getClassName(entity)+&34;); list = getMapper().findByListEntity(entity); System.out.println(&34;+page.getTotal()+&34;+list.size()+&34;); } catch (Exception e) { logger.error(&34;+getClassName(entity)+&34;,e); } return list; }
代碼編寫完畢之後,開始進行最後的測試。
查詢t_user表的所有的數據,並進行分頁。
請求:
GET http://localhost:8084/api/user
返回:
[ { &34;: 1, &34;: &34;, &34;: 25 }, { &34;: 2, &34;: &34;, &34;: 25 }]
控制臺列印:
開始查詢...User設置第一頁兩條數據!2018-04-27 19:55:50.769 DEBUG 6152 --- [io-8084-exec-10] c.p.d.m.UserDao.findByListEntity_COUNT : ==> Preparing: SELECT count(0) FROM t_user WHERE 1 = 1 2018-04-27 19:55:50.770 DEBUG 6152 --- [io-8084-exec-10] c.p.d.m.UserDao.findByListEntity_COUNT : ==> Parameters: 2018-04-27 19:55:50.771 DEBUG 6152 --- [io-8084-exec-10] c.p.d.m.UserDao.findByListEntity_COUNT : <== Total: 12018-04-27 19:55:50.772 DEBUG 6152 --- [io-8084-exec-10] c.p.dao.master.UserDao.findByListEntity : ==> Preparing: select id, name, age from t_user where 1=1 LIMIT ? 2018-04-27 19:55:50.773 DEBUG 6152 --- [io-8084-exec-10] c.p.dao.master.UserDao.findByListEntity : ==> Parameters: 2(Integer)2018-04-27 19:55:50.774 DEBUG 6152 --- [io-8084-exec-10] c.p.dao.master.UserDao.findByListEntity : <== Total: 2總共有:3條數據,實際返回:2兩條數據!
查詢t_student表的所有的數據,並進行分頁。
請求:
GET http://localhost:8084/api/student
返回:
[ { &34;: 1, &34;: &34;, &34;: 16 }, { &34;: 2, &34;: &34;, &34;: 17 }]
控制臺列印:
開始查詢...Studnet設置第一頁兩條數據!2018-04-27 19:54:56.155 DEBUG 6152 --- [nio-8084-exec-8] c.p.d.c.S.findByListEntity_COUNT : ==> Preparing: SELECT count(0) FROM t_student WHERE 1 = 1 2018-04-27 19:54:56.155 DEBUG 6152 --- [nio-8084-exec-8] c.p.d.c.S.findByListEntity_COUNT : ==> Parameters: 2018-04-27 19:54:56.156 DEBUG 6152 --- [nio-8084-exec-8] c.p.d.c.S.findByListEntity_COUNT : <== Total: 12018-04-27 19:54:56.157 DEBUG 6152 --- [nio-8084-exec-8] c.p.d.c.StudentDao.findByListEntity : ==> Preparing: select id, name, age from t_student where 1=1 LIMIT ? 2018-04-27 19:54:56.157 DEBUG 6152 --- [nio-8084-exec-8] c.p.d.c.StudentDao.findByListEntity : ==> Parameters: 2(Integer)2018-04-27 19:54:56.157 DEBUG 6152 --- [nio-8084-exec-8] c.p.d.c.StudentDao.findByListEntity : <== Total: 2總共有:3條數據,實際返回:2兩條數據!
查詢完畢之後,我們再來看Druid 的監控界面。在瀏覽器輸入:http://127.0.0.1:8084/druid/index.html
可以很清晰的看到操作記錄! 如果想知道更多的Druid相關知識,可以查看官方文檔!
這篇終於寫完了,在進行代碼編寫的時候,碰到過很多問題,然後慢慢的嘗試和找資料解決了。本篇文章只是很淺的介紹了這些相關的使用,在實際的應用可能會更複雜。如果有有更好的想法和建議,歡迎留言進行討論!
參考文章:https://www.bysocket.com/?p=1712
Durid官方地址:https://github.com/alibaba/druid
PageHelper官方地址:https://github.com/pagehelper/Mybatis-PageHelper
項目我放到github上面去了: https://github.com/xuwujing/springBoot
作者 | 虛無境的博客
來源 | http://8rr.co/N8gV