HomeMySQL Page 3 - Take Some Load off MySQL with MemCached
Enter MemCached - MySQL
While the execution speed of your codebase can be a factor in the overall scalability of your application, more often than not, your database will become a bottleneck first. Modern web development environments can generally serve many page loads per second, and each of these pages will often make many requests to the database for fresh information. These pages may also be rendered by an easily expandable pool of web servers. While databases, including MySQL, are adequately designed to handle a significant number of queries, eventually, the load from all these requests can become too much to handle.
MemCached is designed as a solution for low complexity caching. Data is stored as simple key-value pairs, with the two primary operations “get” and “set.” All data is stored in RAM allocated to the MemCache server. This allows for incredibly fast access times, generally beating those of a database handily.
Once you’ve installed MemCached on your system (from source, RPM, deb, or tarball), you’ll want to fire up an instance and allocate it some memory:
MemCached is now running, listening on port 11211 of your localhost (127.0.0.1) interface, and using 8 Megabytes of memory. It’s running as user nobody to mitigate any security concerns. (At some point, you’ll want to add this command to your start-up scripts, ensuring that MemCached starts up with your server).
While you’ll generally access MemCached with a higher-level client API, you can get a feel for the system and the protocol used with a telnet client.
> telnet 127.0.0.1 11211
set mykey 0 0 13
VALUE mykey 0 13
The lines beginning with “set” and “Hello, World!” after it are the basic set command. It tells MemCached to store some data for a given key:
set [KEYNAME] [FLAGS] [EXPIRES] [BYTES]\r\n
[BYTES OF DATA]\r\n
KEYNAME can be any string up to 250 characters. FLAGS is used by client libraries to note any characteristic of the stored data. EXPIRES is 0 if the data should never expire, a number of seconds to retain the data, or a unix timestamp when the data should expire. BYTES is the size of the data to be stored and DATA is sent after a line break.
“get” is much simpler; it takes one parameter and returns the stored data.