Spring创建任务执行器实现并发

配置类

 @Configuration
@ComponentScan("demo")
@EnableAsync
public class Config implements AsyncConfigurer{
    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(5);
        executor.setMaxPoolSize(10);
        executor.setQueueCapacity(26);
        executor.initialize();
        return executor;
    }
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return null;
    }
}

服务层

    @org.springframework.stereotype.Service
public class Service {
    @Async
    public void task(Integer i){
        System.out.println("异步"+i);
    }
    @Async
    public void task1(Integer i){
        System.out.println("2异步"+i);
    }
}

测试层

public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(
                Config.class);
        Service s = annotationConfigApplicationContext.getBean(Service.class);
        for (int i = 0; i < 10; i++) {
            s.task(i);
            s.task1(i);
        }
    }
}

结果

异步1
异步0
异步3
2异步0
异步4
2异步4
异步5
2异步5
异步6
2异步6
异步7
2异步7
异步8
2异步8
异步9
2异步9
2异步3
2异步2
2异步1
异步2

读取属性文件,配置类型安全的bean

@Component
@ConfigurationProperties(prefix="book",location={"classpath:config/book.properties"})

restful API

获取请求路径中?后面的参数@RequestParam("id")
获取路径中/1/的1 @PathVariable

snowflake算法

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,951评论 19 139
  • 1、Spring MVC请求流程 (1)初始化:(对DispatcherServlet和ContextLoderL...
    拾壹北阅读 1,974评论 0 12
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,958评论 6 342
  • 因为要去探访叔叔的病情,老爸“转弯”来到郑州,看看这个我上学和工作的地方 第一站:二七广场 虽然说二七塔淹没在一片...
    兰静博阅读 283评论 0 0
  • 吾心愿为父母令,自己作诗众人醒。 看破天下如做帽,一切只想忠情晶。
    乱花渐欲迷人眼阅读 163评论 0 0