Total Pageviews

2017/11/03

SMS Service with Failsafe Mechanism

Scenario


How-To
Making good use of failsafe library can let you handle failure easily.
Remember to add dependency into your pom.xml
1
2
3
4
5
6
        <!-- retry -->
        <dependency>
            <groupId>net.jodah</groupId>
            <artifactId>failsafe</artifactId>
            <version>1.0.4</version>
        </dependency>


Sample code:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
    private void sendSmsWithRetry(final String otp, final SmsParams params) {
        final String mobilePhone = params.getMobilePhone();
        final CallerEnum sourceName = params.getSourceName();
        final String policyNumber = params.getPolicyNumber();
        final String userId = params.getUserId();

        RetryPolicy retryPolicy = new RetryPolicy();
        retryPolicy.withDelay(1, TimeUnit.SECONDS); // Sets the delay between retries.
        retryPolicy.withMaxRetries(5);              // Sets the max number of retries to perform. -1 indicates to retry forever.

        // Creates and returns a new SyncFailsafe instance that will perform executions and 
        // retries synchronously according to the retryPolicy.
        Failsafe.with(retryPolicy)
        // Registers the listener to be called when an execution is successful.
        .onSuccess(new CheckedConsumer() {
            @Override
            public void accept(Object t) throws Exception {
                // The execution is successful, then write success log into database
            }
        })
        // Registers the listener to be called when an execution attempt fails.
        .onFailedAttempt(new CheckedConsumer() {
            @Override
            public void accept(Object t) throws Exception {
                if (t instanceof Exception) {
                    Exception e = (Exception) t;
                    // The execution attempt fails, then write error log into database
                }
            }
        })
        // Registers the listener to be called when an execution fails and cannot be retried.
        .onFailure(new ContextualResultListener() {
            @Override
            public void onResult(Object result, Throwable failure, ExecutionContext context)
                    throws Exception {
                String exeMsg = "驗證碼傳送失敗。手機號碼:" + mobilePhone + ", 失敗原因:" + failure.getMessage();
                failure.printStackTrace();                
                throw new RuntimeException(exeMsg);
            }
        })
        // Executes the runnable until successful or until the configured RetryPolicy is exceeded.
        .run(new CheckedRunnable() {
            @Override
            public void run() throws Exception {
                sendSms(mobilePhone, getSmsText(params.getOtpServiceType(), otp));
            }
        });
    }

No comments: