基于Callable的方式萨醒,也是常見的HTTP異步服務(wù)提供方式芜繁,有利于提高系統(tǒng)的并發(fā)處理能力税弃。
- 在pom.xml中引入配置
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
- 建立Service層接口
public interface PiceaService {
//無返回參數(shù)方法
void task() throws Exception;
//有返回參數(shù)方法
String task2() throws Exception;
}
- 建立Service層實(shí)現(xiàn)
Service層接口與實(shí)現(xiàn)嘴秸,跟其他正常同步請求一樣合溺,沒有差別卒密。
@Service
public class PiceaServiceImpl implements PiceaService {
@Override
public void task() throws Exception {
System.out.println("------------------------在看貂蟬,不要打擾--------------");
Thread.sleep(1000);
}
@Override
public String task2 () throws Exception {
int k = 1;
System.out.println("------------------------在看魚棠赛,不要打擾--------------");
Thread.sleep(1000);
return (String.valueOf(k));
}
}
- 建立Contoller層方法
基于Callable的方式比較簡單哮奇,就是在返回時(shí),單獨(dú)定一個(gè)線程處理返回值問題睛约。
@RestController
public class PiceaServletContoller {
@Autowired
private PiceaService piceaService;
@RequestMapping("/callable")
public Callable<String> deferredResult() throws Exception {
System.out.println("控制層執(zhí)行線程:" + Thread.currentThread().getName());
return new Callable<String>() {
@Override
public String call() throws Exception {
System.out.println("異步執(zhí)行線程:" + Thread.currentThread().getName());
String str = piceaService.task2();
Thread.sleep(1000);
return ("這是【異步】的請求返回: " + str);
}
};
}
}
- 測試結(jié)果及方法
瀏覽器中訪問http://localhost:2001/callable測試結(jié)果鼎俘。
Spring-boot-async-callable.png
其它注意
本文章樣例:
工程名:spring-boot-async-callable
GitHub:https://github.com/zzyjb/SpringBootLearning