/* * 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.get(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
/ 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 ?
There are several places in your clear method where issues could arise:
Key Format Alignment: The format of the keys being inserted into memcachedClient includes the serviceName. However, when clearing the cache, you're directly fetching keys from cachedKeysMap that already include serviceName as part of their values. This alignment needs careful consideration.
Consistency Between Storing Keys and Clearing Keys: When storing keys in the cache, keys are being added to cachedKeysMap appropriately. However, if there's any inconsistency due to different service names or erroneous key entries, it could lead to issues.
Transaction and Consistency Guarantees: Although not directly visible, any race conditions or issues with how cachedKeysMap is maintained might affect the functioning of clear.
Let's walk through the clear method and improve it to address any potential issues:
java
@Override void clear() throws SystemException, UserError {
try {
// Retrieve the set of keys associated with the serviceName from the cachedKeysMap
Set<String> keys = cachedKeysMap.get(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) {
// Ensure the actual key format being used with the memcachedClient is correct
memcachedClient.delete(key);
}
// Optionally clear the keys from the cachedKeysMap if you want immediate state synchronization
cachedKeysMap.remove(serviceName);
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);
}
}
Steps Taken:
Retrieve and Check Key Set: Ensure you're correctly retrieving the set of keys for the current serviceName from cachedKeysMap.
Key Clearing: Iterate and delete each key from Memcached.
Clearing cachedKeysMap: After deleting the keys from Memcached, it might be effective to clear the local cache (cachedKeysMap) to ensure state consistency.
Additional Improvements:
Concurrency Management: If the class is used concurrently, consider synchronizing cachedKeysMap operations to avoid race conditions.
Error Handling: Ensure robust error handling and cleaner logging to diagnose issues quickly.
Unit Testing: Test with different scenarios ensuring keys have been put, get retrieved correctly, and then successfully cleared.
If clear still doesn’t work after these changes, there might be underlying issues with how keys are being tracked or inserted in the cache. You might need more logging to trace the different states and data flows.