memcached的安装、常用命令以及在实际开发中的案例(2)
发布时间:2020-12-25 10:31 所属栏目:53 来源:网络整理
导读:方式2:编译安装 # 安装依赖yum -y install zlib-develyum -y install libmemcached-devel# 编译安装wget https:pecl.php.net/get/memcached-3.1.4.tgz tar zxvf memcached-3.1..tgzcd memcached-4 /usr/bin/phpize
方式2:编译安装 # 安装依赖 yum -y install zlib-devel yum -y install libmemcached-devel # 编译安装 wget https:pecl.php.net/get/memcached-3.1.4.tgz tar zxvf memcached-3.1..tgz cd memcached-4 /usr/bin/phpize ./configure --with-php-config=/usr/bin/php-config make && make install # 修改php.ini vim /etc/php.ini # 添加 extension=memcached.so" # 保存退出 # 重启httpd服务 service httpd restart # 临时关闭 selinux setenforce # 永久关闭 selinux vim /etc/selinux/config # 修改 selinux selinux=disabled # 保存退出 PHP案例:构建高速缓存 第二次从缓存读取 进入mysql mysql -uroot -p 创建数据库 create database cms; use cms; 创建数据表 create table cms_users( id int unsigned not null auto_increment primary key,username varchar(50) not null default '',age tinyint unsigned not 100) not default CURRENT_TIMESTAMP )engine=innodb default charset=utf8; 插入数据 insert into cms_users(username,age,sex,major) values(cyy',22,1)">1,1)">math); insert into cms_users(username,1)">cyy22,1)">chinesecyy323,1)">3,1)">englishcyy424,1)">4,1)">businesscyy525,1)">5,1)">php); 查看数据 select * from cms_users; users.php <?php $start = microtime(true); # 建立memcached连接 $mem = new Memcached(); $mem->addServer('127.0.0.1',11211); $key_name = 'users'; $expire_time = 60;过期时间 判断用户数据在缓存当中是否存在,如果存在,直接get,显示给用户 # 如果不存在,查询数据库,将数据写入到memcached当中,显示给用户 if (false === ($users = $mem->get($key_name))) { 数据不存在于缓存当中,调用PDO查询DB $users = fetchDataFromDB(); 将查询出的数据写入到memcached当中 $mem->set($key_name,1)">$users,time() + $expire_time); } function fetchDataFromDB() { echo 'Fetching data from db....'; Fetch users from mysql using PDO try { $dsn = "mysql:dbname=cms;host=localhost;port=3306"; $pdo = new PDO($dsn,'root','123456',1)"> [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]); $sql = 'select * from cms_users'$stmt = $pdo->prepare($sql); $stmt->execute(); $stmt->fetchAll(PDO::FETCH_ASSOC); } catch (PDOException $pe) { echo $pe->getMessage(); } return $users; } $sex_array = ['unknown','male','female']; echo '<table border=1>'; echo '<tr><th>ID</th><th>USERNAME</th><th>AGE</th><th>SEX</th><th>MAJOR</th><th>CREATED_TIME</th></tr>'foreach ($users as $user) { echo '<tr>'echo '<td>'.$user['id'].'</td>'$user['username'].'</td>'$user['age'].'</td>'$sex_array[$user['sex']].'</td>'$user['major'].'</td>'$user['created_time'].'</td>'echo '</tr>'; } echo '</table>'$end = ); echo "Running time: ". ($end-$start); 小案例 <?php Memcached(); telnet 127.0.0.1 11211 stats $stats = $mem->getStats(); var_dump($stats); $mem->set('php_client',['one' => 1,'two' => 2],1)">time() + 60$res = $mem->get('php_client'var_dump($res); (编辑:ASP站长网) |
相关内容
网友评论
推荐文章
热点阅读