记录 RedisTemplate.executePipelined 使用问题

本文对比了两种版本的Java代码,解决Redis大规模写入导致的内存溢出问题,并介绍了如何通过ArrayList优化get操作和分批处理提升性能,使得处理9000万个key在10分钟内完成。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

需求,向redis写入9000万个key
  • 第一个版本(关键代码)
@Slf4j
@Component("job2")
public class ToRedis2 implements IJob {

    private AtomicLong count = new AtomicLong(0);
    private Long oldCount=0L;
    private List<String> userIdList = new LinkedList<>();

    private ExecutorService es = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 4);

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Setter
    @Getter
    @Value("${user.limit:100000}")
    private volatile int userLimit;

    private Thread td;
    private Thread c;

    private AtomicBoolean stop=new AtomicBoolean(false);

    private void toRedis() throws IOException {
        String root = System.getProperty("user.dir") + "/2021";
        if (userIdList.isEmpty()) {
            // userId
            String filePath = root + "/user.csv";
            readFile(filePath, 0, userIdList);
            save();
        }
        String type[] = {"r1", "r2", "r3"};
        for (String t : type) {
            es.execute(()->{
                redisTemplate.executePipelined((RedisCallback<Object>) redisConnection -> {
                    // 超大数据集通过管道写入,容易引发内存溢出,内存溢出点主要是接收redis返回结果
                    // 组装数据并写入Redis
                    for (int i = 0; i < userIdList.size(); i++) {
                        if(stop.get()){
                            log.info("job2 stop");
                            break;
                        }
                        final int inx=i;
                        String charset = "UTF-8";
			// userIdList.get(inx)性能问题点
                        String key = "app:xxx:202105:userid_" + userIdList.get(inx) + ":" + t;
                        try {
                            redisConnection.set(key.getBytes(charset), String.valueOf(Math.abs(new Random().nextInt())).getBytes(charset));
                            count.incrementAndGet();
                        } catch (UnsupportedEncodingException e) {
                            log.error("编码失败", e);
                        }
                    }
                    return null;
                });
            });
        }
    }

}

  • 第二个版本(关键代码)

@Slf4j
@Component("job2")
public class ToRedis2 implements IJob {

    private AtomicLong count = new AtomicLong(0);
    private Long oldCount=0L;
    private List<String> userIdList = new ArrayList<>();

    private ExecutorService es = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 4);

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Setter
    @Getter
    @Value("${user.limit:100000}")
    private volatile int userLimit;
    @Setter
    @Getter
    @Value("${user.skip-count:0}")
    private volatile int skipCount;
    @Setter
    @Getter
    @Value("${user.batch-count:10000}")
    private volatile int batchCount;

    private AtomicBoolean stop=new AtomicBoolean(false);

    private void toRedis() throws IOException {
        String root =ystem.getProperty("user.dir") + "/2021";
        if (userIdList.isEmpty()) {
            // userId
            String filePath = root + "/user.txt";
            readFile(filePath, 0, userIdList);
//            save();
        }

        for (String t : type) {
            // 组装数据并写入Redis
            es.execute(()->{
                List<String> info = new LinkedList<>();
                exit:for (int i = 0; i < userIdList.size(); i++) {
                    if (i < skipCount) {
                        continue;
                    }
                    if (stop.get()) {
                        log.info("job2 stop");
                        break exit;
                    }
                    String key = "app:xxx:202105:userid_" + userIdList.get(i) + ":" + t;
                    info.add(key);
                    if (info.size() == getBatchCount() || i == userIdList.size() - 1) {
                        if (!stop.get()) {
                            executePipelined(info);
                            info.clear();
                        }
                    }
                }
            });
        }
    }

    private void executePipelined(List<String> info) {
        RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
        redisTemplate.executePipelined((RedisCallback<String>) connection -> {
            info.forEach((key) -> {
                if(!stop.get()){
                    long c=count.incrementAndGet();
                    connection.set(serializer.serialize(key), serializer.serialize(String.valueOf(c)));
                }
            });
            return null;
        }, serializer);
    }

}

两版对比
  • 第一个版本出现了内存溢出问题以及约运行处理越慢问题,9000万数据预计需要30多个小时
  • 第二个版本没有出现内存溢出,性能比第一个版本提高上百倍,9000万数据只用了10多分钟
问题分析
  • 第一个版本性能问题主要是采用了LinkedList 这个数据结构,这个数据结构的特性是曾、删快,但是读取是线性的,被get方法迷惑了,看了源码发现,这个get实际上进行的是遍历操作,虽然有优化,但是当数据了非常庞大时就会有性能问题
   // LinkedList get 方法源码
    /**
     * LinkedList 的get方法
     */
    public E get(int index) {
        checkElementIndex(index);
        return node(index).item;
    }

   /**
     * get 方法实际调用
     */
    Node<E> node(int index) {
        // assert isElementIndex(index);

        if (index < (size >> 1)) {
            Node<E> x = first;
            // 循环遍历,超大数据会有性能瓶颈
            for (int i = 0; i < index; i++)
                x = x.next;
            return x;
        } else {
            Node<E> x = last;
            // 循环遍历,超大数据会有性能瓶颈
            for (int i = size - 1; i > index; i--)
                x = x.prev;
            return x;
        }
    }

  • 第一个版本内存溢出问题分析,由于超大数据集循环在管道方法内,redis 在redis 处理完一批数据返回结果时会造成结果存不下而内存溢出
  • 第二个版本性能分析
    1、超大数据集改为ArrayList,在执行get的时候就不有循环查找问题,由于ArrayList 底层结构是数组,所以通过索引访问时是O(1)的速度,这个比LinkedList 的平局O(logn)要快很多
    2、分批处理数据,此处将数据分为10000条每批,这样不会造成由于接收redis返回结果而造成内存溢出问题

PS:关于内存溢出分析,只是从代码、原理角度分析,可能分析的不准确,仅做参考

package com.fkxinli.zxyy.common.core.utils; import cn.hutool.core.collection.CollUtil; import com.baomidou.mybatisplus.core.metadata.IPage; import com.fkxinli.zxyy.common.core.annotation.TranslateField; import com.fkxinli.zxyy.common.core.service.TranslateService; import jakarta.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisCallback; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.ValueOperations; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; import java.lang.reflect.Field; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; /** * 静态翻译工具类 * 功能:将对象字段值翻译为目标字段值,支持多种数据结构 * * @author 84595 */ @Component public class TranslateUtils { // Redis模板和翻译服务静态引用 private static RedisTemplate<String, Object> redisTemplate; private static TranslateService translateService; private static final String CACHE_PREFIX = "translate:"; private static final long CACHE_EXPIRE = 24 * 3600L; @Autowired private RedisTemplate<String, Object> staticRedisTemplate; @Autowired private TranslateService staticTranslateService; @PostConstruct public void init() { redisTemplate = this.staticRedisTemplate; translateService = this.staticTranslateService; } /** * 通过Spring自动注入初始化静态依赖 */ // static { // redisTemplate = SpringContextUtil.getBean("redisCacheTemplate"); // translateService = SpringContextUtil.getBean(TranslateService.class); // } /** * 翻译IPage对象 */ public static void translate(IPage<?> page, String... fieldPairs) { if (page != null) translate(page.getRecords(), fieldPairs); } /** * 翻译集合对象 */ public static void translate(Collection<?> targets, String... fieldPairs) { if (CollectionUtils.isEmpty(targets)) return; // 1. 收集需要翻译的键 Map<TranslateKey, TranslationTarget> translationMap = new HashMap<>(); targets.forEach(target -> collectKeys(target, fieldPairs, translationMap)); // 2. 批量查询缓存 Map<TranslateKey, Object> cachedValues = batchGetCache(translationMap.keySet()); // 3. 查询数据库获取缺失的翻译值 Set<TranslateKey> missingKeys = translationMap.keySet().stream() .filter(k -> !cachedValues.containsKey(k)) .collect(Collectors.toSet()); if (!missingKeys.isEmpty()) { Map<TranslateKey, Object> dbValues = batchQueryDB(missingKeys); cachedValues.putAll(dbValues); batchSetCache(dbValues); } // 4. 应用翻译结果到目标对象 applyTranslations(translationMap, cachedValues); } /** * 收集需要翻译的键 */ private static void collectKeys(Object obj, String[] fieldPairs, Map<TranslateKey, TranslationTarget> map) { if (obj instanceof Map) { processMap((Map<?, ?>) obj, fieldPairs, map); } else { processObject(obj, fieldPairs, map); } } /** * 处理Map类型对象的翻译键收集 */ private static void processMap(Map<?, ?> map, String[] fieldPairs, Map<TranslateKey, TranslationTarget> result) { map.forEach((k, v) -> { if (v != null && !isSimpleValue(v.getClass())) { collectKeys(v, fieldPairs, result); } else if (fieldPairs != null) { Arrays.stream(fieldPairs) .map(pair -> pair.split("\\|")) .filter(parts -> parts.length == 2) .forEach(parts -> { Object value = map.get(parts[0].trim()); if (value != null) { String type = parts[1].trim().toLowerCase(); String targetField = parts[0] + "Name"; result.put(new TranslateKey(value.toString(), type), new TranslationTarget(map, targetField)); } }); } }); } /** * 处理普通对象的翻译键收集 */ private static void processObject(Object obj, String[] fieldPairs, Map<TranslateKey, TranslationTarget> result) { // 处理注解字段 Arrays.stream(obj.getClass().getDeclaredFields()) .filter(f -> f.isAnnotationPresent(TranslateField.class)) .forEach(f -> { try { f.setAccessible(true); Object value = f.get(obj); if (value != null) { TranslateField anno = f.getAnnotation(TranslateField.class); String targetField = anno.targetField().isEmpty() ? f.getName() + "Name" : anno.targetField(); result.put(new TranslateKey(value.toString(), anno.type()), new TranslationTarget(obj, targetField)); } } catch (Exception e) { throw new RuntimeException(e); } }); // 处理参数指定字段 if (fieldPairs != null) { Arrays.stream(fieldPairs) .map(pair -> pair.split("\\|")) .filter(parts -> parts.length == 2) .forEach(parts -> { try { Field f = obj.getClass().getDeclaredField(parts[0].trim()); f.setAccessible(true); Object value = f.get(obj); if (value != null) { String type = parts[1].trim().toLowerCase(); String targetField = parts[0] + "Name"; result.put(new TranslateKey(value.toString(), type), new TranslationTarget(obj, targetField)); } } catch (Exception e) { throw new RuntimeException(e); } }); } } /** * 批量从缓存获取翻译值 */ private static Map<TranslateKey, Object> batchGetCache(Set<TranslateKey> keys) { if (CollectionUtils.isEmpty(keys)) { return Collections.emptyMap(); } // 构建缓存键列表 List<String> cacheKeys = keys.stream() .map(k -> String.format("%s%s:%s", CACHE_PREFIX, k.type(), k.value())) .collect(Collectors.toList()); // 批量获取缓存值 List<Object> cachedValues = redisTemplate.opsForValue().multiGet(cacheKeys); if (CollectionUtils.isEmpty(cachedValues)) { return Collections.emptyMap(); } // 构建结果映射 Map<TranslateKey, Object> result = new HashMap<>(keys.size()); Iterator<TranslateKey> keyIterator = keys.iterator(); Iterator<Object> valueIterator = cachedValues.iterator(); while (keyIterator.hasNext() && valueIterator.hasNext()) { TranslateKey key = keyIterator.next(); Object value = valueIterator.next(); if (value != null) { result.put(key, value); } } return result; } /** * 批量从数据库查询翻译值 */ private static Map<TranslateKey, Object> batchQueryDB(Set<TranslateKey> keys) { Map<TranslateKey, Object> result = new HashMap<>(); Map<String, List<String>> groupedKeys = keys.stream() .collect(Collectors.groupingBy( k -> k.type, Collectors.mapping(k -> k.value, Collectors.toList()) )); Map<String, Map<String, String>> stringMapMap = translateService.batchTranslate(groupedKeys); if (CollUtil.isNotEmpty(stringMapMap)) { stringMapMap.forEach((type, map) -> { map.forEach((id, name) -> { result.put(new TranslateKey(id, type), name); }); }); } // groupedKeys.forEach((type, ids) -> { // if ("person".equals(type)) { // translateService.batchGetUserNames(ids) // .forEach((id, name) -> // result.put(new TranslateKey(id, type), name)); // } else if ("org".equals(type)) { // translateService.batchGetOrgNames(ids) // .forEach((id, name) -> // result.put(new TranslateKey(id, type), name)); // } // }); return result; } /** * 批量设置缓存值(使用管道) */ private static void batchSetCache(Map<TranslateKey, Object> values) { redisTemplate.executePipelined((RedisCallback<?>) connection -> { ValueOperations<String, Object> ops = redisTemplate.opsForValue(); values.forEach((key, value) -> { String cacheKey = CACHE_PREFIX + key.type + ":" + key.value; // 使用RedisTemplate的set方法替代过时的connection.setEx ops.set(cacheKey, value, CACHE_EXPIRE, TimeUnit.SECONDS); }); return null; }); } /** * 应用翻译结果到目标对象 */ private static void applyTranslations(Map<TranslateKey, TranslationTarget> targets, Map<TranslateKey, Object> values) { targets.forEach((key, target) -> { Object translatedValue = values.get(key); if (translatedValue != null) { setFieldValue(target.target, target.fieldName, translatedValue); } }); } /** * 设置字段值 */ private static void setFieldValue(Object target, String fieldName, Object value) { try { if (target instanceof Map) { ((Map) target).put(fieldName, value); } else { Field field = target.getClass().getDeclaredField(fieldName); field.setAccessible(true); field.set(target, value); } } catch (Exception e) { throw new RuntimeException("Set field failed: " + fieldName, e); } } /** * 判断是否为简单值类型 */ private static boolean isSimpleValue(Class<?> clazz) { return clazz.isPrimitive() || CharSequence.class.isAssignableFrom(clazz) || Number.class.isAssignableFrom(clazz) || clazz == Boolean.class; } /** * 翻译键记录 */ private record TranslateKey(String value, String type) { } /** * 翻译目标记录 */ private record TranslationTarget(Object target, String fieldName) { } } springboot其他服务使用时,redis空指针
最新发布
07-24
package com.fkxinli.zxyy.common.core.utils; import cn.hutool.core.collection.CollUtil; import com.baomidou.mybatisplus.core.metadata.IPage; import com.fkxinli.zxyy.common.core.annotation.TranslateField; import com.fkxinli.zxyy.common.core.service.TranslateService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisCallback; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.ValueOperations; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; import java.lang.reflect.Field; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; /** * 静态翻译工具类 * 功能:将对象字段值翻译为目标字段值,支持多种数据结构 * * @author 84595 */ @Component public class TranslateUtils { // Redis模板和翻译服务静态引用 private static RedisTemplate<String, Object> redisTemplate; private static TranslateService translateService; private static final String CACHE_PREFIX = "translate:"; private static final long CACHE_EXPIRE = 24 * 3600L; /** * 通过Spring自动注入初始化静态依赖 */ @Autowired public void setDependencies(RedisTemplate<String, Object> redisTemplate, TranslateService translateService) { TranslateUtils.redisTemplate = redisTemplate; TranslateUtils.translateService = translateService; } // @Autowired // public void translateService(TranslateService translateService) { // TranslateUtils.translateService = translateService; // } // // @Autowired // public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) { // TranslateUtils.redisTemplate = redisTemplate; // } /** * 翻译IPage对象 */ public static void translate(IPage<?> page, String... fieldPairs) { if (page != null) translate(page.getRecords(), fieldPairs); } /** * 翻译集合对象 */ public static void translate(Collection<?> targets, String... fieldPairs) { if (CollectionUtils.isEmpty(targets)) return; // 1. 收集需要翻译的键 Map<TranslateKey, TranslationTarget> translationMap = new HashMap<>(); targets.forEach(target -> collectKeys(target, fieldPairs, translationMap)); // 2. 批量查询缓存 Map<TranslateKey, Object> cachedValues = batchGetCache(translationMap.keySet()); // 3. 查询数据库获取缺失的翻译值 Set<TranslateKey> missingKeys = translationMap.keySet().stream() .filter(k -> !cachedValues.containsKey(k)) .collect(Collectors.toSet()); if (!missingKeys.isEmpty()) { Map<TranslateKey, Object> dbValues = batchQueryDB(missingKeys); cachedValues.putAll(dbValues); batchSetCache(dbValues); } // 4. 应用翻译结果到目标对象 applyTranslations(translationMap, cachedValues); } /** * 收集需要翻译的键 */ private static void collectKeys(Object obj, String[] fieldPairs, Map<TranslateKey, TranslationTarget> map) { if (obj instanceof Map) { processMap((Map<?, ?>) obj, fieldPairs, map); } else { processObject(obj, fieldPairs, map); } } /** * 处理Map类型对象的翻译键收集 */ private static void processMap(Map<?, ?> map, String[] fieldPairs, Map<TranslateKey, TranslationTarget> result) { map.forEach((k, v) -> { if (v != null && !isSimpleValue(v.getClass())) { collectKeys(v, fieldPairs, result); } else if (fieldPairs != null) { Arrays.stream(fieldPairs) .map(pair -> pair.split("\\|")) .filter(parts -> parts.length == 2) .forEach(parts -> { Object value = map.get(parts[0].trim()); if (value != null) { String type = parts[1].trim().toLowerCase(); String targetField = parts[0] + "Name"; result.put(new TranslateKey(value.toString(), type), new TranslationTarget(map, targetField)); } }); } }); } /** * 处理普通对象的翻译键收集 */ private static void processObject(Object obj, String[] fieldPairs, Map<TranslateKey, TranslationTarget> result) { // 处理注解字段 Arrays.stream(obj.getClass().getDeclaredFields()) .filter(f -> f.isAnnotationPresent(TranslateField.class)) .forEach(f -> { try { f.setAccessible(true); Object value = f.get(obj); if (value != null) { TranslateField anno = f.getAnnotation(TranslateField.class); String targetField = anno.targetField().isEmpty() ? f.getName() + "Name" : anno.targetField(); result.put(new TranslateKey(value.toString(), anno.type()), new TranslationTarget(obj, targetField)); } } catch (Exception e) { throw new RuntimeException(e); } }); // 处理参数指定字段 if (fieldPairs != null) { Arrays.stream(fieldPairs) .map(pair -> pair.split("\\|")) .filter(parts -> parts.length == 2) .forEach(parts -> { try { Field f = obj.getClass().getDeclaredField(parts[0].trim()); f.setAccessible(true); Object value = f.get(obj); if (value != null) { String type = parts[1].trim().toLowerCase(); String targetField = parts[0] + "Name"; result.put(new TranslateKey(value.toString(), type), new TranslationTarget(obj, targetField)); } } catch (Exception e) { throw new RuntimeException(e); } }); } } /** * 批量从缓存获取翻译值 */ private static Map<TranslateKey, Object> batchGetCache(Set<TranslateKey> keys) { if (CollectionUtils.isEmpty(keys)) { return Collections.emptyMap(); } // 构建缓存键列表 List<String> cacheKeys = keys.stream() .map(k -> String.format("%s%s:%s", CACHE_PREFIX, k.type(), k.value())) .collect(Collectors.toList()); // 批量获取缓存值 List<Object> cachedValues = redisTemplate.opsForValue().multiGet(cacheKeys); if (CollectionUtils.isEmpty(cachedValues)) { return Collections.emptyMap(); } // 构建结果映射 Map<TranslateKey, Object> result = new HashMap<>(keys.size()); Iterator<TranslateKey> keyIterator = keys.iterator(); Iterator<Object> valueIterator = cachedValues.iterator(); while (keyIterator.hasNext() && valueIterator.hasNext()) { TranslateKey key = keyIterator.next(); Object value = valueIterator.next(); if (value != null) { result.put(key, value); } } return result; } /** * 批量从数据库查询翻译值 */ private static Map<TranslateKey, Object> batchQueryDB(Set<TranslateKey> keys) { Map<TranslateKey, Object> result = new HashMap<>(); Map<String, List<String>> groupedKeys = keys.stream() .collect(Collectors.groupingBy( k -> k.type, Collectors.mapping(k -> k.value, Collectors.toList()) )); Map<String, Map<String, String>> stringMapMap = translateService.batchTranslate(groupedKeys); if (CollUtil.isNotEmpty(stringMapMap)) { stringMapMap.forEach((type, map) -> { map.forEach((id, name) -> { result.put(new TranslateKey(id, type), name); }); }); } // groupedKeys.forEach((type, ids) -> { // if ("person".equals(type)) { // translateService.batchGetUserNames(ids) // .forEach((id, name) -> // result.put(new TranslateKey(id, type), name)); // } else if ("org".equals(type)) { // translateService.batchGetOrgNames(ids) // .forEach((id, name) -> // result.put(new TranslateKey(id, type), name)); // } // }); return result; } /** * 批量设置缓存值(使用管道) */ private static void batchSetCache(Map<TranslateKey, Object> values) { redisTemplate.executePipelined((RedisCallback<?>) connection -> { ValueOperations<String, Object> ops = redisTemplate.opsForValue(); values.forEach((key, value) -> { String cacheKey = CACHE_PREFIX + key.type + ":" + key.value; // 使用RedisTemplate的set方法替代过时的connection.setEx ops.set(cacheKey, value, CACHE_EXPIRE, TimeUnit.SECONDS); }); return null; }); } /** * 应用翻译结果到目标对象 */ private static void applyTranslations(Map<TranslateKey, TranslationTarget> targets, Map<TranslateKey, Object> values) { targets.forEach((key, target) -> { Object translatedValue = values.get(key); if (translatedValue != null) { setFieldValue(target.target, target.fieldName, translatedValue); } }); } /** * 设置字段值 */ private static void setFieldValue(Object target, String fieldName, Object value) { try { if (target instanceof Map) { ((Map) target).put(fieldName, value); } else { Field field = target.getClass().getDeclaredField(fieldName); field.setAccessible(true); field.set(target, value); } } catch (Exception e) { throw new RuntimeException("Set field failed: " + fieldName, e); } } /** * 判断是否为简单值类型 */ private static boolean isSimpleValue(Class<?> clazz) { return clazz.isPrimitive() || CharSequence.class.isAssignableFrom(clazz) || Number.class.isAssignableFrom(clazz) || clazz == Boolean.class; } /** * 翻译键记录 */ private record TranslateKey(String value, String type) { } /** * 翻译目标记录 */ private record TranslationTarget(Object target, String fieldName) { } } 优化一下,实际使用redis空指针
07-24
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值