您的位置:首页 > 编程语言 > Java开发

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

2018-04-03 15:53 134 查看
### 配置类
     
     @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算法
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: