1. import java.util.HashMap;
  2. import java.util.Map;
  3. public class ApiCacheInvalidator {
  4. private static final Map<String, Long> cache = new HashMap<>(); // Simulate a cache
  5. private static final int INVALIDATION_INTERVAL_SECONDS = 60; // Invalidation frequency
  6. public static void invalidateCache(String endpoint) {
  7. // Invalidate the cache entry for the given endpoint.
  8. cache.remove(endpoint);
  9. System.out.println("Invalidated cache for endpoint: " + endpoint);
  10. }
  11. public static void invalidateAll() {
  12. cache.clear();
  13. System.out.println("Invalidated all cache entries.");
  14. }
  15. public static boolean isCacheValid(String endpoint) {
  16. return !cache.containsKey(endpoint);
  17. }
  18. public static void main(String[] args) {
  19. // Example usage (development environment)
  20. // Simulate an API endpoint
  21. String endpoint1 = "/users";
  22. String endpoint2 = "/products";
  23. // Invalidate the cache for specific endpoints
  24. invalidateCache(endpoint1);
  25. invalidateCache(endpoint2);
  26. // Check cache validity
  27. System.out.println("Is cache valid for " + endpoint1 + "? " + isCacheValid(endpoint1));
  28. System.out.println("Is cache valid for " + endpoint2 + "? " + isCacheValid(endpoint2));
  29. System.out.println("Is cache valid for /orders? " + isCacheValid("/orders"));
  30. //Invalidate all cache entries
  31. invalidateAll();
  32. System.out.println("Is cache valid for " + endpoint1 + "? " + isCacheValid(endpoint1));
  33. System.out.println("Is cache valid for " + endpoint2 + "? " + isCacheValid(endpoint2));
  34. System.out.println("Is cache valid for /orders? " + isCacheValid("/orders"));
  35. }
  36. }

Add your comment