基于Callable的方式,也是常见的HTTP异步服务提供方式,有利于提高系统的并发处理能力。
- 在pom.xml中引入配置
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
- 建立Service层接口
public interface PiceaService {
//无返回参数方法
void task() throws Exception;
//有返回参数方法
String task2() throws Exception;
}
- 建立Service层实现
Service层接口与实现,跟其他正常同步请求一样,没有差别。
@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的方式比较简单,就是在返回时,单独定一个线程处理返回值问题。
@RestController
public class PiceaServletContoller {
@Autowired
private PiceaService piceaService;
@RequestMapping("/callable")
public Callable<String> deferredResult() throws Exception {
System.out.println("控制层执行线程:" + Thread.currentThread().getName());
return new Callable<String>() {
@Override
public String call() throws Exception {
System.out.println("异步执行线程:" + Thread.currentThread().getName());
String str = piceaService.task2();
Thread.sleep(1000);
return ("这是【异步】的请求返回: " + str);
}
};
}
}
- 测试结果及方法
浏览器中访问http://localhost:2001/callable测试结果。
其它注意
本文章样例:
工程名:spring-boot-async-callable
GitHub:https://github.com/zzyjb/SpringBootLearning