/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template / package ubq.base; /* * * @author sai / import avian.base.SystemException; import avian.base.UserError; import avian.utils.StringUtils; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import net.spy.memcached.MemcachedClient; import java.io.Serializable; import java.net.InetSocketAddress; import java.sql.ResultSet; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import org.json.JSONObject; import org.json.simple.JSONArray; import org.json.simple.parser.JSONParser; /* * DistributedCacheServiceMemcached provides a service for interacting with * Memcached, a distributed in-memory caching system, for storing and retrieving * objects. This class extends the abstract class CacheService. / public class DistributedCacheServiceMemcached extends CacheService { private static final ULogger logger = new ULogger(DistributedCacheServiceMemcached.class); private static String memcachedHost = "127.0.0.1"; private static int memcachedPort = 11211; private static int DEFAULT_EXPIRATION_TIME_SECONDS = 86400; // Default expiration time: 24 hour private static MemcachedClient memcachedClient; private static final Map<String, Set> cachedKeysMap = new HashMap<>(); private final String serviceName; /* * Initializes the Memcached client and connects to the Memcached server. * The default host and port are used. / Properties props = new Properties(); private void _init() throws UBaseException, IOException { String environment = StringUtils.blankIfNull(System.getProperty("appEnvironment")); if ("".equals(environment)) { environment = "default"; } if (memcachedClient != null) { return; } try { memcachedHost = props.getProperty(environment + "-host"); memcachedPort = Integer.parseInt(props.getProperty(environment + "-port")); DEFAULT_EXPIRATION_TIME_SECONDS = Integer.parseInt(props.getProperty(environment + "-expiration-time-seconds")); } catch (Exception ex) { logger.error("Failed to get the connection details from configuration file."); } logger.info("Connecting to Memcached server @ " + memcachedHost + ":" + memcachedPort); try { memcachedClient = new MemcachedClient(new InetSocketAddress(memcachedHost, memcachedPort)); logger.info("Memcached Client available servers" + memcachedClient.getAvailableServers().isEmpty()); memcachedClient.set("PRODUCT_ID", DEFAULT_EXPIRATION_TIME_SECONDS, "1"); logger.info("PRODUCT_ID: " + memcachedClient.get("PRODUCT_ID")); logger.info("Connected to Memcached server successfully @ " + memcachedHost + ":" + memcachedPort); } catch (Exception ex) { throw new UBaseException("Failed to connect to Memcached server"); } } /* * Constructs a new DistributedCacheServiceMemcached instance using the * provided configuration file path. * * @param configFilePath The path to the configuration file containing * Memcached settings. * @param serviceName * @throws avian.base.SystemException * @throws avian.base.UserError * @throws ubq.base.UBaseException * @throws java.io.IOException * * Stores a Serializable object in Memcached with the specified key and the * default expiration time. * * @param key The key under which the object will be stored in Memcached. * @param value The Serializable object to be stored in Memcached. * * Stores a Serializable object in Memcached with the specified key and * expiration time. * * @param key The key under which the object will be stored in Memcached. * @param value The Serializable object to be stored in Memcached. * @param expirationTimeSecs The expiration time for the cached object in * seconds. * * Retrieves a Serializable object from Memcached using the specified key. * * @param key The key associated with the object to be retrieved from * Memcached. * @param The type of the Serializable object to be retrieved. * @return The Serializable object retrieved from Memcached, or null if not * found or on error. */ public T getObject(String key) { try { return getObjectWithServiceName(serviceName + "" + key); cachedKeysMap.computeIfPresent(serviceName, (k, v) -> { v.remove(key); return v.isEmpty() ? null : v; }); logger.info("Object with key '" + key + "' successfully removed from Memcached."); } catch (Exception ex) { logger.error("Error removing object from Memcached. Key: " + key + ", Error: " + ex.getMessage()); throw new SystemException("Error removing object from Memcached", ex); } } @Override void clear() throws SystemException, UserError { try { // Retrieve the set of keys associated with the serviceName from the cachedKeysMap Set keys = cachedKeysMap.remove(serviceName); // Check if any keys were retrieved for the service if (keys != null && !keys.isEmpty()) { logger.info("Clearing Memcached cache for service '" + serviceName + "'"); // Iterate over each key and delete the corresponding object from Memcached for (String key : keys) { memcachedClient.delete(key); } logger.info("Cleared Memcached cache for service '" + serviceName + "' successfully."); } else { logger.info("No cached keys found for service '" + serviceName + "'"); } } catch (Exception ex) { logger.error("Error clearing Memcached cache: " + ex.getMessage()); throw new SystemException("Error clearing Memcached cache", ex); } } @Override void put(String key, Object value) throws SystemException, UserError { putObject(key, (Serializable) value); } @Override Object get(String key) throws SystemException, UserError { return getObject(key); } }
Assistant
User
is this right ?
code
// Retrieve the set of keys associated with the serviceName from the cachedKeysMap
Set<String> keys = cachedKeysMap.remove(serviceName);
Assistant
/ public DistributedCacheServiceMemcached(String configFilePath, String serviceName) throws SystemException, UserError, UBaseException, IOException { super(configFilePath); this.serviceName = serviceName; if (memcachedClient != null) { return; } FileReader f = null; try { f = new FileReader(configFilePath + "/cache.memcached"); props.load(f); _init(); } catch (Exception ex) { logger.error(ex.getMessage()); throw new UBaseException(ex.getMessage()); } finally { if (f != null) { try { f.close(); } catch (IOException ex) { logger.error("Failed to close file reader"); } } } } /
/ public void putObject(String key, Serializable value, int expirationTimeSecs) { try { // memcachedClient.set(key, expirationTimeSecs, value); putObjectWithServiceName(serviceName + "_" + key, value, expirationTimeSecs); logger.info("Object with key '" + key + "' successfully put in Memcached."); } catch (Exception ex) { logger.error("Error putting object in Memcached. Key: " + key + ", Error: " + ex.getMessage()); } } /
" + key); // T value = (T) memcachedClient.get(key); // // logger.info("Object with key '" + key + "' successfully retrieved from Memcached."); // return value; } catch (Exception ex) { logger.error("Error getting object from Memcached. Key: " + key + ", Error: " + ex.getMessage()); return null; } } private void putObjectWithServiceName(String key, Serializable value, int expirationTimeSecs) { try { memcachedClient.set(key, expirationTimeSecs, value); cachedKeysMap.computeIfAbsent(serviceName, k -> new HashSet<>()).add(key); logger.info("Object with key '" + key + "' successfully put in Memcached."); } catch (Exception ex) { logger.error("Error putting object in Memcached. Key: " + key + ", Error: " + ex.getMessage()); } } @SuppressWarnings("unchecked") private T getObjectWithServiceName(String key) { try { T value = (T) memcachedClient.get(key); logger.info("Object with key '" + key + "' successfully retrieved from Memcached."); return value; } catch (Exception ex) { logger.error("Error getting object from Memcached. Key: " + key + ", Error: " + ex.getMessage()); return null; } } @Override void remove(String key) throws SystemException, UserError { try { memcachedClient.delete(serviceName + "
clear is not working here
It is not clearing any data
any problem here ?
The issue with the clear method might lie in the cachedKeysMap not being populated correctly. The cachedKeysMap is used to keep track of the keys stored in Memcached for a particular service, but it relies on the putObjectWithServiceName method to add keys to this map. If the keys are not being correctly added to this map, the clear method will not have the necessary keys to delete.
Here are some steps to debug and potentially fix the issue:
Ensure cachedKeysMap is Populated: Verify that the cachedKeysMap is being correctly populated when objects are being stored.
Enable Logging: Add logging to check the state of cachedKeysMap before and after operations.
Review the Put Methods: Ensure that putObjectWithServiceName is being called correctly and that keys are being added to the map.
Check Key Formatting: Ensure that the keys in the cachedKeysMap match exactly with the keys used in Memcached (i.e., including the service name prefix).
Here is an updated version of the DistributedCacheServiceMemcached class with enhanced logging to help debug the issue:
java
// Add these imports to ensure everything works fine
import java.util.logging.Logger;
import java.util.logging.Level;
public class DistributedCacheServiceMemcached extends CacheService {
private static final ULogger logger = new ULogger(DistributedCacheServiceMemcached.class);
// Define the logger from java.util.logging
private static final Logger javaLogger = Logger.getLogger(DistributedCacheServiceMemcached.class.getName());
private static String memcachedHost = "127.0.0.1";
private static int memcachedPort = 11211;
private static int DEFAULT_EXPIRATION_TIME_SECONDS = 86400; // Default expiration time: 24 hour
private static MemcachedClient memcachedClient;
private static final Map<String, Set<String>> cachedKeysMap = new HashMap<>();
private final String serviceName;
// Other existing methods...
/**
* Stores a Serializable object in Memcached with the specified key and
* expiration time.
*
* @param key The key under which the object will be stored in Memcached.
* @param value The Serializable object to be stored in Memcached.
* @param expirationTimeSecs The expiration time for the cached object in
* seconds.
*/
public void putObject(String key, Serializable value, int expirationTimeSecs) {
putObjectWithServiceName(serviceName + "_" + key, value, expirationTimeSecs);
}
private void putObjectWithServiceName(String key, Serializable value, int expirationTimeSecs) {
try {
memcachedClient.set(key, expirationTimeSecs, value);
cachedKeysMap.computeIfAbsent(serviceName, k -> new HashSet<>()).add(key);
logger.info("Object with key '" + key + "' successfully put in Memcached.");
javaLogger.log(Level.INFO, "Cached keys for service {0}: {1}", new Object[]{serviceName, cachedKeysMap.get(serviceName)});
} catch (Exception ex) {
logger.error("Error putting object in Memcached. Key: " + key + ", Error: " + ex.getMessage());
}
}
@Override
void clear() throws SystemException, UserError {
try {
// Retrieve the set of keys associated with the serviceName from the cachedKeysMap
Set<String> keys = cachedKeysMap.remove(serviceName);
// Log the keys for debugging
if (keys != null) {
javaLogger.log(Level.INFO, "Clearing keys: {0}", keys);
} else {
javaLogger.log(Level.INFO, "No keys found for service: {0}", serviceName);
}
// Check if any keys were retrieved for the service
if (keys != null && !keys.isEmpty()) {
logger.info("Clearing Memcached cache for service '" + serviceName + "'");
// Iterate over each key and delete the corresponding object from Memcached
for (String key : keys) {
memcachedClient.delete(key);
}
logger.info("Cleared Memcached cache for service '" + serviceName + "' successfully.");
} else {
logger.info("No cached keys found for service '" + serviceName + "'");
}
} catch (Exception ex) {
logger.error("Error clearing Memcached cache: " + ex.getMessage());
throw new SystemException("Error clearing Memcached cache", ex);
}
}
// Other existing methods...
}
In this updated version:
We added a Logger from java.util.logging to log more detailed information about the cachedKeysMap.
After adding a key to cachedKeysMap in putObjectWithServiceName, we log the current state of the map for debug purposes.
We also added logging in the clear method to see what keys are being cleared.
Run the updated code and check the logs to see if the keys are being correctly added to cachedKeysMap and whether they match the keys used in the clear method. This should help you diagnose why the clear method is not working as expected.
Yes, the line where you retrieve the set of keys associated with the serviceName from the cachedKeysMap is correct:
However, there's a nuance that is worth addressing here:
Why use cachedKeysMap.remove(serviceName);?
Removing and Retrieving: remove method retrieves the value associated with the specified key and also removes the entry from the map. This is useful if you want to clear the cache and forget about the keys once they are removed.
Potential Issue: If you call clear multiple times for the same service name without adding new keys, on subsequent calls to clear, cachedKeysMap will not have any record of the previously cached keys, since it was already removed during the first call to clear.
Alternate Approach:
If you want to keep track of the keys persistently even after calling clear, you might want to just retrieve the keys without removing them from the map. This can be done using the get method instead of remove.
Here's the alternate approach using get:
java
@Override
void clear() throws SystemException, UserError {
try {
// Retrieve the set of keys associated with the serviceName from the cachedKeysMap without removing
Set<String> keys = cachedKeysMap.get(serviceName);
// Log the keys for debugging
if (keys != null) {
javaLogger.log(Level.INFO, "Clearing keys: {0}", keys);
} else {
javaLogger.log(Level.INFO, "No keys found for service: {0}", serviceName);
}
// Check if any keys were retrieved for the service
if (keys != null && !keys.isEmpty()) {
logger.info("Clearing Memcached cache for service '" + serviceName + "'");
// Iterate over each key and delete the corresponding object from Memcached
for (String key : keys) {
memcachedClient.delete(key);
}
logger.info("Cleared Memcached cache for service '" + serviceName + "' successfully.");
// Optionally clear the service keys from the cachedKeysMap
cachedKeysMap.remove(serviceName); // If you still want to clear the service after deleting the keys
} else {
logger.info("No cached keys found for service '" + serviceName + "'");
}
} catch (Exception ex) {
logger.error("Error clearing Memcached cache: " + ex.getMessage());
throw new SystemException("Error clearing Memcached cache", ex);
}
}
In this approach:
We use cachedKeysMap.get(serviceName) to retrieve the keys without removing them from the map.
The keys are then cleared from Memcached.
Optionally, you can still remove the keys from cachedKeysMap after clearing them from Memcached to ensure the map is updated.
Choose the approach that best fits your application's requirements. If you always want the clear method to forget about the keys it has cleared, go with the remove approach. If you want to keep the keys in memory even after clearing the cache, use the get approach.