How to use memcached with php

Using this tutorial you will know, How to use memcached with php. We given code for using memcache with php. we shown you to configure memcache with php.

How to use memcached with php

 

How to use memcached with php
How to use memcached with php

If you try to install memcached with Linux server then use following commands

# yum install libevent
# yum install libmemcached libmemcached-devel
# yum install memcached

For Starting the memcached server
# memcached -d -m 512 -l 127.0.0.1 -p 11211 -u nobody

11211 port is default port for memcached server.

For using the memecached with php client you need to install following package

# pecl install memcache

After installing all packages restart the apache server.

# /etc/sbin/service httpd restart

<!--?php
/* OO API */
$memcache_obj = new Memcache;
$memcache_obj--->connect('memcache_host', 11211);
$memcache_obj->set('any_key', 'some value', MEMCACHE_COMPRESSED, 50);
echo $memcache_obj->get('any_key');
?>

Important Note: Memcached key has limitations of 250 charactors, So key value should be with in 250 charactors.

Memcached Server with Rails

To install memcached server on linux/fedora box
yum install memcached

Find help for memcached commands and option
memcached -help

Start memcached server(11211 is default port Number for memcached server)
memcached -m 500 -l 192.168.2.4 -p 11211 -vv
(192.168.2.4 this is my local ip address you can cahnge that)

Stop the Memcached server
ps -ef|grep memcached
kill PROCESS_ID

start memcached server with
memcached -m 500 -l 192.168.2.4 -p 11211 -vv

How to install on Windows server:
1.  Downloaded this Win32 port of memcached by Kenneth Dalgleish.(download from following url)
http://thewebfellas.com/blog/2008/6/9/rails-2-1-now-with-better-integrated-caching
2. Extracted the files to C:\Program Files\memcached
3. Opened a command prompt in the folder and installed memcached as a service using memcached -d install
4. Started the service using net start “memcached Server”

How to use memcache in Rails app?
Open  /config/environments/development.rb for development mode,
production.rb for production mode.
paste following line into file.
config.cache_store = :mem_cache_store, ‘127.0.0.1’, ‘127.0.0.1:11211’ , { :namespace => ‘dev’ }
(127.0.0.1 this is my local ip address you can cahnge or point out to any server where memcached server is running)
Restart mongrel server. you are ready to use memcached server

How to use in Rails
@user= User.find(1)—–OLD Code

New Code With Caching:
@user = cache([‘User’,1],:expires_in => 30.minutes) do
User.find(1)
end