We have a Java application to connect to OPC server, if it fail to connect to OPC server it will retry 5 times.
How-to
You can make good use of Failsafe to fulfill this requirement.
Failsafe is a lightweight, zero-dependency library for handling failures. It was designed to be as easy to use as possible, with a concise API for handling everyday use cases and the flexibility to handle everything else.
Maven dependency:
1 2 3 4 5 6 7 | <dependencies> <dependency> <groupId>net.jodah</groupId> <artifactId>failsafe</artifactId> <version>0.9.5</version> </dependency> </dependencies> |
If I catch ConnectionException, it will do retry, the retry policy is as bellows:
- it will delay 2 seconds between retries
- it will retry 5 times at most
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 | package albert.practice.retry; import java.util.Calendar; import java.util.Date; import java.util.concurrent.TimeUnit; import lombok.extern.slf4j.Slf4j; import net.jodah.failsafe.Failsafe; import net.jodah.failsafe.RetryPolicy; @Slf4j public class RetryTest { public static void main(String[] args) throws ConnectionException { @SuppressWarnings("unchecked") RetryPolicy retryPolicy = new RetryPolicy().retryOn(ConnectionException.class) .withDelay(2, TimeUnit.SECONDS).withMaxRetries(5); Failsafe.with(retryPolicy).run(() -> new RetryTest().connect()); } public void connect() throws ConnectionException { log.debug("time=" + new Date(Calendar.getInstance().getTimeInMillis())); if (true) { throw new ConnectionException("connection fail!"); } } } |
Reference
[1] https://github.com/jhalterman/failsafe
No comments:
Post a Comment