Hystrix 只在第一次出错时执行 fallbackMethod

Hystrix only executes the fallbackMethod the first time the error occurs

我正在尝试使用 Spring 框架编写一个小脚本,为 "Notes" 微服务上的 "user" 创建一个 "note"。

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

但是,如果 "User" 微服务出现故障,我想将该注释(连同用户名)存储在地图中,然后每隔 10 秒重试创建它。

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

如果 "Users" 微服务在第二次调用 "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);
    }
}

我将我的代码留在此处,非常感谢任何关于正在发生的事情的线索。

非常感谢您!

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

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

这就是为什么您只看到它被调用一次的原因。

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