同步数据至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);
    }
相关推荐
SimonKing9 分钟前
Firefox 太卡?换了这浏览器,内存占用直接降了 70%
java·后端·程序员
咖啡八杯11 分钟前
GoF设计模式——建造者模式
java·后端
敖正炀11 分钟前
Elasticsearch 特性全景与选型指南
elasticsearch
l软件定制开发工作室13 分钟前
Spring开发系列教程(41)——集成Open API
java·后端·spring
敖正炀13 分钟前
倒排索引与文本分析引擎
elasticsearch
折哥的程序人生 · 物流技术专研19 分钟前
《Java 100 天进阶之路》第14篇:Java final关键字详解
java·开发语言·后端·面试
IT当时语_青山师__JAVA技术栈20 分钟前
数组与链表深度解析:从内存布局到工业级实践
java·算法·面试
java1234_小锋21 分钟前
Spring AI 2.0 开发Java Agent智能体 - 工具调用(Function Calling / Tools)
java·人工智能·spring
Cosmoshhhyyy22 分钟前
《Effective Java》解读第 52 条:慎用重载
java·开发语言·windows
大大杰哥22 分钟前
温故知新:Java 线程创建方式的演进与总结
java·开发语言·jvm