【问题标题】:Pass service's function in controller for not duplicating try catch block在控制器中传递服务的功能以不复制 try catch 块
【发布时间】:2020-11-16 06:55:26
【问题描述】:

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

我的控制器中有这个功能

@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 and try..catch blocks

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

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

每个控制器都扩展了一个 BaseController,所以在 BaseController 中有通用方法可能会更好?

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

请大家给个意见好吗?

【问题讨论】:

    标签: spring-boot function hibernate lambda controller


    【解决方案1】:

    您可以使用弹簧重试。更多details

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

    【讨论】:

    • 太棒了,我回家试试,谢谢你的回答
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-25
    • 1970-01-01
    • 2011-01-05
    • 2010-09-26
    • 2014-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多