springboot 长轮询实现

springboot 长轮询实现

基于 @EnableAsync , @Sync

@SpringBootApplication
@EnableAsync
public class DemoApplication {
	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
	}
}
@RequestMapping("/async")
@RestController
public class AsyncRequestDemo {

    @Autowired
    private AsyncRequestService asyncRequestService;

    @GetMapping("/value")
    public String getValue() {

        String msg =  null;
        Future<String> result = null;
        try{
            result = asyncRequestService.getValue();
            msg = result.get(10, TimeUnit.SECONDS);
        }catch (Exception e){
            e.printstacktrace();
        }finally {
            if (result != null){
                result.cancel(true);
            }
        }

        return msg;
    }

    @PostMapping("/value")
    public void postValue(String msg) {
        asyncRequestService.postValue(msg);
    }
}
@Service
public class AsyncRequestService {

    private String msg = null;

    @Async
    public Future<String> getValue() throws InterruptedException {

        while (true){
            synchronized (this){
                if (msg != null){
                    String resultMsg = msg;
                    msg = null;
                    return new AsyncResult(resultMsg);
                }
            }
            Thread.sleep(100);
        }
    }

    public synchronized void postValue(String msg) {
        this.msg = msg;
    }
}

备注

  1. @EnableAsync 开启异步
  2. @Sync 标记异步方法
  3. Future 用于接收异步返回值
  4. result.get(10, TimeUnit.SECONDS); 阻塞,超时获取结果
  5. Future.cancel() 中断线程

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/181940.html原文链接:https://javaforall.cn

相关文章

这篇文章主要介绍了spring的事务传播属性REQUIRED_NESTED的原...
今天小编给大家分享的是一文解析spring中事务的传播机制,相...
这篇文章主要介绍了SpringCloudAlibaba和SpringCloud有什么区...
本篇文章和大家了解一下SpringCloud整合XXL-Job的几个步骤。...
本篇文章和大家了解一下Spring延迟初始化会遇到什么问题。有...
这篇文章主要介绍了怎么使用Spring提供的不同缓存注解实现缓...