簡體   English   中英

Java Spring-管理同步請求的線程

[英]Java Spring - manage threads for sync requests

我有使用SPRING進行REST調用的Java Web應用程序。

我想控制應用程序為請求打開的線程數。

所以我添加了線程配置:

package myPackage;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

@Configuration
public class ThreadConfig {
    @Bean
    public TaskExecutor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(1);
        executor.setMaxPoolSize(1);
        executor.initialize();
        return executor;
    }
}

我使用的是Sync服務而不是Async,我對其進行了測試,它不限制處理請求的線程,它可以同時處理所有請求。

我期望的是一次發送2個請求-拋出第二個請求,或者等待直到第一個請求完成。

我根本沒有在應用程序中實現Thread。 這是我的控制器的相關代碼:

    @RestController
    public class Module1Controller {
        @RequestMapping(method = RequestMethod.GET, path = "/module1")
InterruptedException {
        public Module1 Module1() throws InterruptedException {
            Date startDate = new Date();
            System.out.println("Thread #: " + Thread.currentThread().getId() + " Request received at: " + startDate);
            Thread.sleep(10000);
            Date endDate = new Date();
            long diff = endDate.getTime() - startDate.getTime();
            long seconds = TimeUnit.MILLISECONDS.toSeconds(diff);
            System.out.println("Thread #: " + Thread.currentThread().getId() + " thread released at: " + endDate + ", total seconds: " + seconds);
            return new Module1(new Clock());
        }

這是控制台結果:

Thread #: 34 Request received at: Sun Dec 17 10:16:20 IST 2017
Thread #: 35 Request received at: Sun Dec 17 10:16:21 IST 2017
Thread #: 34 thread released at: Sun Dec 17 10:16:30 IST 2017, total seconds: 10
Thread #: 35 thread released at: Sun Dec 17 10:16:31 IST 2017, total seconds: 10

我在這里想念什么?

問題在於,在配置Bean中創建TaskExecutor不會影響RestController。

使一次RestController一次僅處理一個請求的最簡單方法是使處理方法同步,例如:

@RequestMapping(method = RequestMethod.GET, path = "/module1")
public synchronized Module1 getModule1() throws InterruptedException {

如果希望同時處理一定數量的最大請求,則可以使用FixedThreadPool,例如:

// allow only 2 requests at a time, more requests are automatically placed in a queue
private final ExecutorService es = Executors.newFixedThreadPool(2);

@RequestMapping(method = RequestMethod.GET, path = "/module1")
public Module1 getModule1() throws ExecutionException, InterruptedException {
    Future<Module1> result = es.submit(new Callable<Module1>() {
        @Override
        public String call() throws Exception {
            try {
                //.... do your work here....
                return Module1()
            } catch (InterruptedException e) {
                return null;
            }
        }
    });
    return result.get();
}

我不確定您為什么要這樣做。 限制請求數量將導致性能下降,並且用戶不會喜歡這樣。

您不能在應用程序中而是在容器中控制請求的線程。 也許您想在應用程序的有限線程中運行某些任務。 您可以這樣:

@RestController
public class ThreadController {
@Autowired
private TaskExecutor taskExecutor;

@RequestMapping(method = RequestMethod.GET, path = "/thread")
public void Module1() {


    taskExecutor.execute(new Runnable() {
        @Override
        public void run() {
            Date startDate = new Date();
            System.out.println("Thread #: " + Thread.currentThread().getId() +
                    " Request received at: " + startDate);
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Date endDate = new Date();
            long diff = endDate.getTime() - startDate.getTime();
            long seconds = TimeUnit.MILLISECONDS.toSeconds(diff);
            System.out.println("Thread #: " + Thread.currentThread().getId() +
                    " thread released at: " + endDate + ", total seconds: " + seconds);
        }
    });
  }
}

結果:

Thread #: 55 Request received at: Sun Dec 17 22:40:57 CST 2017
Thread #: 55 thread released at: Sun Dec 17 22:41:07 CST 2017, total seconds: 10
Thread #: 55 Request received at: Sun Dec 17 22:41:16 CST 2017
Thread #: 55 thread released at: Sun Dec 17 22:41:26 CST 2017, total seconds: 10
Thread #: 55 Request received at: Sun Dec 17 22:41:32 CST 2017
Thread #: 55 thread released at: Sun Dec 17 22:41:42 CST 2017, total seconds: 10

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM