同步数据至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);
    }
相关推荐
脸大是真的好~19 小时前
计算机408基础相关面试题-备用,不推荐
java
小费的部落19 小时前
Excel 在Sheet3中 匹配Sheet1的A列和Sheet2的A列并处理空内容
java·前端·excel
咘噜biu19 小时前
多租户动态数据源插件dynamic-datasource简介
java·mybatisplus·动态数据源·多租户
漫漫求19 小时前
Java内存模型【JMM】、JVM内存模型
java·开发语言·jvm
原来是好奇心19 小时前
深入Spring Boot源码(五):外部化配置与Profile机制深度解析
java·源码·springboot
IT界的奇葩19 小时前
OAuth2 单点登录流程图
java·流程图·oauth2·单点登录·sso
ZHang......20 小时前
LeetCode 1114. 按序打印
java·开发语言·算法
程序员欣宸20 小时前
LangChain4j实战之四:集成到spring-boot
java·人工智能·spring boot
慧都小项20 小时前
Parasoft Jtest 如何用 JSON 文件驱动Java 测试自动化
java·自动化·json
Hui Baby21 小时前
全局事务入口感知子事务方法-TCC
java·开发语言·数据库