package com.duiba.tuia.youtui.web.filter;

import cn.com.duiba.boot.perftest.PerfTestContext;
import cn.com.duiba.filter.QpsLimitProxy;
import com.duiba.tuia.youtui.web.tool.RequestLocal;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by wenqi.huang on 2016/11/3.
 */
@Component
public class QpsLimitInterceptor extends HandlerInterceptorAdapter implements InitializingBean,DisposableBean {

    @Value("${taw.zookeeper.address}")
    private String zkServers;

    private QpsLimitProxy qpsLimitProxy;
    
    @Override
    public void afterPropertiesSet() throws Exception {
        qpsLimitProxy = new QpsLimitProxy(zkServers, 5);
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Long consumerId = RequestLocal.get().getCid();
        Long appId = RequestLocal.get().getAppId();

        boolean limited = qpsLimitProxy.doLimit(request,response,consumerId,appId);

        return !(limited && !PerfTestContext.isCurrentInPerfTestMode());
    }

    @Override
    public void destroy() throws Exception {
        qpsLimitProxy.destroy();
    }
}
