是否可以在 RetryListener 中访问失败方法的参数?



我有一个方法,它采用会话对象与外部系统通信。会话对象包含用户名和会话令牌。如果外部系统无法识别会话令牌,则会引发异常。在这种情况下,我想使用传递的用户名登录,创建一个新的会话对象,并使用包含有效会话令牌的新会话对象调用原始方法。

我创建了一个扩展 RetryListenerSupport 的侦听器。我用@Retry注释了该方法,并将我的侦听器指定为侦听器。但是在我的侦听器的 onError 方法中,我无法访问该方法的参数。

@Value
public class Session {
private final String username;
private final String sessionToken;
}
@Component
public class EmployeeRetryListener extends RetryListenerSupport {
@Override
public <T, E extends Throwable> void onError(RetryContext context,
RetryCallback<T, E> callback, Throwable throwable) {
if (throwable instance of UnknownSessionException) {
// Here I want to access the arguments of the createEmployee method
}
super.onError(context, callback, throwable);
}
}
@Service
public class EmployeeService {
@Retryable(listeners = "employeeRetryListener")
public void createEmployee(Session session, String employeeName) throws UnknownSessionException {
}
}

我想知道调用该方法的会话实例中的用户名。我还想修改会话实例以更新为会话令牌。

我相信您可能需要对特定异常进行@Recover注释。顾名思义,重试只会重做失败的操作。但是,恢复方法将为您提供在恢复错误时在代码中执行特定操作的选项。这也允许访问正在"重试"的方法的参数。

春季恢复文档。

使用恢复指南重试。

查看链接 2 中的第 4.2 节。它有关于使用重试和恢复的示例

您可以尝试使用RetryTemplate而不是@Retryable注释。
使用模板,您可以访问RetryContext并手动设置参数:

private String goSomething(String arg1) {
return retryTemplate.execute(context -> {
context.setAttribute("argument1", "arg1");
return "some result"
});
}

然后,您可以在侦听器中访问此参数:

@Override
public <T, E extends Throwable> void onError(RetryContext context, RetryCallback<T, E> callback, Throwable throwable) {
if (throwable instance of UnknownSessionException) {
String arg1 = (String) context.getAttribute("argument1")
}
super.onError(context, callback, throwable);
}

最新更新