java - springmvc controller 请求中新开线程的困惑
伊谢尔伦
伊谢尔伦 2017-04-17 14:44:44
0
2
436

有一个使用场景,在用户一次的访问中,我向steam的dota2接口请求了20条用户的最近比赛记录,然后传到jsp渲染了,我想把这20条记录存在数据库中,这个操作比较耗时,就新开了一个线程这样做会不会导致线程安全问题,好像不推荐在servlet中新开线程?还有其他的解决方案吗?
模拟代码
@RequestMapping("/thread")

@ResponseBody
public String actionThread(){
    Thread t=new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(5000);
                System.out.println("数据库操作");        
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    });
    t.start();
    return "nihao";
}

谢谢各位 查了文档用了springmvc容器级的taskexecutor ,可以限制线程数目和等待队列的大小。
<task:annotation-driven executor="myExecutor" scheduler="myScheduler"/>

<task:executor id="myExecutor" pool-size="5-10" queue-capacity="100" rejection-policy="CALLER_RUNS"/>
<task:scheduler id="myScheduler" pool-size="10"/>
@Async
public void test(String s){
    try {
        Thread.currentThread().sleep(5000);
        System.out.println("test asny"+s);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

reply all(2)
阿神

Don’t open another thread in the controller. You can put the data from remote access into the cache, such as ehcache or memcache. First determine whether the cache has the timestamp. If it meets the requirements, read it from the cache. Otherwise, access it remotely.

PHPzhong

Is it to avoid blocking the rendering of the jsp page?
1. After the jsp page is loaded, you can make an Ajax request through js to call the interface to join the database.
2. You can use MQ for asynchronous processing

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!