服务器配置Redis
Redis下载安装配置
wget http://download.redis.io/releases/redis-stable.tar.gz tar -xvf redis-stable.tar.gz cd redis-stable/ make make install ./utils/install_server.sh
安装成功:
Redis服务查看、开启、关闭
ps -ef|grep redis
/etc/init.d/redis_6379 start /etc/init.d/redis_6379 stop service redis_6379 start service redis_6379 stop
Yii2工程配置Redis
下载yii2-redis
在composer.json中添加
"yiisoft/yii2-redis": "~2.0.0"
并执行
composer update
配置common/config/main.php
'components' => [ 'redis' => [ 'class' => 'yii\redis\Connection', 'hostname' => 'localhost', 'port' => 6379, 'database' => 0, ], ],
购物车接口
public function actionSetcart(){ if (isset($_REQUEST['uid'])&&isset($_REQUEST['cart'])) { $uid = $_REQUEST['uid']; $cart = $_REQUEST['cart']; //Redis保存购物车数据:30分钟 $redis = Yii::$app->redis; $redis->set('cart:'.$uid, $cart); $redis->expire('cart:'.$uid, 30*60); $result['error'] = 0; $result['msg'] = '保存成功'; } else { $result['error'] = 1; $result['msg'] = '参数错误'; } return $result; } public function actionGetcart(){ if (isset($_REQUEST['uid'])) { $uid = $_REQUEST['uid']; //Redis保存购物车数据:30分钟 $redis = Yii::$app->redis; $cart = $redis->get('cart:'.$uid); $result['error'] = 0; $result['msg'] = '获取成功'; $result['cart'] = $cart ? $cart : ''; } else { $result['error'] = 1; $result['msg'] = '参数错误'; } return $result; }
根据IP限制接口访问
$ip = $_SERVER['REMOTE_ADDR']; $redis = Yii::$app->redis; $redis_ip = $redis->get('ip:'.$ip); if ($redis_ip) { # code... } else { $redis->set('ip:'.$ip, TRUE); $redis->expire('ip:'.$ip, 60); # code... }
小demo
public static function getJsApiTicket() {
//使用Redis缓存 jsapi_ticket
$redis = Yii::$app->redis;
$redis_ticket = $redis->get('wechat:jsapi_ticket');
if ($redis_ticket) {
$ticket = $redis_ticket;
} else {
$accessToken = self::getAccessToken();
$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=".$accessToken;
$res = json_decode(self::curlGet($url));
$ticket = $res->ticket;
if ($ticket) {
$redis->set('wechat:jsapi_ticket', $ticket);
$redis->expire('wechat:jsapi_ticket', 7000);
}
}
return $ticket;
}
public static function getAccessToken() {
//使用Redis缓存 access_token
$redis = Yii::$app->redis;
$redis_token = $redis->get('wechat:access_token');
if ($redis_token) {
$access_token = $redis_token;
} else {
$appid = Yii::$app->params['wechat']['appid'];
$appsecret = Yii::$app->params['wechat']['appsecret'];
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret;
$res = json_decode(self::curlGet($url));
$access_token = $res->access_token;
if ($access_token) {
$redis->set('wechat:access_token', $access_token);
$redis->expire('wechat:access_token', 7000);
}
}
return $access_token;
}