同步数据至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);
    }
相关推荐
Alson_Code2 分钟前
Spring Ai Alibaba
java·人工智能·spring
计算机安禾3 分钟前
【c++面向对象编程】第5篇:类与对象(四):赋值运算符重载
java·前端·c++
AI人工智能+电脑小能手11 分钟前
【大白话说Java面试题 第45题】【JVM篇】第5题:JVM中,对象何时会进入老年代?
java·开发语言·jvm·后端·面试
luck_bor15 分钟前
使用接口定义规范,实现类完成具体逻辑
java·开发语言
Tsuki_tl16 分钟前
Thread类的基本用法干货总结
java·javase·线程中断·休眠·线程等待·thread类
likerhood20 分钟前
java的泛型(generics)详细讲解
java·开发语言
大龄码农-涵哥25 分钟前
Java 调用 LLM 全解析:ChatGPT、Claude、通义千问一网打尽
java·开发语言·chatgpt
小新同学^O^26 分钟前
简单学习 --> JVM
java·开发语言·python
Hello.Reader28 分钟前
算法基础(十一)—— 递归树如何看懂分治算法的运行时间
java·算法·排序算法
沐泽__32 分钟前
Elasticsearch 磁盘水位线详解:从触发只读到安全解锁
大数据·安全·elasticsearch