当前位置: 首页 > news >正文

Spring(四)多线程+异步任务执行服务+常见的Enable注解+SpringUnit测试

Spring多线程

  • Spring通过任务执行器(TaskExecutor)来实现多线程和并发编程
  • ThreadPoolTaskExecutor实现一个基于线程池的TaskExecutor
  • 配置类中@EnableAsync开启对异步任务的支持
  • 使用@Async声明该任务为异步

①、配置类

@Configuration
@ComponentScan("com.xxx.taskExecutor")
@EnableAsync //开启异步任务
public class TaskExecutorConfig implements AsyncConfigurer{//获取一个基于线程池的TaskExecutor@Overridepublic Executor getAsyncExecutor(){ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();taskExecutor.setCorePoolSize(5);taskExecutor.setMaxPoolSize(10);taskExecutor.setQueueCapacity(25);taskExecutor.initialize();return taskExecutor;}@Overridepubic AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler(){return null;}
}

②、任务执行类

这里的方法自动被注入使用ThreadPoolTaskExecutor作为TaskExecutor

@Service
public class AsyncTaskService{@Async //该方法是异步方法,如果注解到类上,标识该类所有方法都是异步的public void executeAsyncTask(Integer i){System.out.println("执行异步任务"+i);}@Asyncpublic void executeAsyncTaskPlus(Integer i){System.out.println("执行异步任务+1"+(i+1));}
}

③、运行

结果是并发执行,而不是顺序执行

public class Main{public static void main(String[] args){AnnotationConfigApplicationContext context = AnnotationConfigApplicationContext(TaskExecutorConfig.class);AsyncTaskService asyncTaskService = context.getBean(TaskExecutorConfig.class);for(int i = 0;i < 10;i++){asyncTaskService.executeAsyncTask(i);asyncTaskService.executeAsyncTaskPlus(i);}context.close();}
}

异步任务执行服务ExecutorService

任务的提交和任务的执行相分离

  • 执行服务封装了任务执行的细节(线程创建、关闭,任务调度)
  • 提交关注任务本身(提交任务、获取结果、取消任务)
public class BasicDemo{static class Task implements Callable<Integer>{int sleepSeconds = new Random().nextInt(1000);Thread.sleep(sleepSeconds);return sleepSeconds;}public static void main(String[] args){ExecutorService executor = Executors.newSingleThreadExecutor();Future<Integer> future = executor.submit(new Task());//模拟其他任务Thread.sleep(100);try{System.out.println(future.get());}catch(ExecutionException e){e.printStackTrace();}executor.shutdown();}
}

@Enable*注解

@EnableAspectJAutoProxy 开启对AspectJ自动代理的支持
@EnableAsync 开启异步方法的支持
@EnableScheduling 开启计划任务的支持

@EnableWebMvc 开启Web MVC的配置支持
@EnableConfigurationProperties开启对@ConfigurationProperties注解配置Bean的支持
@EnableJpaRepositories开启对Spring Data Repository的支持
@EnableTransactionManagement开启对注解式事务的支持
@EnableCaching开启注解式的缓存支持

以上所有开启功能的共性,都有一个@Import用来导入配置类

一、直接导入配置类

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Import(SchedulingConfiguration.class)//直接导入配置类
@Documented
public @interface EnableScheduling{}

二、依据条件选择配置类

@Target(ElementType.TYPE)
@Retention(RetentionPlicy.RUNTIME)
@Documented
@Import(AsyncConfigurationSelector.class)//通过条件来选择需要导入的
public @interface EnableAsync{Class<? extends Annotation> annotation() default Annotation.class;boolean proxyTargetClass() default false;AdviceMode mode() default AdviceMode.PROXY;int order() default Order.LOWEST_PRECEDENCE;
}

三、动态注册Bean

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(AspectJAutoProxyRegistrar.class)//运行时自动添加Bean到已有的配置类
public @interface EnableAspectJAutoProxy{boolean proxyTargetClass() default false;
}

Spring测试

Spring通过Spring TestContext Framework对集成测试提供顶级支持
不依赖特定框架,既可以用Junit,也可以用TestNG

Spring提供了一个SpringJUnit4ClassRunner类
该类提供了Spring TestContext Framework的功能,通过@ContextConfiguration来配置Application Context
通过@ActiveProfiles确定活动的profile

①、依赖

spring-test junit

②、业务代码

public class TestBean{private String content;public TestBean(String content){super();this.content = content;}public String getContent(){return content;}public void setContent(String content){this.content = content;}
}

③、配置类

@Configuration
public class TestConfig{@Bean@Profile("dev")public TestBean devTestBean(){return new TestBean("from development profile");}@Bean@Profile("prod")public TestBean prodTestBean(){return new TestBean("from production profile");}
}

④、测试```java
@RunWith(SpringJUnit4ClassRunner.class)//JUnit环境下提供Spring TestContext Framework的功能
@ContextConfiguration(classes = {TestConfig.class})//用来加载配置ApplicationContext其中classes属性用来加载配置类
@ActiveProfiles("prod")//用来声明活动的profile
public class DemoBeanIntegrationTests{@Autowiredprivate TestBean testBean;@Testpublic void prodBeanShouldInject(){String expected = "from production profile";String actual = testBean.getContent();Assert.assertEquals(expected,actual);}
}
http://www.lryc.cn/news/444504.html

相关文章:

  • 解析与实现二叉树
  • Java面向对象——内部类(成员内部类、静态内部类、局部内部类、匿名内部类,完整详解附有代码+案例)
  • 操作系统笔记三
  • uniapp快速入门教程,内容来源于官方文档,仅仅记录快速入门需要了解到的知识点
  • 基于微信小程序的商品展示+ssm(lw+演示+源码+运行)
  • 【Linux】常用指令(下)(内含more、less、 head、tail、date、find、grep、zip、tar以及学习笔记)
  • DesignMode__unity__抽象工厂模式在unity中的应用、用单例模式进行资源加载
  • Leetcode3289. 数字小镇中的捣蛋鬼
  • 13_Python的高阶函数
  • 清空当前机器所有Docker容器和镜像
  • FreeRTOS学习——Systick中断、SVC中断、PendSV中断
  • 汇量科技大数据面试题及参考答案
  • 移情别恋c++ ദ്ദി˶ー̀֊ー́ ) ——14.AVL树
  • Python 的数据类型与操作
  • Python燃烧废气排放推断算法模型
  • Qt中多语言的操作(以QtCreator为例)
  • 计算机毕业设计 社区医疗服务系统的设计与实现 Java实战项目 附源码+文档+视频讲解
  • html+css学习
  • 2.gitlab ce 细粒度的权限控制
  • G - Merchant Takahashi / F - Useless for LIS
  • 自然语言处理实例
  • 『功能项目』主角属性值显示【75】
  • 单片机嵌入式编程中常用技术点
  • 【毕业论文+源码】基于ASP+NET的人事管理系统
  • 计算机毕业设计 校园志愿者管理系统的设计与实现 Java实战项目 附源码+文档+视频讲解
  • 速通LLaMA2:《Llama 2: Open Foundation and Fine-Tuned Chat Models》全文解读
  • 如何使用VM中win10搭建Hfish蜜罐(危险感知平台)。从下载到部署详细教程
  • Rust: AES 加密算法库
  • 计算机网络34——Windows内存管理
  • Redisson 总结