Spring snooze not working in RestController

I'm trying to retry spring and I got a weird problem. When I use the replay annotation for the method in the break controller, the retry does not work. But if I translate this method into a separate service class, it works. The following code does not work:

@RestController public class HelloController { @RequestMapping(value = "/hello") public String hello() { return getInfo(); } @Retryable(RuntimeException.class) public String getInfo() { Random random = new Random(); int r = random.nextInt(2); if (r == 1) { throw new RuntimeException(); } else { return "Success"; } } } 

But the following:

 @RestController public class HelloController { @Autowired private SomeService service; @RequestMapping(value = "/hello") public String hello() { String result = service.getInfo(); return result; } } @Service public class SomeService { @Retryable(RuntimeException.class) public String getInfo() { Random random = new Random(); int r = random.nextInt(2); if (r == 1) { throw new RuntimeException(); } else { return "Success"; } } } 

My question is why @Retryable does not work when used in a controller?

+5
source share
1 answer

The problem you see is related to the way you call your getInfo() method.

In the first example, you call getInfo() from the same spring managed bean. In the second example, you call getInfo() from another spring managed bean. This difference is subtle, but very important, and very likely what causes your problems.

When you use the @Retryable annotation, spring creates a proxy server around your original bean so that they can perform special processing in special circumstances. In this particular case, spring applies a tip that delegates the call to your actual method, catches a RuntimeException that it can throw, and retry calling your method according to the configuration of the @Retryable annotation.

The reason this proxy matters in your case is because only external callers see the proxy advice. Your bean does not know that it is proxied, and only knows that its methods are called (according to the proxy). When your bean calls the method on its own, no additional proxying occurs, so retrying is not performed.

+4
source

Source: https://habr.com/ru/post/1246443/


All Articles