簡介
又到了吹水時間,是這樣的,今天開發時想將自己寫好的代碼拿來優化,因為不想在開發服弄,怕搞壞了到時候GIT到生產服一大堆問題,然后把它分離到我輪子(工具)項目上,最后運行后發現我獲取List的時候很卡至少10秒,我驚了平時也就我的正常版本是800ms左右(不要看它很久,因為數據量很大,也很正常。),前提是我也知道很慢,就等的確需要優化時,我在放出我優化的plus版本,回到10秒哪里,最開始我剛剛接到這個app項目時,在我用 PageHelper.startPage(page, num);(分頁),還沒等查到的數據封裝(PageInfo)就已經分好頁了,現在換到輪子上就發現了這個問題,它沒有幫我將limit拼接到sql后面,導致我獲取全部,再PageInfo分頁,數據量龐大導致很卡,最后…
10秒:
正常的:
springboot整合mybatis分頁攔截器
分頁攔截實際上就是獲取sql后將sql拼接limit
pom.xml
<!-- 引入分頁插件 --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.2.0</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.21</version> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> </dependency>
yml
spring: application: name: spring-cloud-dynamic datasource: #類型 type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/f2f?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai username: root password: initial-size: 2 max-idle: 10 min-idle: 1 max-wait: 60000 max-active: 20 #最大空閑連接數 #多久進行一次檢測,檢測需要關閉的空閑連接 time-between-eviction-tuns-millis: 60000
MybatisConfig
/** * @author lanys * @Description: * @date 23/7/2021 下午8:38 */ @Configuration @EnableTransactionManagement @PropertySource(value = "classpath:application.yml", ignoreResourceNotFound = true) public class MybatisConfig implements TransactionManagementConfigurer { @Value("${mybatis.mapper-locations}") private String mapper; @Value("${mybatis.type-aliases-package}") private String aliases; @Autowired private DataSource dataSource; @Bean(name = "sqlSessionFactory") public SqlSessionFactory sqlSessionFactory() throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); // 設置數據源 bean.setDataSource(dataSource); // 設置xml bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapper)); // 設置別名 bean.setTypeAliasesPackage(aliases); // 添加分頁插件 bean.setPlugins(new Interceptor[]{pageInterceptor()}); bean.getObject().getConfiguration().setMapUnderscoreToCamelCase(true); return bean.getObject(); } /** * 分頁攔截器 * @return */ private PageInterceptor pageInterceptor() { PageInterceptor pageInterceptor = new PageInterceptor(); // 詳見 com.github.pagehelper.page.PageParams Properties p = new Properties(); // RowBounds是否進行count查詢 - 默認不查詢 p.setProperty("rowBoundsWithCount", "true"); // 當設置為true的時候,如果page size設置為0(或RowBounds的limit=0),就不執行分頁,返回全部結果 p.setProperty("pageSizeZero", "true"); // 分頁合理化 p.setProperty("reasonable", "false"); // 是否支持接口參數來傳遞分頁參數,默認false p.setProperty("supportMethodsArguments", "true"); // 設置數據庫方言 , 也可以不設置,會動態獲取 p.setProperty("helperDialect", "mysql"); pageInterceptor.setProperties(p); return pageInterceptor; } @Override public PlatformTransactionManager annotationDrivenTransactionManager() { return new DataSourceTransactionManager(dataSource); } }
測試
自己的其中代碼
/** * 關注列表 * @param userId * @param page * @param size * @return */ @Override public List<DynamicInfo> focusList(Long userId, Integer page, Integer size) { PageHelper.startPage(page, size); List<DynamicInfo> listByUserId = new ArrayList<>(); try { //獲取自己關注列表 listByUserId = this.dynamicReleaseMapper.getListFocusId(userId); if (listByUserId == null || listByUserId.size() == 0){ return listByUserId; } //List<DynamicInfo> listByUserId = this.dynamicReleaseMapper.getListFocusId(userId).stream().filter(x->(x.getIsPicture()!=2 && x.getIsVideo() !=2)||(x.getIsPicture()==2 && x.getIsVideo() !=2)||(x.getIsPicture()!=2 && x.getIsVideo() ==2)).collect(Collectors.toList()); publicGetDynamicInfo(userId,listByUserId); //} log.info("-------獲取關注列表-------"); return listByUserId; } catch (Exception e) { log.error("獲取關注列表異常",e); } return listByUserId; }
想分頁要加 PageHelper.startPage(page, size);,否則會默認不分頁,也可以自己加limit.
結果(sql語句很長截取一部分):
GROUP BY id ORDER BY create_time desc LIMIT ?
總結
這代碼是最后發現不對后,問公司大佬才懂,瞬間學到了,可能有人會問,這有什么好處嗎?
優點(自己的想法):
1. 直接在數據庫過濾,少了很多處理。為什么?因為如果你先查出全部在進行封裝分頁,看不出什么問題。但是如果你直接獲取后,還要其他處理,比如一個動態,你要獲取最新的動態,動態需要圖片,視頻,標簽,地址等,這一系列獲取,如果獲取到的動態很少還好,如果很多,那個速度自己都覺得可怕(慢)。
2. 運行速度快很多,在開發中,盡量減少訪問數據庫來獲取數據。
3. 省事,有些是在sql后面自己加limit,但是sql語句很多時,也很繁瑣
缺點:
看個人需求,看合不合適
到此這篇關于springboot整合mybatis攔截器分頁的文章就介紹到這了,更多相關springboot整合mybatis分頁內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://blog.csdn.net/qq_44697754/article/details/119045075