package com.usky.website.interceptor;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Set;

@Component  //此处将其注入到容器中
public class RedisInterceptor  implements HandlerInterceptor {

    @Resource
    RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //拦截每一次请求并获取请求的URL作为Key
        String url = String.valueOf(request.getRequestURL());
        Map<String,String[]> map = request.getParameterMap();
        Set<String> keys = map.keySet();
        for(String key : keys){
            if(key.equals("id")){
                String[] value = map.get(key);
                if(StringUtils.isNotBlank(value[0])){
                    //默认访问一次请求都会对该请求进行计数+1
                    redisTemplate.opsForValue().increment(value[0]);
                }

                break;
            }
        }

        //放行
        return true;
    }
}
