JAVAEE颠覆者,SpringBoot实战一书学习小记(多线程,计划任务,条件注解@Conditional)

本文介绍了SpringBoot中如何实现多线程,通过TaskExecutor和@Async注解支持异步任务。接着讲解了计划任务的设置,使用@EnableScheduling和@Scheduled注解实现定时任务。最后,探讨了Spring的条件注解@Conditional,通过自定义条件判断在不同环境下创建不同的Bean。
摘要由CSDN通过智能技术生成

多线程

Spring 通过任务执行器(TaskExecutor)来实现多线程和并发编程。使用ThreadPoolTaskExecutor可实现一个基于线程池的TaskExecutor。而实际开发中任务一般是非阻碍的,即异步的,所以我们要在配置类中通过@EnableAsync开启对异步的支持,并通过在实际执行的Bean的方法中使用@Async注解来声明其是一个异步任务。

示例

首先配置类

package com.cn.sola.config;

import java.util.concurrent.Executor;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

@Configuration
@ComponentScan("com.cn.sola.service")
@EnableAsync//利用此注解开启异步任务支持
public class TaskExecutorConfig implements AsyncConfigurer{

	@Override
	public Executor getAsyncExecutor() {
		//配置类实现AsyncConfigurer 接口 并重写getAsyncExecutor方法并返回一个ThreadPoolTaskExecutor
		//这样我们就获得了一个基于线程池的TaskExecutor
		ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
		
		taskExecutor.setCorePoolSize(5);
		taskExecutor.setMaxPoolSize(10);
		taskExecutor.setQueueCapacity(25);
		taskExecutor.initialize();
		
		return taskExecutor;
	}
	
	@Override
	public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
		// TODO Auto-generated method stub
		return null;
	}
}

任务执行类

package com.cn.sola.service;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class AsyncTaskService {

	@Async//该注表明该方法是个异步方法,如果注解在类级别,则表名该类所有的方法都是异步方
	      //而这里的方法自动被注入使用ThreadPoolTaskExecutor作为TaskExecutor
	public void excuteAsyncTask(Integer i){
		System.out.println("执行异步任务"+i);
	}
	
	@Async
	public void excuteAsyncTaskPlus(Integer i){
		
		System.out.println("执行异步任务+1:"+(i+1));
	}
}

运行

package com.cn.sola;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.test.context.junit4.SpringRunner;

import com.cn.sola.config.TaskExecutorConfig;
import com.cn.sola.service.AsyncTaskService;


@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootShiZhanApplicationTests {

	@Test
	public void contextLoads() {
		
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值