redis实际项目作用

时间:2021-08-05 21:23:09

我整理一下redis主要在项目作用,只是我接触到的

1  手机验证码存入redis中,可以限制什么时候有效

2 防止接口请求频率过高,例如一分钟只能请求5次

代码如下:

<?php
/**
 * 获取ip
 * @return array|false|string
 */
function getIp()
{
    if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
        $ip = getenv("HTTP_CLIENT_IP");
    else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
        $ip = getenv("HTTP_X_FORWARDED_FOR");
    else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
        $ip = getenv("REMOTE_ADDR");
    else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
        $ip = $_SERVER['REMOTE_ADDR'];
    else
        $ip = "unknown";

    return ($ip);
}

$ip = getIp();

$redis = new Redis();
$redis->connect('127.0.0.1','6379');
$key = "api-".$ip."-limit";
$num = 5;

if ($redis->exists($key)) {
    $redis->incr($key);
    $result = $redis->get($key);

    if ($result > 5) {
        exit('次数过多');
    }

}else{
    $redis->incr($key);
    $redis->expire($key,60);
}

print_r('这是获得第 '.$redis->get($key)." 次");

3做缓存用,公司抓取股票基金的数据,存入redis进行缓存使用

4进行队列,应对并发请求

5消息订阅推送

publish(消息发布端):pub.php

 

<?php
/**
 * Created by PhpStorm.
 * User: ma
 * Date: 2018/1/8
 * Time: 16:28
 * 测试消息推送
 */
$redis = new Redis();
$redis->connect('127.0.0.1','6379');

//消息发布
$res = $redis->publish('test1',123);
$res = $redis->publish('test2',789);

subscribe(消息订阅端): sub.php

<?php
/**
 * Created by PhpStorm.
 * User: ma
 * Date: 2018/1/8
 * Time: 16:31
 * 测试消息订阅
 */
$redis = new Redis();
$redis->connect('127.0.0.1','6379');
$redis->subscribe(['test1','test2'],'rec');

function rec($instance,$channelName,$message){
    var_dump($instance);
    echo "--".$channelName."===>".$message.PHP_EOL;
}

用守护进程模式, php  sub.php