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