奔跑吧,JAVA!互联网科技程序员

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

2018-03-22  本文已影响1人  Kiss石头君

配置类

 @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算法

上一篇 下一篇

猜你喜欢

热点阅读