同步数据至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);
    }
相关推荐
瀚高PG实验室6 分钟前
HGDB集群(安全版)repmgr手动切换主备库
java·数据库·安全·瀚高数据库
刘新明198917 分钟前
Frida辅助分析OLLVM虚假控制流程(下)
java·开发语言·前端
第二只羽毛39 分钟前
重载和继承的实践
java·开发语言
王嘉俊92544 分钟前
设计模式--适配器模式:优雅解决接口不兼容问题
java·设计模式·适配器模式
王嘉俊9251 小时前
设计模式--组合模式:统一处理树形结构的优雅设计
java·设计模式·组合模式
道19931 小时前
50 台小型无人车与50套穿戴终端 5 公里范围内通信组网方案深度研究
java·后端·struts
迎風吹頭髮1 小时前
UNIX下C语言编程与实践35-UNIX 守护进程编写:后台执行、脱离终端、清除掩码与信号处理
java·c语言·unix
光军oi1 小时前
全栈开发杂谈————JAVA微服务全套技术栈详解
java·开发语言·微服务
帮帮志1 小时前
目录【系列文章目录】-(关于帮帮志,关于作者)
java·开发语言·python·链表·交互
聪明的笨猪猪1 小时前
Java Spring “MVC ”面试清单(含超通俗生活案例与深度理解)
java·经验分享·笔记·面试