同步数据至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);
    }
相关推荐
码哥字节5 分钟前
升到 Spring Boot 4.1,虚拟线程开了,HikariCP 连接池却崩了
java·springboot·claude code
devilnumber7 分钟前
java自定义事件处理器极简版:「外卖点餐」场景
java·开发语言
J2虾虾9 分钟前
Spring AI Alibaba - 智能体作为工具(Agent Tool)
java·人工智能·spring
Hesionberger9 分钟前
巧用异或找出唯一数字(多解)
java·数据结构·python·算法·leetcode
铁链鞭策大师10 分钟前
javaEE之多线程(2)
java·前端·java-ee
Devin~Y12 分钟前
从内容社区到AIGC客服:Spring Boot、Redis、Kafka、K8s、RAG的三轮大厂Java面试对话(附标准答案)
java·spring boot·redis·spring cloud·kafka·kubernetes·micrometer
それども16 分钟前
怎么理解TCP的状态
java·网络·网络协议·tcp/ip·dubbo
Xzh042316 分钟前
Redis黑马点评 实战复盘与面试高频考点详解
java·数据库·redis·面试
YOU OU20 分钟前
案例综合练习-博客系统
java·开发语言
瑞雪兆丰年兮30 分钟前
[从0开始学Java|第十八、十九天]API(常见API&对象克隆&正则表达式)
java·开发语言