public class LibraryException extends Exception {
public LibraryException(String message) {
super(message);
}
}
public class Library {
public void borrowBook(String bookId) throws LibraryException {
if (!isBookAvailable(bookId)) {
}
// ...
}
private boolean isBookAvailable(String bookId) {
// ...
}
}
public class LibraryApp {
public static void main(String[] args) {
Library library = new Library();
try {
library.borrowBook("123456");
} catch (LibraryException e) {
}
}
}
<configuration>
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="CONSOLE"/>
</root>
</configuration>
public class BorrowService {
private final CircuitBreaker circuitBreaker;
public BorrowService() {
circuitBreaker = new CircuitBreaker();
}
public void borrowBook(String bookId) throws LibraryException {
if (circuitBreaker.isCircuitOpen()) {
}
try {
// ...
} catch (Exception e) {
circuitBreaker.registerError();
}
}
}
public class CircuitBreaker {
private static final int THRESHOLD = 5;
private int errorCount;
public CircuitBreaker() {
errorCount = 0;
}
public synchronized void registerError() {
errorCount++;
if (errorCount >= THRESHOLD) {
tripCircuit();
}
}
public synchronized void tripCircuit() {
// ...
}
public synchronized boolean isCircuitOpen() {
return errorCount >= THRESHOLD;
}
}