Hystrix仅在第一次发生错误时执行fallbackMethod

问题描述 投票:1回答:1

我正在尝试使用Spring框架的一个小脚本,该框架为“Notes”微服务上的“用户”创建“注释”。

然后有一个独立的“用户”微服务,为了为用户创建注释,我应该首先检查该用户是否存在于“用户”微服务中。

但是,如果“用户”微服务关闭,我想将该注释存储在地图中(连同用户名),然后每10秒重试一次。

每次执行带有@HystrixCommand标记的方法时,我都希望Hystrix执行完全相同的方式,但是第一次执行时,Hystrix执行的方式完全相同。

如果“用户”微服务在第二次调用“createUserNote”方法时保持关闭,则Hystrix不会处理错误。

    @HystrixCommand(fallbackMethod = "createUserNoteReliable")
public NoteLab createUserNote(String username, NoteLab noteLab) {

    System.out.println("Trying to create user note (HystrixCommand)");

    URI uri = URI.create("http://localhost:8080/users/userExists/" + username);

    System.out.println("uri created");

    if (restTemplate.getForObject(uri, boolean.class)) {
        System.out.println("CREATING NOTE " +noteLab.getId());
        try {
            noteLab.setDateCreation(LocalDateTime.now());
            noteLab.setDateEdit(LocalDateTime.now());
            return addUserNote(username, noteLab);
        } catch (Exception e){
            return null;
        }
    } else {
        System.out.println("User " +username + " does not exist");
        return null;
    }

}

HashMap<NoteLab, String> mapNoteUser = new HashMap<>();

public NoteLab createUserNoteReliable(String username, NoteLab noteLab) {
    System.out.println("User server is down. Saving the note " +noteLab.getId());
    try {
        mapNoteUser.put(noteLab, username);
    } catch (Exception e){}
    return null;
}

@Scheduled(fixedDelay = 10000) //In miliseconds. (10s)
public void retryCreateUserNote(){
    System.out.println("Executing automatic retry method");

    for( NoteLab note:  mapNoteUser.keySet() ) {
        System.out.println("Retying to create note " + note.toString() + " from " + mapNoteUser.get(note));

        NoteLab noteToRetry = note;
        String userToRetry = mapNoteUser.get(note);

        mapNoteUser.remove(note);

        createUserNote(userToRetry, noteToRetry);
    }
}

我把我的代码保留在这里,任何有关正在发生的事情的线索都将非常感激。

非常感谢你提前!

java spring microservices hystrix
1个回答
1
投票

您必须了解注释的工作原理。注释仅在课外使用。注释@HystrixCommand将包装您的对象以处理来自外部的所有调用。

但是当你从createUserNote方法调用retryCreateUserNote方法时,这是一个内部操作。此方法调用不会通过包装器对象!

这就是为什么你只看到它被调用一次。

我希望这能澄清正在发生的事情!

© www.soinside.com 2019 - 2024. All rights reserved.