springmvc耗时处理的结果返回优化Callable

  1. 背景
    公司最近上了一个项目,其中要求用websocket去另一项目中获取相应结果,返回给本项目中的control,由于websocket靠另外一个项目推送,所以时效性不能保证,需要使用一个线程,那么如何在查询接口中使用线程且不影响效率呢?Callable便被使用上了。

  2. 关于Callable是什么
    而自从Java 1.5开始,就提供了Callable和Future,通过它们可以在任务执行完毕之后得到任务执行结果。如果要将一个流异步输出需要借助于Spring 4.2版本添加的一个新的接口StreamingResponseBody。

  3. 怎么使用

@RestController
@RequestMapping("/demo")
public class DemoApi {
public static ConcurrentMap<Long, Student> studentMap = new ConcurrentHashMap<>();
    @PostMapping("/")
    public Callable<Student> index(@RequestBody School school){
         return ()->
        {
            long id = Thread.currentThread().getId();
            studentMap.remove(id);
            Map<String, Object> sendMessage = new HashMap<>(3,1);
            sendMessage.put("id", id);
            sendMessage.put("data", school);
            Gson gson = new Gson();
            SocketClient.send(gson.toJson(sendMessage));
            synchronized(Thread.currentThread()){
                Thread.currentThread().wait(60000);//超时自动唤醒
            }
            if(studentMap.containsKey(id)){
                Student result = studentMap.get(id);
                studentMap.remove(id);
                return result;
            }else {
                return null;
            }
        };
    }
}

唤醒线程

 @OnMessage
    public void onMessage(String message){
        if(EmptyUtil.isEmpty(message)){
            return;
        }
        Gson gson = new Gson();
        Student student= gson.fromJson(message, Student.class);
        long id = Long.parseLong(student.getThreadId());
        DemoApi.boqVOMap.put(id, student);
        Thread thread = findThread(id);
        if (thread != null) {
        synchronized(this){
           thread.notify();
        }
       }
      }
    }
    private  Thread findThread(long threadId) {
        ThreadGroup group = Thread.currentThread().getThreadGroup();
        while(group != null) {
            Thread[] threads = new Thread[(int)(group.activeCount() * 1.2)];
            int count = group.enumerate(threads, true);
            for(int i = 0; i < count; i++) {
                if(threadId == threads[i].getId()) {
                    return threads[i];
                }
            }
            group = group.getParent();
        }
        return null;
    }

使用过程中可能会报错误

An Executor is required to handle java.util.concurrent.Callable return value

这个有可能是项目中自己重写了WebMvcConfigurationSupport 类需要重写下面的方法

@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
    @Override
    public void configureAsyncSupport(final AsyncSupportConfigurer configurer) {
        configurer.setDefaultTimeout(60 * 1000L);
        configurer.registerCallableInterceptors(timeoutInterceptor());
        configurer.setTaskExecutor(threadPoolTaskExecutor());
   }
    @Bean
    public TimeoutCallableProcessingInterceptor timeoutInterceptor() {
        return new TimeoutCallableProcessingInterceptor();
    }
    @Bean
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor t = new ThreadPoolTaskExecutor();
        t.setCorePoolSize(10);
        t.setMaxPoolSize(50);
        t.setQueueCapacity(10);
        t.setThreadNamePrefix("WEB-Thread-");
        return t;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章