同步数据至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);
    }
相关推荐
hqxstudying9 分钟前
J2EE模式---服务层模式
java·数据库·后端·spring·oracle·java-ee
GM_82815 分钟前
【最新最完整】SpringAI-1.0.0开发MCP Server,搭建MCP Client 实战笔记(进阶+详细+完整代码)
java·后端·ai编程·springai·mcp
都叫我大帅哥16 分钟前
Java DelayQueue:时间管理大师的终极武器
java
秋千码途23 分钟前
小架构step系列27:Hibernate提供的validator
java·spring·架构·hibernate
都叫我大帅哥24 分钟前
TOGAF迁移规划阶段全解密:从菜鸟到达人的通关秘籍
java
探索java26 分钟前
深入理解 Spring 中的 XmlBeanFactory 原理及实践
java·spring·xmlbeanfactory
虚伪的空想家32 分钟前
记录es收集日志报错问题as the final mapping would have more than 1 type[XXX,doc]
大数据·elasticsearch·搜索引擎·容器·kubernetes·log-pilot
hqxstudying3 小时前
Java异常处理
java·开发语言·安全·异常
我命由我123455 小时前
Kotlin 数据容器 - List(List 概述、创建 List、List 核心特性、List 元素访问、List 遍历)
java·开发语言·jvm·windows·java-ee·kotlin·list
武子康8 小时前
Java-80 深入浅出 RPC Dubbo 动态服务降级:从雪崩防护到配置中心秒级生效
java·分布式·后端·spring·微服务·rpc·dubbo