同步数据至ES时,数据丢失问题处理

问题背景:

数据同步到es过程中,发现数据丢失问题,原因正是因为写入索引前会先删除索引导致!

总体流程:

  • 使用别名索引E
  • redis获取当前索引B(即E指向B),获取新索引A
  • 初始化新索引A,将数据存储到新索引A
  • redis存储当前索引A,别名索引E指向A

代码实现:

  1. redis获取当前索引B
java 复制代码
    public Class<?> getCurrentIndexByAlias(@NonNull String alias, Class<?> defaultClass) {
        String value = stringRedisTemplate.boundValueOps(INDEX_ALIAS +"_"+ alias).get();
        if (value == null) {
            return defaultClass;
        }
        return Class.forName(value);
    }
  1. 获取新索引A,存储数据
java 复制代码
     Method method = currentIndex.getMethod("other");
     //执行方法获取新索引
     Class<?> newIndex = (Class<?>) method.invoke(currentIndex.getDeclaredConstructor().newInstance());
     //初始化索引
     initIndex(newIndex);
     //存储数据
     ...........
  1. redis存储当前索引A
java 复制代码
	redisRepository.switch2IndexOfAlias("E", newIndex);
    public void switch2IndexOfAlias(String alias, Class<?> clazz) {
        stringRedisTemplate.boundValueOps(INDEX_ALIAS +"_"+ alias).set(clazz.getName());
    }
  1. 别名索引E指向A
java 复制代码
 esRepository.switchIndex("E",newIndex.getAnnotation(Document.class).indexName(),
                    currentIndex.getAnnotation(Document.class).indexName());
java 复制代码
    public <T> void switchIndex(String alias, String newIndexName, String oldIndexName) {
        AliasActions aliasActions = new AliasActions();
        //更新新索引
        if (existsIndex(newIndexName)) {
            AliasAction.Add addAction = new AliasAction.Add(AliasActionParameters.builder()
                    .withIndices(newIndexName).withAliases(alias).build());
            aliasActions.add(addAction);
        }
        //删除旧索引
        if (existsIndex(oldIndexName)) {
            AliasAction.Remove removeAction = new AliasAction.Remove(AliasActionParameters.builder()
                    .withIndices(oldIndexName).withAliases(alias).build());
            aliasActions.add(removeAction);
        }
        //绑定别名
        elasticsearchOperations.indexOps(IndexCoordinates.of(newIndexName)).alias(aliasActions);
    }
相关推荐
phltxy3 小时前
C语言操作符详解
java·c语言·算法
步行cgn5 小时前
@Configuration 详解:Spring 配置类的核心注解
java·后端·spring
sunshine22 girl5 小时前
Java学习一 环境配置2 安装和基本使用Idea
java·学习·intellij-idea
嘿嘿-666 小时前
Windows 一键使用 GPT-6 Astra:Codex CLI 配置教程
java·人工智能·windows·gpt·chatgpt·web
策案案案7 小时前
YOLO: 将AI Agents嵌入到IntelliJ IDEA
java·大数据·人工智能·笔记·yolo·microsoft·intellij-idea
Elasticsearch9 小时前
Elasticsearch:ES|QL 搜索教程
elasticsearch
辰烨chenye9 小时前
LeetCode Hot 100 题解 · 堆篇
java·算法·leetcode
shehuiyuelaiyuehao9 小时前
算法29,前缀和,除自身以外的数组的乘积
java·数据结构·算法
小刘在重生~10 小时前
Java常用类|String类详解 + BigDecimal精准计算(含面试题)
java·开发语言·python
随遇而安zx10 小时前
【多线程】---JMM 与 volatile 深度解析
java·多线程