Spring Boot 基于Callable的异步服务

基于Callable的方式,也是常见的HTTP异步服务提供方式,有利于提高系统的并发处理能力。

  1. 在pom.xml中引入配置
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
  1. 建立Service层接口
public interface PiceaService {
    //无返回参数方法
    void task() throws Exception;
    //有返回参数方法
    String task2() throws Exception;
}
  1. 建立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));
    }
}
  1. 建立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);
            }
        };
    }
}
  1. 测试结果及方法
    浏览器中访问http://localhost:2001/callable测试结果。
    Spring-boot-async-callable.png

其它注意

本文章样例:
工程名:spring-boot-async-callable
GitHub:https://github.com/zzyjb/SpringBootLearning

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容