您的位置:首页 > 理论基础 > 计算机网络

springmvc+spring线程池处理http并发请求数据同步控制问题

2017-03-31 16:24 507 查看
spring配置文件添加线程池配置

<bean id="taskExecutor"
class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<!-- 核心线程数 -->
<property name="corePoolSize" value="3" />
<!-- 最大线程数 -->
<property name="maxPoolSize" value="10" />
<!-- 队列最大长度 >=mainExecutor.maxSize -->
<property name="queueCapacity" value="25" />
<!-- 线程池维护线程所允许的空闲时间 -->
<property name="keepAliveSeconds" value="300" />
<!-- 线程池对拒绝任务(无线程可用)的处理策略 ThreadPoolExecutor.CallerRunsPolicy策略 ,调用者的线程会执行该任务,如果执行器已关闭,则丢弃.  -->
<property name="rejectedExecutionHandler">
<bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy" />
</property>
</bean>


controller类

package com.test.controller;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.test.entity.Order;
import com.test.entity.Test;
import com.test.service.TestService;

@Controller
@RequestMapping("/test")
public class TestController {

@Autowired
private TaskExecutor executor;

@Autowired
TestService testService;

@ResponseBody
@RequestMapping("/order")
public Map<String, Object> test(HttpServletRequest request){

//线程池+同步块
executor.execute(new Runnable() {
@Override
public void run() {
synchronized (testService) {
testService.insert(order);
}
}
});
return null;
}
}


数据库有个字段num值为:382

http每请求一次,num都会-1

模拟并发500个请求

结果如图:





内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring mvc 线程池
相关文章推荐