慕課 php 開發APP介面(三)
阿新 • • 發佈:2019-01-30
#檔案:
存key value 值
$value 不為空,則存,為空 則讀,為 null 則刪除
class File{ private $_dir; const EXT = '.txt'; public function __construct(){ $this->_dir = dirname(__FILE__).'/files/'; } public function cacheData($key,$value='',$path=''){ $filename = $this->_dir.$path.$key.self::EXT; if($value !== ''){ if(is_null($value)){ return @unlink($filename); } $dir = dirname($filename); if(!is_dir($dir)){ mkdir($dir,0777); } return file_put_contents($filename,json_encode($value)); } if(!is_file($filename)){ return false; }else{ return json_decode(file_get_contents($filename),true); } } }
#測試
<?php require_once('./response.php'); require_once('./file.php'); $arr = array( 'id'=>1, 'name'=>'singwa', 'type'=>array(4,5,6), 'test'=>array(1,45,67=>array(123,'dsagt')) ); //Response::json(200,'success',$arr); //Response::show(200,'success',$arr,'json'); $file = new File(); $cacheData = $file->cacheData('index_mk_cache',$arr); if($cacheData){ print_r($cacheData); echo "success"; }else{ echo "error"; }
#安裝 redis 參考我這篇文章
#獲取 redis目錄
whereis redis
顯示 /etc/redis 所在的目錄#開啟redis
redis-server /etc/redis/redis.conf
我預設是開啟這一步,並加入全域性變量了,不需要執行這一步#進入redis 終端
redis-cli
#設定值
set singwa 12
#獲取值
get singwa
沒有值則為 nil #設定過期時間
setex singwa 12 aaa
第二個引數是過期時間 (秒)#刪除
del singwa
#退出
exit
#php 操作redis
#新建 setCache.php
<?php
$redis = new Redis();
$redis->connect('127.0.0.1',6379);
$redis->set('singwa',123);
執行
php setCache.php
redis-cli
get singwa
exit
#新建getCache.php
<?php
$redis = new Redis();
$redis->connect('127.0.0.1',6379);
$result = $redis->get('singwa');
var_dump($result);
#執行
php getCache.php
#設定有效時間
$redis->setex('singwa',15,'dfsagas');
#memcache 類似redis 新建memcache.php
<?php
$memcache_obj = new Memcache();
$memcache_obj->connect('memcache_host',11211);
$memcache_obj->set('var_key','some value',MEMCACHE_COMPRESSED,50);
echo $memcache_obj->get('var_key');
#定時任務
1.定時任務服務提供 crontab 命令來設定服務
2.crontab -e // 編輯某個使用者的cron 服務
3.crontab -l //列出某個使用者cron 服務的詳細內容
4.crontab -r //刪除某個使用者的cron 服務
詳細參照我這篇文章
#新建一個定時任務
sudo crontab -e
新增
*/1 * * * * /usr/bin/php /usr/share/nginx/html/mukeApi/12.php
秒 分鐘 小時 月 星期 命令#列出
sudo crontab -l
#刪除
sudo crontab -r
#建立測試資料
mysql -uroot -p
show databases;
create database mukeapi;
use mukeapi;
#建立資料表 catagory
CREATE TABLE `category` (
`category_id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(200) NOT NULL,
`parent_id` int(10) NOT NULL,
`path` varchar(255) NOT NULL,
`create_time` int(11) NOT NULL,
`update_time` int(11) NOT NULL,
PRIMARY KEY (`category_id`)
);
show tables;
exit;
#建立 cron.php
<?php
$connect = mysql_connect('127.0.0.1','root','');
mysql_select_db('mukeapi',$connect);
$sql = "INSERT INTO `category` (`name`, `create_time`) VALUES ('dagtgdsa',".time().")";
mysql_query($sql,$connect);
#開啟定時任務
sudo crontab -e
×/1 × × × × /usr/bin/php /usr/share/nginx/html/mukeApi/cron.php
# 刪除定時任務
sudo crontab -r
sudo crontab -l