如何通过Spring中的并发调用来限制方法?

时间:2016-11-02 11:00:56

标签: java spring spring-mvc

是否可以使用任何Spring库来“限制”方法的并发调用次数?像:

@RestController
public class MyRest {
   @RequestMethod
   public void call() {
         someLongRunningSyncTask();
         return "finished"; 
   } 

    public void someLongRunningSyncTask() {

    }
}

假设我已经希望这个方法延迟任何执行(以及其余的webservice响应),如果已有5个其他线程正在运行此方法。

是否有任何注释或其他抽象层已经给我这种行为?

1 个答案:

答案 0 :(得分:1)

可以实现一个接口HandlerInterceptorAdapter来拦截spring mvc请求。 Spring还在HandlerInterceptorAdapter中提供了它的抽象实现,因此您可以扩展它并覆盖您需要的任何方法。从您的描述中看起来您只需要覆盖preHandlepostHandle方法。您可以查看this帖子以获取更多示例。以下是如何实现您需要的任何锁定策略,您觉得方便;

public class CustomInterceptor extends HandlerInterceptorAdapter {

    private final Semaphore semaphore;
    private final long waitTime;

    public CustomInterceptor() {
        // Hardcode this values or inject through spring as preferred.
        semaphore = new Semaphore(5);
        waitTime = 10;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            boolean acquired = semaphore.tryAcquire(1, waitTime, TimeUnit.SECONDS);
            if (!acquired) {
                //TODO Do something with the response or keep waiting or whatever 
            }
        } catch (InterruptedException e) {
            // Do something with this exception. Write custom message to response and then return false.
            // TODO write custom message to response i.e interrupted or something
            return false;
        }
        return super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
        semaphore.release();
        super.postHandle(request, response, handler, modelAndView);
    }

}

然后在spring xml或java config中实例化,并将其注入SimpleUrlHandlerMapping的拦截器属性,如下所示;

<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
    <property name="mappings">
        <props>
            <prop key="/welcome">welcomeController</prop>
        </props>
    </property>
    <property name="interceptors">
        <list>
            <ref bean="customInterceptor" />
        </list>
    </property>
</bean>

<bean id="customInterceptor" class="com.common.mvc.interceptors.CustomInterceptor" />

PS: Haven未对代码进行测试,但您应该了解基本知识。