Olaoluwa Oke| 14 June 2023
Have you ever found yourself marveling at the resilience of your favorite websites and applications, effortlessly staying up and running despite encountering unexpected hiccups? As an African, I've become well acquainted with the challenges we often face when it comes to reliable services, and perhaps today, we can unravel the secret behind this digital wizardry.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseConnectionManager {
private String /* Connection */ primaryConnection;
private String /* Connection */ backupConnection;
private String /* Connection */ activeConnection;
public void initialize() throws SQLException {
// Initialize primary and backup connections
primaryConnection ="Primary connection" ;/*DriverManager.getConnection("jdbc:mysql://primary-host:3306/database",
"username", "password");*/
backupConnection ="Secondary connection" ;/* DriverManager.getConnection("jdbc:mysql://backup-host:3306/database",
"username", "password");*/
// Set the primary connection as the active connection initially
activeConnection = primaryConnection;
}
public String getConnection() {
return activeConnection;
}
public void performFailOver() {
// Switch to the backup connection
activeConnection = backupConnection;
System.out.println("Error: Fail-over: Switched to backup connection.");
}
public void performFailBack() {
// Switch back to the primary connection
activeConnection = primaryConnection;
System.out.println("Fail-back: Switched back to primary connection.");
}
public static void main(String[] args) {
try {
DatabaseConnectionManager connectionManager = new DatabaseConnectionManager();
connectionManager.initialize();
// Simulating normal database operation
/*Connection*/ String connection = connectionManager.getConnection();
System.out.println("Performing database operation using connection: " + connection);
// Simulating primary connection failure
connectionManager.performFailOver();
// Simulating fail-over scenario
connection = connectionManager.getConnection();
System.out.println("Performing database operation using connection: " + connection);
// Simulating primary connection restoration
connectionManager.performFailBack();
// Simulating fail-back scenario
connection = connectionManager.getConnection();
System.out.println("Performing database operation using connection: " + connection);
} catch (SQLException e) {
e.printStackTrace();
}
}
}