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

devtools/2024/9/24 3:33:39/

Spring多线程

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

①、配置类

java">@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

java">@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));}
}

③、运行

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

java">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

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

  • 执行服务封装了任务执行的细节(线程创建、关闭,任务调度)
  • 提交关注任务本身(提交任务、获取结果、取消任务)
java">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用来导入配置类

一、直接导入配置类

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

二、依据条件选择配置类

java">@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

java">@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

②、业务代码

java">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;}
}

③、配置类

java">@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.ppmy.cn/devtools/116301.html

相关文章

CVC输入语言

声明 位向量表达式&#xff08;或项&#xff09;由位向量常数、位向量变量以及下列函数构成。在STP中&#xff0c;所有变量必须在使用前声明。声明一个长度为32的位向量变量的例子是&#xff1a;x : BITVECTOR(32);。声明数组的例子如下&#xff1a; x_arr : ARRAY BITVECTOR(…

文本分类实战项目:如何使用NLP构建情感分析模型

文本分类实战项目&#xff1a;如何使用NLP构建情感分析模型 一、引言 随着互联网的迅速发展&#xff0c;用户在社交媒体、产品评论、论坛等平台上产生了大量的文本数据。通过分析这些数据&#xff0c;我们可以了解用户的情绪和态度&#xff0c;而情感分析就是专门用于分析文本…

伦敦金的交易差价意味着什么?

在伦敦金投资市场上&#xff0c;点差是指交易平台的买入价&#xff08;买价&#xff09;和卖出价&#xff08;卖价&#xff09;之间的差额。对投资者来说&#xff0c;点差是交易成本的一部分&#xff0c;但它是经纪商的收入来源。点差代表伦敦金投资者在进入和退出交易时需要支…

C#基础(13)结构体

前言 随着函数的讲解完成&#xff0c;我想你已经初步有了写一些复杂逻辑功能的能力&#xff0c;但是我们会发现其实在我们大部分实际开发情况中&#xff0c;很多我们需要写的变量可能不只有一个属性。 他可能有很多变量&#xff0c;那这时候我们如果要把这些变量集中到一个东…

LabVIEW提高开发效率技巧----使用LabVIEW工具

LabVIEW为开发者提供了多种工具和功能&#xff0c;不仅提高工作效率&#xff0c;还能确保项目的质量和可维护性。以下详细介绍几种关键工具&#xff0c;并结合实际案例说明它们的应用。 1. VI Analyzer&#xff1a;自动检查代码质量 VI Analyzer 是LabVIEW提供的一款强大的工…

通过多模态关系图学习实现可解释的医学图像视觉问答|文献速递--Transformer架构在医学影像分析中的应用

Title 题目 Interpretable medical image Visual Question Answering via multi-modal relationship graph learning 通过多模态关系图学习实现可解释的医学图像视觉问答。 01 文献速递介绍 医学视觉问答&#xff08;VQA&#xff09;是医学多模态大语言模型&#xff08;LL…

comfyui中报错 Cmd(‘git‘) failed due to: exit code(128) 如何解决

&#x1f388;背景 comfyui今天在安装插件的过程中&#xff0c;发现有个插件第一次安装失败后&#xff0c;再次安装就开始报错了&#xff0c;提示&#xff1a; ComfyUI-Inpaint-CropAndStitch install failed: Bad Request 截图如下&#xff1a; 看下后台的报错&#xff1a; …

设计支持 50 万 QPS 的站内未读消息系统

引言 在现代互联网应用中&#xff0c;站内消息系统是许多平台不可或缺的功能之一&#xff0c;尤其是对于社交网络、电商、金融等需要大量用户交互的系统来说&#xff0c;消息通知功能更是关键。在高并发场景下&#xff0c;一个设计良好的消息系统不仅需要处理大量用户的未读消…