spring-boot - 在 Controller 中传递服务的功能,以便不复制 try catch block

标签 spring-boot function hibernate lambda controller

我正在使用 Hibernate 在 Spring boot 中开发 REST API。

我的 Controller 里有这个功能

@PostMapping("/profile")
public ResponseEntity<String> saveProfile(@Valid @RequestBody SaveProfileVM saveProfileVM,
                                          BindingResult bindingResult)
throws JsonProcessingException {

    if (bindingResult.hasErrors()) return super.fieldExceptionResponse(bindingResult);

    Profile profile;

    boolean optimisticLockException = true;
    int retryCount = 0;

    do {
        try {
            profile = accountService.saveProfile(saveProfileVM.getAccountId(),
                                                 saveProfileVM.getName(),
                                                 saveProfileVM.getEmail());

            optimisticLockException = false;
            retryCount++;

        } catch (ObjectOptimisticLockingFailureException exception) {
            retryCount++;
            System.out.println(exception.getMessage());
        }
    } while (optimisticLockException && retryCount < MAX_OPTIMISTIC_LOCK_EXCEPTION_RETRY_COUNT);

    return ResponseEntity.status(HttpStatus.OK).body(objectMapper.writeValueAsString(profile));
} 

MAX_OPTIMISTIC_LOCK_EXCEPTION_RETRY_COUNT 为 3

我不想在每个需要检查 ObjectOptimisticLockingFailureException 的方法中重复 do..while 和 try..catch block

do { 
   try{} 
   catch{} 
} while()

有什么方法可以将 accountService.saveProfile() 传递给具有 do..while 和 try..catch block 的通用方法,以便我不必将 block 复制并粘贴到我需要的每个方法?

每个 Controller 都扩展一个 BaseController,所以在 BaseController 中包含通用方法可能会更好?

@RestController
@RequestMapping("/account")
public class AccountController extends BaseController {

你们能给个主意吗?

最佳答案

您可以使用 Spring 重试。更多 details

@Retryable(value = ObjectOptimisticLockingFailureException.class, maxAttempts = 3)
public void saveProfile(Long accountId, String name, String email){..}

关于spring-boot - 在 Controller 中传递服务的功能,以便不复制 try catch block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64853783/

相关文章:

java - Spring调度不运行多线程

spring - 如何同时运行 Spring Boot 测试?

java - Spring Cloud Stream RabbitMQ Binder - Spring Cloud函数错误处理

javascript - 退出pointerlockcontrols Three.js不工作

Javascript:缓存的函数属性与新值

java - 使用 @Bean 注释和 Spring EL 表达式创建 Bean 和名称

python - 递归或迭代函数 (Python)

java - 创建实体时添加静态属性数据

java - 如何使用 JPA 创建 UNIQUE 列?

java - SQL 查询正常,但使用 Hibernate "Multiple ResultSets were returned by the query."- 错误