限制ip操作业务次数

package kainian.wu.demoweb.controller;

import com.alibaba.fastjson.JSONException;
import kainian.wu.demoweb.entity.StudentEntity;
import kainian.wu.demoweb.request.ReqUser;
import kainian.wu.demoweb.service.StudentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * * *  GOOK LUCK  * *
 *
 * @Author by   wukainian,
 * @Date on     2018/11/22.
 */
@RestController
@RequestMapping("student")
public class StudentController {

Logger logger = LoggerFactory.getLogger(StudentController.class);

    @Autowired
    private StudentService studentService;


    @PostMapping(value = "/find")
    public StudentEntity fidnUser(@RequestBody @Validated ReqUser reqUser, BindingResult bindingResult) {
        logger.info("ReqUser"+reqUser);
        return  studentService.findById(reqUser.getId());


    }





    private CopyOnWriteArrayList> ipList = new CopyOnWriteArrayList<>();


    @RequestMapping(value = "/send")
    public Object sendMsg(HttpServletRequest request) throws JSONException {
        try {
            //限制访问频率
            String userIp = request.getRemoteAddr();
            System.out.println("IP"+userIp);
            ConcurrentHashMap ipMap = new ConcurrentHashMap<>();
            if(ipList!=null && !ipList.isEmpty()){
                for(ConcurrentHashMap myMap : ipList) {
                    if(myMap.get(userIp) != null) {
                        //同一IP 3秒内只能提交一次
                        if(System.currentTimeMillis() - myMap.get(userIp) < 3 * 1000){
                            myMap.put(userIp,System.currentTimeMillis());
                            return "提交过于频繁";
                        }
                    }
                }
                if(ipList.size()==10) {
                    //放满10次请求 清空一次
                    ipList.clear();
                }
            }
            ipMap.put(userIp,System.currentTimeMillis());
            ipList.add(ipMap);
            //发邮件--实际业务
            System.out.println("执行业务。。。。。。。。。。");
        } catch (NumberFormatException e) {
            System.out.println("提交过于频繁");
            e.printStackTrace();
        }
        return "执行业务。。。。。。。。。。";
    }













}

 

你可能感兴趣的:(密码问题)