Design pattern for “retrying” logic that failed?

后端 未结 11 1309
挽巷
挽巷 2020-12-07 16:10

I\'m writing some reconnect logic to periodically attempt to establish a connection to a remote endpoint which went down. Essentially, the code looks like this:



        
11条回答
  •  遥遥无期
    2020-12-07 16:56

    You can also create a wrapper function that just does a loop over the intended operation and when is done just break out of the loop.

    public static void main(String[] args) {
        retryMySpecialOperation(7);
    }
    
    private static void retryMySpecialOperation(int retries) {
        for (int i = 1; i <= retries; i++) {
            try {
                specialOperation();
                break;
            }
            catch (Exception e) {
                System.out.println(String.format("Failed operation. Retry %d", i));
            }
        }
    }
    
    private static void specialOperation() throws Exception {
        if ((int) (Math.random()*100) % 2 == 0) {
            throw new Exception("Operation failed");
        }
        System.out.println("Operation successful");
    }
    

提交回复
热议问题