springboot 长轮询实现


原文链接:https://blog.csdn.net/maple_son/article/details/87884185

 

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;
}
}


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



免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM