首页 > 其他分享 >流式查询2、mybatis的ResultHandler 每次查询返回定义的500条

流式查询2、mybatis的ResultHandler 每次查询返回定义的500条

时间:2024-07-19 11:19:14浏览次数:14  
标签:String cdc ResultHandler aswatson redis 查询 mybatis import com

流式查询2、mybatis通过用ResultHandler 流式查询,每次查询返回定义的500条,再去批量处理(可异步并发):

package com.aswatson.cdc.redis.schedule;

import com.aswatson.cdc.redis.common.lock.DistLock;
import com.aswatson.cdc.redis.common.lock.DistLockRegistry;
import com.aswatson.cdc.redis.conf.Constant;
import com.aswatson.cdc.redis.domain.repository.RedisTaskLogRepository;
import com.aswatson.cdc.redis.domain.repository.StaffProfileRepository;
import com.aswatson.cdc.redis.infrastructure.dao.redisDao.mapper.RedisLogMapper;
import com.aswatson.cdc.redis.infrastructure.dao.redisDao.model.RedisLogPO;
import com.aswatson.cdc.redis.utils.LocalCache;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.ResultContext;
import org.apache.ibatis.session.ResultHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class StaffProfileRefreshCache {

    public static String tableName = "STAFF_PROFILE";
    @Value("${buId}")
    private String buId;
    @Value("${staffProfile.cacheCount}")
    private Long staffProfileCashCount;
    @Autowired
    private DistLockRegistry distLockRegistry;
    @Autowired
    private RedisLogMapper redisLogMapper;
    @Autowired
    private RedisTaskLogRepository redisTaskLogRepository;
    @Autowired
    private StaffProfileRepository staffProfileRepository;

    public void refreshStaffProfile(String lockId, String count) throws Exception {
        log.info("refreshStaffProfile log: {}, {}, {}", lockId, LocalDate.now(), count);
        LocalDateTime startTime = LocalDateTime.now();
        DistLock lock = distLockRegistry.getLock(lockId);
        if(!lock.tryLock()) {
            upsertRedisLockLog(lockId);
            return;
        }
        Optional.ofNullable(count).ifPresent(x -> staffProfileCashCount = Long.valueOf(count));
        final int BATCH_SIZE = 1000;
        List<RedisLogPO> redisLogPOs = new ArrayList<>();

        redisLogMapper.selectLargeDataByTableNameAndCount(buId, tableName, staffProfileCashCount,
            new ResultHandler<RedisLogPO>() {
                private int size;

                @Override public void handleResult(ResultContext<? extends RedisLogPO> resultContext) {
                    redisLogPOs.add(resultContext.getResultObject());
                    size++;
                    if (size == BATCH_SIZE) {
                        staffProfileRefreshByKey(redisLogPOs);
                        size = 0;
                    }
                }
            });

        Optional.of(redisLogPOs)
            .filter(list -> !list.isEmpty())
            .ifPresent(this::staffProfileRefreshByKey);

        redisTaskLogRepository.saveRedisTaskLog(lockId, startTime, InetAddress.getLocalHost().getHostAddress());
    }

    public void staffProfileRefreshByKey(List<RedisLogPO> redisLogPOs) {
        try {
            redisLogPOs.parallelStream().forEach(redisLog -> {
                String key = LocalCache.filterRedisKey(redisLog.getRedisName());
                if (StringUtils.isNotBlank(key)) {
                    staffProfileRepository.refreshStaffProfileByKey(key.substring(25));
                }
            });
        } catch (Exception e) {
            log.error("e", e);
            throw new RuntimeException(e);
        } finally {
            redisLogPOs.clear();
        }
    }

    private void upsertRedisLockLog(String lockId) throws UnknownHostException {
        String serverIp = InetAddress.getLocalHost().getHostAddress();
        LocalDateTime startTime = LocalDateTime.now();
        redisTaskLogRepository.saveRedisTaskLogByLock(lockId, startTime, serverIp, Constant.LOCK_EXIST);
    }

}
void selectLargeDataByTableNameAndCount(@Param("buId")String buId, @Param("tableName")String tableName,
        @Param("cacheCount")Long cacheCount,
        ResultHandler<RedisLogPO> handler);
        
<select id="selectLargeDataByTableNameAndCount" resultType="com.aswatson.cdc.redis.infrastructure.dao.redisDao.model.RedisLogPO" resultSetType="FORWARD_ONLY" fetchSize = "500">
     SELECT * from REDIS_ACCESS_LOG where table_name  = #{tableName} and NAME_SPACE = #{buId} ORDER BY COUNT DESC LIMIT ${cacheCount}
</select>

标签:String,cdc,ResultHandler,aswatson,redis,查询,mybatis,import,com
From: https://www.cnblogs.com/lgg20/p/18311132

相关文章

  • springboot~mybatis-pagehelper原理与使用
    原理PageHelper是一个用于MyBatis的分页插件,pagehelper-spring-boot-starter是其在SpringBoot中的集成组件。下面简要介绍PageHelper的分页原理:PageHelper的分页原理拦截器机制:PageHelper通过MyBatis的拦截器机制实现分页功能。它会在SQL执行前拦截并修改SQL语句,添加分页相......
  • SQL Server 使用 OPTION (RECOMPILE) 和查询存储的查询
    设置        我们正在使用WideWorldImporters数据库,您可以从Github下载【sql-server-samples/samples/databases/wide-world-importersatmaster·microsoft/sql-server-samples·GitHub】。我正在运行SQLServer2017的最新CU【https://sqlserverbuilds.......
  • 论如何直接用EF Core实现创建更新时间、用户审计,自动化乐观并发、软删除和树形查询(中)
    前言数据库并发,数据审计和软删除一直是数据持久化方面的经典问题。早些时候,这些工作需要手写复杂的SQL或者通过存储过程和触发器实现。手写复杂SQL对软件可维护性构成了相当大的挑战,随着SQL字数的变多,用到的嵌套和复杂语法增加,可读性和可维护性的难度是几何级暴涨。因此如何在实......
  • OLAP中的反范式设计:优化查询效率与数据更新
    在OLAP(联机分析处理)系统中,通常需要处理大量的数据,并进行复杂的查询和分析操作。为了提高查询效率,常采用反范式设计,并进行定时的大批量数据插入更新。本文将探讨OLAP中的反范式设计的优势,以及定时大批量数据插入对系统性能的影响。一、反范式设计优化查询效率在OLAP系统中,查询......
  • springboot+vue+mybatis销售评价系统+PPT+论文+讲解+售后
    随着科学技术的飞速发展,社会的方方面面、各行各业都在努力与现代的先进技术接轨,通过科技手段来提高自身的优势,销售评价系统当然也不能排除在外。销售评价系统是以实际运用为开发背景,运用软件工程开发方法,采用Java技术构建的一个管理系统。整个开发过程首先对软件系统进行需求分......
  • SQL 分页查询employees表,每5行一页,返回第2页的数据
    系列文章目录文章目录系列文章目录前言前言前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到网站,这篇文章男女通用,看懂了就去分享给你的码吧。描述分页查询employees表,每5行一页,返回第2页的数据CREATETABLEemploy......
  • 数据库的查询语言
    目录文章目录前言一、sql查询语言关键字二、基础查询1.查询学生表中学号是101的学生信息2.限定条件ISNOTNULL(不为空)ISNULL(为空)IN(集合)LIKE(模糊查询)关键词DISTINCT用于返回唯一不同的值(去重复)三、排序查询查找所有学生并按照成绩升序排序查找所有男学生......
  • vue+element-ui根据时间查询
    查询头<el-form-itemlabel="检验时间:"prop="date"><el-date-pickerv-model="queryParams.date"type="date"placeholder="请选择"clearable......
  • SSM 整合(Spring + MyBatis;Spring + Spring MVC)
    1.SSM整合(Spring+MyBatis;Spring+SpringMVC)文章目录1.SSM整合(Spring+MyBatis;Spring+SpringMVC)2.引入相关依赖3.SSM整合3.1创建包结构4.Spring整合+MyBatis4.1编写jdbc.properties4.2编写DataSourceConfig数据源配置4.3编写MyBatisConf......
  • SpringBoot整合MyBatis+MySQL
    一、添加mysql驱动mysqlmysql-connector-java二、添加MyBatis依赖org.mybatis.spring.bootmybatis-spring-boot-starter3.0.1三、添加配置spring:datasource:name:xx-datasourcedriverClassName:com.mysql.cj.jdbc.Driverurl:jdbc:mysql://127.0.0.1:3306/xx-......