sudo apt-get install php-memcached
Once installed, enable the Memcache extension in the php.ini file:
extension=memcached.so
After making the changes, restart the web server to apply the new settings.
// Connect to Memcache server $memcached = new Memcached(); $memcached->addServer('localhost', 11211); <p>// Attempt to get data from Memcache cache<br> $cacheKey = 'user_123';<br> $data = $memcached->get($cacheKey);</p> <p>// If data is not found in cache, query the database<br> if (!$data) {<br> $data = fetchDataFromDatabase();<br> // Store data in cache, setting the expiration time to 1 hour<br> $memcached->set($cacheKey, $data, 3600);<br> }</p> <p>// Use data for business logic<br> // ...<br>
This code first connects to the Memcache server and specifies the server's address and port. Then, it attempts to fetch data from the cache. If the data is found in the cache, it is used for subsequent processing. If the data is not found, it is fetched from the database and stored in the cache.
It is important to note that cached data typically needs to have a reasonable expiration time set. In the example above, the expiration time is set to 1 hour (3600 seconds), ensuring that cached data can be reused within that period.
Limited Use Cases: Memcache is best suited for caching frequently accessed data that doesn't change often. It is not ideal for storing data that changes rapidly.
Memory Limitations: Memcache is an in-memory caching system, which means it is limited by available memory. When the cached data volume grows too large, it may cause memory overflow, so it’s important to monitor cache size.
Data Consistency Issues: Memcache is not a strong consistency storage system. It is essential to have mechanisms for cache invalidation to ensure data consistency when using Memcache.