通过检查返回 mono 的数据库中的值来确保唯一 id

问题描述 投票:0回答:1
需要根据从请求收到的格式生成唯一的 ID。 在插入到数据库之前,需要检查它是否已经存在,如果数据库中不存在,则生成一个新的。 目前,使用 Springboot 3,反应式。

需要有关以下代码的一些指导。

期望:

    根据格式创建唯一的ID。
  • 检查数据库中是否已存在记录
  • 如果已经存在,则生成一个新的 id
  • 尝试生成新的id 10次,否则错误
如何检查数据库中是否存在记录并继续生成直到过滤条件匹配?

// DB CRUD operation service for Group table // Group record is unique by groupId and type @Autowired final GroupService groupService; public String newUniqueId(String format, String groupId) { // try 10 times to generate a unique id return IntStream.range(0, 10) .mapToObj(i -> newIdByFormat(format)) .filter(newIdByFormat -> isIdUnique(newIdByFormat, groupId)) // Need some guidence here .findFirst() .orElseThrow(() -> new RuntimeException("Could not generate unique id")); } private String newIdByFormat(String format) { // Map<String, Supplier<String>> map; return map.get(format).get(); } private Predicate<String> isIdUnique(String groupId) { // This call returns, Mono<Group> group = groupService.query(id, groupId) return id -> groupService.query(id, groupId) .filter(Objects::isNull); // How to return boolen value here? // tried calling .block() here, but fails with exception // block()/blockFirst()/blockLast() are blocking, which is not supported in thread reactor-http-nio-4 }


public Mono<Group> createGroup(Request) {

    return transformRequest(request)
}

private Mono<Group> transformRequest(request) {
  String uniqueId = newUniqueId(request.format, request.groupId);
  
  return dbService.save(new Group(uniqueId));
}

感谢您的宝贵时间。

spring-boot spring-webflux project-reactor reactive
1个回答
0
投票
private Mono<Group> transformRequest(request) { // newUniqueId() must return a Mono. // otherwise you start to execute the code right in this method, which is not reactive. // Ex., a non-mono executed even if the result is cancelled. // Reactive code executed only when it actually needed. Like lazily Mono<String> uniqueId = newUniqueId(request.format, request.groupId); return uniqueId.map { id -> new Group(id) }.flatMap { group -> // .save() should be a Mono dbService.save(group).thenReturn(group) } } public Mono<String> newUniqueId(String format, String groupId) { Mono.fromCallable { // Callable executed only when it's actually subscribed newIdByFormat(format) }.flatMap { id -> groupService.query(id, groupId).retry(10) } }
    
© www.soinside.com 2019 - 2024. All rights reserved.