Yii 某一个接口增加频率限制并锁死

本文描述了一个API控制器类,涉及用户登录验证、签名检查、频率限制(包括IP和用户层面)、请求数据处理以及错误响应机制,旨在确保系统安全并管理高并发下的服务器压力。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

时间:2021-04-13 17:36:49

 

红包活动被人用工具刷,把服务器压力搞的很大。

处理过程:

  1. IP+接口 按IP封死,不合适,如果同一个网内有多个用户、或换IP无效

  2. 按用户封死,不合适,正常业务受影响

  3. 按用户+接口封死,比较合适,正常业务不影响,只限制指定接口或业务

     

     

 

实现:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

<?php

 

namespace api\components;

 

use common\helper\CaptchaHelper;

use phpDocumentor\Reflection\Types\True_;

use services\CommonService;

use services\users\UserService;

use share\jobs\users\CommonJobs;

use share\models\Users;

use yii;

use yii\web\Controller;

use yii\web\Response;

use yii\web\HttpException;

use yii\base\UserException;

 

class ApiController extends Controller

{

    private $debug = HT_DEBUG;

    protected $needLogin = true;

    protected $needSign = true;

    protected $userId = 0;

    protected $_user;

    protected $params;

    protected $_post;

    protected $format = Response::FORMAT_JSON;

    protected $_data = [];

    const AUTO_CHECK = false;

    protected $_no_encode = ['config''error''wechat'];

 

    // HUATANG_API_SECRET_NEWYEAR

    protected $sign_secret 'HUATANG_API_SECRET';

    /**

     * @var array $_no_catch 不拦截的action列表

     * key 为module/controller

     * value 为,号拼接的action列表, 如果为空,则controller不需要拦截

     */

    protected $_no_catch = [

        'user' . D_S . 'attention' => 'news,more,list,scope',

    ];

 

    public $enableCsrfValidation = false;

 

    public function init()

    {

        parent::init();

        //  \Yii::$app->cache->flush();

        Yii::$app->getResponse()->on(Response::EVENT_BEFORE_SEND, [$this'beforeSend']);

    }

 

    /**

     * 尝试次数限制

     * 通过ip进行限制

     * @param $params

     * @param $funcName

     * @param int $userId

     */

    public function controllerLimit($params$funcName,$userId = 0)

    {

        foreach ($params as $v) {

            if ($v['url'] == $funcName) {

                $this->tryLimit($v['url'], "urlLimit:".$userId$v['time_limit'], $v['try_times'], $v['time_lock']);

            }

        }

    }

 

    /**

     * 尝试次数限制

     * @param $key

     * @param $prefix //前缀,用于跟key组合存redis

     * @param $timeLimit // 限制的频率时间

     * @param $tryTimes // 限制的次数

     * @param $time_lock // 锁死时间

     */

    public function tryLimit($key$prefix$timeLimit$tryTimes$time_lock)

    {

        if (Yii::$app->redis->exists($key ':lock:' $prefix)) {

            return $this->end('亲,操作太频繁,稍后再试!');

        }

        $times = Yii::$app->redis->get($key $prefix) ?: 0;

        if ($times >= $tryTimes) {

            // 一小时只能获取$tryTimes次

            Yii::$app->redis->setex($key ':lock:' $prefix$time_lock, time());

            return $this->end('亲,操作太频繁,稍后再试!');

        else {

            Yii::$app->redis->setex($key $prefix$timeLimit$times + 1);

        }

    }

 

 

    /*

     * 检查是否在不需要拦截的接口列表中

     *

     * @return bool true=在不需要拦截的接口列表中, false=不在

     */

    protected function checkInNoCatch()

    {

        $moduleID strtolower(\Yii::$app->controller->module->id); // @todo

        $controllerID strtolower(\Yii::$app->controller->id);

        $controllerID $moduleID . D_S . $controllerID;

        $actionID strtolower(\Yii::$app->controller->action->id);

        if (isset($this->_no_catch[$controllerID])) {

            $actions $this->_no_catch[$controllerID];

            if (!empty($actions)) {

                $actions array_flip(explode(','$actions));

                if (!isset($actions[$actionID])) {

                    return false;

                }

            }

            return true;

        }

        return false;

    }

 

    public function beforeAction($action)

    {

        $this->params = $this->getRequestData();

        if ($this->checkInNoCatch() || $this->needLogin == false) {

            return true;

        else {

            $this->checkParams(['token''platform']);

            $this->checkToken($this->params['token'], $this->params['platform']);

        }

        return true;

    }

 

    public function afterAction($action$result)

    {

         

 

    }

 

    public function checkToken($token$platform)

    {

        if ($user_id = UserService::getUserInfoByToken($token$platform'user_id')) {

            $this->userId = (int)$user_id;

            // 根据接口频率锁用户

            $uri = Yii::$app->requestedRoute;

            if (in_array($uri, [

                'user/index/info''v2/map/search''map/search'

            ])) {

                $this->controllerLimit([

                    // 指定某接口规则

                    [

                        'url' => 'user/index/info',

                        'time_limit' => 60, // 频率时长 秒

                        'try_times' => 2, // 次数

                        'time_lock' => 86400 * 7,// 秒 用户此接口锁XX秒建议锁到活动结束

                    ],

                    //  [

                    //     'funciton' => 'v2/map/search',

                    //     'time_limit' => $time_limit,

                    //     'try_times' => $try_times,

                    // ],

                    //  [

                    //     'funciton' => 'map/search',

                    //     'time_limit' => $time_limit,

                    //     'try_times' => $try_times,

                    // ]

                ], $uri$this->userId);

            }

            return true;

        else {

            return $this->end('请重新登陆', ErrorCode::ERROR_TOKEN);

        }

    }

 

    public function render($err$msg ''$data = null)

    {

        $ret = ['status' => $err'msg' => $msg];

        $ret['data'] = is_null($data) ? (Object)[] : $data;

        if (empty($ret['data'])) {

            unset($ret['data']);

        }

        return $ret;

    }

 

    public function error($data$msg 'Error')

    {

        return $this->render(ErrorCode::ERROR, $msg$data);

    }

 

    public function success($data$msg 'Success')

    {

        return $this->render(ErrorCode::SUCCESS, $msg$data);

    }

 

    public function getRequestData()

    {

        $_get = Yii::$app->request->getQueryParams();

        $_post = Yii::$app->request->getBodyParams();

 

        $_data array_merge($_get$_post);

 

        if ($_data) {

            $act = Yii::$app->controller->id . "/" . Yii::$app->controller->action->id;

            if (!is_dir(PROJECT_PATH . D_S . 'data' . D_S . 'log')) {

                mkdir(PROJECT_PATH . D_S . 'data' . D_S . 'log', 0777, true);

            }

            file_put_contents(PROJECT_PATH . "/data/log/post-" date("y-m-d") . ".txt"date('Y-m-d H:i:s') . "[" $act "]: " . print_r(json_encode($_data, JSON_UNESCAPED_UNICODE), true) . "\n", FILE_APPEND);

            if($this->needSign)

            $this->checkSign($_data);

            return $_data;

        }

        return false;

    }

 

 

    public function checkParams($params)

    {

         

    }

 

    /**

     * 获取客户端ip

     * @return string

     */

    public function getClientIp()

    {

        if (getenv('HTTP_CLIENT_IP')) {

            $ip getenv('HTTP_CLIENT_IP');

        else if (getenv('HTTP_X_FORWARDED_FOR')) {

            $ip getenv('HTTP_X_FORWARDED_FOR');

        else if (getenv('REMOTE_ADDR')) {

            $ip getenv('REMOTE_ADDR');

        else {

            $ip $_SERVER['REMOTE_ADDR'];

        }

        return $ip;

    }

 

    public function checkSign($params)

    {

    }

 

 

    public function end($msg ''$code = ErrorCode::ERROR)

    {

        $response = yii::$app->response;

        $response->format = yii\web\Response::FORMAT_JSON;

        $response->data = ['status' => $code'msg' => $msg];

        $response->send();

        \Yii::$app->end();

    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值