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 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 getValue() throws InterruptedException {
while (true){
synchronized (this){
if (msg != null){
String resultMsg = msg;
msg = null;
return new AsyncResult(resultMsg);