1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > SpringBoot+Mybatis+ Druid+PageHelper 实现多数据源并分页

SpringBoot+Mybatis+ Druid+PageHelper 实现多数据源并分页

时间:2023-10-25 08:00:29

相关推荐

SpringBoot+Mybatis+ Druid+PageHelper 实现多数据源并分页

点击上方“方志朋”,选择“设为星标”

回复”666“获取新整理的面试资料

作者:虚无境

/xuwujing/p/8964927.html

前言

本篇文章主要讲述的是SpringBoot整合Mybatis、Druid和PageHelper 并实现多数据源和分页。其中SpringBoot整合Mybatis这块,在之前的的一篇文章中已经讲述了,这里就不过多说明了。重点是讲述在多数据源下的如何配置使用Druid和PageHelper 。

/xuwujing/p/8260935.html

Druid介绍和使用

在使用Druid之前,先来简单的了解下Druid。

Druid是一个数据库连接池。Druid可以说是目前最好的数据库连接池!因其优秀的功能、性能和扩展性方面,深受开发人员的青睐。

Druid已经在阿里巴巴部署了超过600个应用,经过一年多生产环境大规模部署的严苛考验。Druid是阿里巴巴开发的号称为监控而生的数据库连接池!

同时Druid不仅仅是一个数据库连接池,Druid 核心主要包括三部分:

基于Filter-Chain模式的插件体系。

DruidDataSource 高效可管理的数据库连接池。

SQLParser

Druid的主要功能如下:

是一个高效、功能强大、可扩展性好的数据库连接池。

可以监控数据库访问性能。

数据库密码加密

获得SQL执行日志

扩展JDBC

介绍方面这块就不再多说,具体的可以看官方文档。那么开始介绍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=5spring.datasource.minIdle=5spring.datasource.maxActive=20#配置获取连接等待超时的时间spring.datasource.maxWait=60000#配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒spring.datasource.timeBetweenEvictionRunsMillis=60000#配置一个连接在池中最小生存的时间,单位是毫秒spring.datasource.minEvictableIdleTimeMillis=300000spring.datasource.validationQuery=SELECT1FROMDUALspring.datasource.testWhileIdle=truespring.datasource.testOnBorrow=falsespring.datasource.testOnReturn=false#打开PSCache,并且指定每个连接上PSCache的大小spring.datasource.poolPreparedStatements=truespring.datasource.maxPoolPreparedStatementPerConnectionSize=20#配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙spring.datasource.filters=stat,wall,log4j#通过connectProperties属性来打开mergeSql功能;慢SQL记录spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000

成功添加了配置文件之后,我们再来编写Druid相关的类。

首先是MasterDataSourceConfig.java这个类,这个是默认的数据源配置类。

@Configuration@MapperScan(basePackages=MasterDataSourceConfig.PACKAGE,sqlSessionFactoryRef="masterSqlSessionFactory")publicclassMasterDataSourceConfig{staticfinalStringPACKAGE="com.pancm.dao.master";staticfinalStringMAPPER_LOCATION="classpath:mapper/master/*.xml";@Value("${master.datasource.url}")privateStringurl;@Value("${master.datasource.username}")privateStringusername;@Value("${master.datasource.password}")privateStringpassword;@Value("${master.datasource.driverClassName}")privateStringdriverClassName;@Value("${spring.datasource.initialSize}")privateintinitialSize;@Value("${spring.datasource.minIdle}")privateintminIdle;@Value("${spring.datasource.maxActive}")privateintmaxActive;@Value("${spring.datasource.maxWait}")privateintmaxWait;@Value("${spring.datasource.timeBetweenEvictionRunsMillis}")privateinttimeBetweenEvictionRunsMillis;@Value("${spring.datasource.minEvictableIdleTimeMillis}")privateintminEvictableIdleTimeMillis;@Value("${spring.datasource.validationQuery}")privateStringvalidationQuery;@Value("${spring.datasource.testWhileIdle}")privatebooleantestWhileIdle;@Value("${spring.datasource.testOnBorrow}")privatebooleantestOnBorrow;@Value("${spring.datasource.testOnReturn}")privatebooleantestOnReturn;@Value("${spring.datasource.poolPreparedStatements}")privatebooleanpoolPreparedStatements;@Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")privateintmaxPoolPreparedStatementPerConnectionSize;@Value("${spring.datasource.filters}")privateStringfilters;@Value("{spring.datasource.connectionProperties}")privateStringconnectionProperties;@Bean(name="masterDataSource")@PrimarypublicDataSourcemasterDataSource(){DruidDataSourcedataSource=newDruidDataSource();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(SQLExceptione){e.printStackTrace();}dataSource.setConnectionProperties(connectionProperties);returndataSource;}@Bean(name="masterTransactionManager")@PrimarypublicDataSourceTransactionManagermasterTransactionManager(){returnnewDataSourceTransactionManager(masterDataSource());}@Bean(name="masterSqlSessionFactory")@PrimarypublicSqlSessionFactorymasterSqlSessionFactory(@Qualifier("masterDataSource")DataSourcemasterDataSource)throwsException{finalSqlSessionFactoryBeansessionFactory=newSqlSessionFactoryBean();sessionFactory.setDataSource(masterDataSource);sessionFactory.setMapperLocations(newPathMatchingResourcePatternResolver().getResources(MasterDataSourceConfig.MAPPER_LOCATION));returnsessionFactory.getObject();}}

其中这两个注解说明下:

@Primary :标志这个Bean如果在多个同类Bean候选时,该Bean

优先被考虑。多数据源配置的时候注意,必须要有一个主数据源,用@Primary 标志该 Bean。

@MapperScan:扫描 Mapper 接口并容器管理。

需要注意的是sqlSessionFactoryRef 表示定义一个唯一 SqlSessionFactory 实例。

上面的配置完之后,就可以将Druid作为连接池使用了。但是Druid并不简简单单的是个连接池,它也可以说是一个监控应用,它自带了web监控界面,可以很清晰的看到SQL相关信息。

在SpringBoot中运用Druid的监控作用,只需要编写StatViewServlet和WebStatFilter类,实现注册服务和过滤规则。这里我们可以将这两个写在一起,使用@Configuration和@Bean。

为了方便理解,相关的配置说明也写在代码中了,这里就不再过多赘述了。

代码如下:

@ConfigurationpublicclassDruidConfiguration{@BeanpublicServletRegistrationBeandruidStatViewServle(){//注册服务ServletRegistrationBeanservletRegistrationBean=newServletRegistrationBean(newStatViewServlet(),"/druid/*");//白名单(为空表示,所有的都可以访问,多个IP的时候用逗号隔开)servletRegistrationBean.addInitParameter("allow","127.0.0.1");//IP黑名单(存在共同时,deny优先于allow)servletRegistrationBean.addInitParameter("deny","127.0.0.2");//设置登录的用户名和密码servletRegistrationBean.addInitParameter("loginUsername","pancm");servletRegistrationBean.addInitParameter("loginPassword","123456");//是否能够重置数据.servletRegistrationBean.addInitParameter("resetEnable","false");returnservletRegistrationBean;}@BeanpublicFilterRegistrationBeandruidStatFilter(){FilterRegistrationBeanfilterRegistrationBean=newFilterRegistrationBean(newWebStatFilter());//添加过滤规则filterRegistrationBean.addUrlPatterns("/*");//添加不需要忽略的格式信息filterRegistrationBean.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");System.out.println("druid初始化成功!");returnfilterRegistrationBean;}}

编写完之后,启动程序,在浏览器输入:http://127.0.0.1:8084/druid/index.html ,然后输入设置的用户名和密码,便可以访问Web界面了。

多数据源配置

在进行多数据源配置之前,先分别在springBoot和springBoot_test的mysql数据库中执行如下脚本。

--springBoot库的脚本CREATETABLE`t_user`(`id`int(11)NOTNULLAUTO_INCREMENTCOMMENT'自增id',`name`varchar(10)DEFAULTNULLCOMMENT'姓名',`age`int(2)DEFAULTNULLCOMMENT'年龄',PRIMARYKEY(`id`))ENGINE=InnoDBAUTO_INCREMENT=15DEFAULTCHARSET=utf8--springBoot_test库的脚本CREATETABLE`t_student`(`id`int(11)NOTNULLAUTO_INCREMENT,`name`varchar(16)DEFAULTNULL,`age`int(11)DEFAULTNULL,PRIMARYKEY(`id`))ENGINE=InnoDBAUTO_INCREMENT=2DEFAULTCHARSET=utf8

注:为了偷懒,将两张表的结构弄成一样了!不过不影响测试!

在application.properties中已经配置这两个数据源的信息,上面已经贴出了一次配置,这里就不再贴了。

这里重点说下第二个数据源的配置。和上面的MasterDataSourceConfig.java差不多,区别在与没有使用@Primary 注解和名称不同而已。需要注意的是MasterDataSourceConfig.java对package和mapper的扫描是精确到目录的,这里的第二个数据源也是如此。

那么代码如下:

@Configuration@MapperScan(basePackages=ClusterDataSourceConfig.PACKAGE,sqlSessionFactoryRef="clusterSqlSessionFactory")publicclassClusterDataSourceConfig{staticfinalStringPACKAGE="com.pancm.dao.cluster";staticfinalStringMAPPER_LOCATION="classpath:mapper/cluster/*.xml";@Value("${cluster.datasource.url}")privateStringurl;@Value("${cluster.datasource.username}")privateStringusername;@Value("${cluster.datasource.password}")privateStringpassword;@Value("${cluster.datasource.driverClassName}")privateStringdriverClass;//和MasterDataSourceConfig一样,这里略@Bean(name="clusterDataSource")publicDataSourceclusterDataSource(){DruidDataSourcedataSource=newDruidDataSource();dataSource.setUrl(url);dataSource.setUsername(username);dataSource.setPassword(password);dataSource.setDriverClassName(driverClass);//和MasterDataSourceConfig一样,这里略...returndataSource;}@Bean(name="clusterTransactionManager")publicDataSourceTransactionManagerclusterTransactionManager(){returnnewDataSourceTransactionManager(clusterDataSource());}@Bean(name="clusterSqlSessionFactory")publicSqlSessionFactoryclusterSqlSessionFactory(@Qualifier("clusterDataSource")DataSourceclusterDataSource)throwsException{finalSqlSessionFactoryBeansessionFactory=newSqlSessionFactoryBean();sessionFactory.setDataSource(clusterDataSource);sessionFactory.setMapperLocations(newPathMatchingResourcePatternResolver().getResources(ClusterDataSourceConfig.MAPPER_LOCATION));returnsessionFactory.getObject();}}

成功写完配置之后,启动程序,进行测试。

分别在springBoot和springBoot_test库中使用接口进行添加数据。

t_user

POSThttp://localhost:8084/api/user{"name":"张三","age":25}{"name":"李四","age":25}{"name":"王五","age":25}

t_student

POSThttp://localhost:8084/api/student{"name":"学生A","age":16}{"name":"学生B","age":17}{"name":"学生C","age":18}

成功添加数据之后,然后进行调用不同的接口进行查询。

请求:

GEThttp://localhost:8084/api/user?name=李四

返回:

{"id":2,"name":"李四","age":25}

请求:

GEThttp://localhost:8084/api/student?name=学生C

返回:

{"id":1,"name":"学生C","age":16}

通过数据可以看出,成功配置了多数据源了。

PageHelper 分页实现

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:mysqloffsetAsPageNum:truerowBoundsWithCount:truereasonable:false

第二种,在mybatis.xml配置中添加

<beanid="sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean"><propertyname="dataSource"ref="dataSource"/><!--扫描mapping.xml文件--><propertyname="mapperLocations"value="classpath:mapper/*.xml"></property><!--配置分页插件--><propertyname="plugins"><array><beanclass="com.github.pagehelper.PageHelper"><propertyname="properties"><value>helperDialect=mysqloffsetAsPageNum=truerowBoundsWithCount=truereasonable=false</value></property></bean></array></property></bean>

第三种,在代码中添加,使用@Bean注解在启动程序的时候初始化。

@BeanpublicPageHelperpageHelper(){PageHelperpageHelper=newPageHelper();Propertiesproperties=newProperties();//数据库properties.setProperty("helperDialect","mysql");//是否将参数offset作为PageNum使用properties.setProperty("offsetAsPageNum","true");//是否进行count查询properties.setProperty("rowBoundsWithCount","true");//是否分页合理化properties.setProperty("reasonable","false");pageHelper.setProperties(properties);}

因为这里我们使用的是多数据源,所以这里的配置稍微有些不同。我们需要在sessionFactory这里配置。这里就对MasterDataSourceConfig.java进行相应的修改。

在masterSqlSessionFactory方法中,添加如下代码。

@Bean(name="masterSqlSessionFactory")@PrimarypublicSqlSessionFactorymasterSqlSessionFactory(@Qualifier("masterDataSource")DataSourcemasterDataSource)throwsException{finalSqlSessionFactoryBeansessionFactory=newSqlSessionFactoryBean();sessionFactory.setDataSource(masterDataSource);sessionFactory.setMapperLocations(newPathMatchingResourcePatternResolver().getResources(MasterDataSourceConfig.MAPPER_LOCATION));//分页插件Interceptorinterceptor=newPageInterceptor();Propertiesproperties=newProperties();//数据库properties.setProperty("helperDialect","mysql");//是否将参数offset作为PageNum使用properties.setProperty("offsetAsPageNum","true");//是否进行count查询properties.setProperty("rowBoundsWithCount","true");//是否分页合理化properties.setProperty("reasonable","false");interceptor.setProperties(properties);sessionFactory.setPlugins(newInterceptor[]{interceptor});returnsessionFactory.getObject();}

注:其它的数据源也想进行分页的时候,参照上面的代码即可。

这里需要注意的是reasonable参数,表示分页合理化,默认值为false。如果该参数设置为 true 时,pageNum<=0时会查询第一页,pageNum>pages(超过总数时),会查询最后一页。默认false 时,直接根据参数进行查询。

设置完PageHelper 之后,使用的话,只需要在查询的sql前面添加PageHelper.startPage(pageNum,pageSize);,如果是想知道总数的话,在查询的sql语句后买呢添加 page.getTotal()就可以了。

代码示例:

publicList<T>findByListEntity(Tentity){List<T>list=null;try{Page<?>page=PageHelper.startPage(1,2);System.out.println(getClassName(entity)+"设置第一页两条数据!");list=getMapper().findByListEntity(entity);System.out.println("总共有:"+page.getTotal()+"条数据,实际返回:"+list.size()+"两条数据!");}catch(Exceptione){logger.error("查询"+getClassName(entity)+"失败!原因是:",e);}returnlist;}

代码编写完毕之后,开始进行最后的测试。

查询t_user表的所有的数据,并进行分页。

请求:

GEThttp://localhost:8084/api/user

返回:

[{"id":1,"name":"张三","age":25},{"id":2,"name":"李四","age":25}]

控制台打印:

开始查询...User设置第一页两条数据!-04-2719:55:50.769DEBUG6152---[io-8084-exec-10]c.p.d.m.UserDao.findByListEntity_COUNT:==>Preparing:SELECTcount(0)FROMt_userWHERE1=1-04-2719:55:50.770DEBUG6152---[io-8084-exec-10]c.p.d.m.UserDao.findByListEntity_COUNT:==>Parameters:-04-2719:55:50.771DEBUG6152---[io-8084-exec-10]c.p.d.m.UserDao.findByListEntity_COUNT:<==Total:1-04-2719:55:50.772DEBUG6152---[io-8084-exec-10]c.p.dao.master.UserDao.findByListEntity:==>Preparing:selectid,name,agefromt_userwhere1=1LIMIT?-04-2719:55:50.773DEBUG6152---[io-8084-exec-10]c.p.dao.master.UserDao.findByListEntity:==>Parameters:2(Integer)-04-2719:55:50.774DEBUG6152---[io-8084-exec-10]c.p.dao.master.UserDao.findByListEntity:<==Total:2总共有:3条数据,实际返回:2两条数据!

查询t_student表的所有的数据,并进行分页。

请求:

GEThttp://localhost:8084/api/student

返回:

[{"id":1,"name":"学生A","age":16},{"id":2,"name":"学生B","age":17}]

控制台打印:

开始查询...Studnet设置第一页两条数据!-04-2719:54:56.155DEBUG6152---[nio-8084-exec-8]c.p.d.c.S.findByListEntity_COUNT:==>Preparing:SELECTcount(0)FROMt_studentWHERE1=1-04-2719:54:56.155DEBUG6152---[nio-8084-exec-8]c.p.d.c.S.findByListEntity_COUNT:==>Parameters:-04-2719:54:56.156DEBUG6152---[nio-8084-exec-8]c.p.d.c.S.findByListEntity_COUNT:<==Total:1-04-2719:54:56.157DEBUG6152---[nio-8084-exec-8]c.p.d.c.StudentDao.findByListEntity:==>Preparing:selectid,name,agefromt_studentwhere1=1LIMIT?-04-2719:54:56.157DEBUG6152---[nio-8084-exec-8]c.p.d.c.StudentDao.findByListEntity:==>Parameters:2(Integer)-04-2719:54:56.157DEBUG6152---[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相关知识,可以查看官方文档!

结语

这篇终于写完了,在进行代码编写的时候,碰到过很多问题,然后慢慢的尝试和找资料解决了。本篇文章只是很浅的介绍了这些相关的使用,在实际的应用可能会更复杂。如果有有更好的想法和建议,欢迎留言进行讨论!

参考文章:

/?p=1712

Durid官方地址:

/alibaba/druid

PageHelper官方地址:

/pagehelper/Mybatis-PageHelper

文中源码:

/xuwujing/springBoot

热门内容:

17 个方面,综合对比 Kafka、RabbitMQ、RocketMQ、ActiveMQ 四个分布式消息队列

Mybatis的工作原理,你了解过吗?

图解 Java 垃圾回收机制,写得非常好!

一个员工的离职成本到底有多恐怖!

终于有人把 Docker 讲清楚了,万字详解!

Tomcat 和 JVM 的性能调优总结

Java 性能优化:教你提高代码运行的效率

感受lambda之美,推荐收藏,需要时查阅

最近面试BAT,整理一份面试资料《Java面试BAT通关手册》,覆盖了Java核心技术、JVM、Java并发、SSM、微服务、数据库、数据结构等等。

获取方式:点“在看”,关注公众号并回复666领取,更多内容陆续奉上。

明天见(。・ω・。)ノ♡

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。