springboot集成线程池

9 篇文章 0 订阅
1 篇文章 0 订阅

springboot @async 线程自定义线程池

import java.util.Random;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.test.annotation.Commit;

/**
 * 
 * @author hemingzhhu
 * @version 2018-6-1
 *
 */
@Component
public class Threads {

	public static Random random = new Random();
	
	Logger log = LoggerFactory.getLogger(Threads.class);

    @Async("taskExecutor")
    public void doTaskOne() throws Exception {
        log.info("开始做任务一");
        long start = System.currentTimeMillis();
        Thread.sleep(random.nextInt(10000));
        long end = System.currentTimeMillis();
        log.info("完成任务一,耗时:" + (end - start) + "毫秒");
    }

    @Async("taskExecutor")
    public void doTaskTwo() throws Exception {
        log.info("开始做任务二");
        long start = System.currentTimeMillis();
        Thread.sleep(random.nextInt(10000));
        long end = System.currentTimeMillis();
        log.info("完成任务二,耗时:" + (end - start) + "毫秒");
    }

    @Async("taskExecutor")
    public void doTaskThree() throws Exception {
        log.info("开始做任务三");
        long start = System.currentTimeMillis();
        Thread.sleep(random.nextInt(10000));
        long end = System.currentTimeMillis();
        log.info("完成任务三,耗时:" + (end - start) + "毫秒");
    }
	
}

2.直接调用就好

@RestController
public class ThreadController {

	 @Autowired
	    private Threads task;

	   @GetMapping("/aa")
	    public void test() throws Exception {

	        task.doTaskOne();
	        task.doTaskTwo();
	        task.doTaskThree();

	        Thread.currentThread().join();
	    }
	
}

springboot @async 使用Futrue以及定义超时加ThreadPoolTaskScheduler线程池的调用

1.

import java.util.Random;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

import java.util.concurrent.Future;

/**
 * 
 * @author hemingzhhu
 * @version 2018-6-1
 *
 */
@Component
public class Threads {

	@Autowired
	private StringRedisTemplate stringRedisTemplate;
	
	public static Random random = new Random();
	
	Logger log = LoggerFactory.getLogger(Threads.class);

	 @Async("taskExecutor")
	    public void doTaskOne() throws Exception {
	        log.info("开始做任务一");
	        long start = System.currentTimeMillis();
	        log.info(stringRedisTemplate.randomKey());
	        long end = System.currentTimeMillis();
	        log.info("完成任务一,耗时:" + (end - start) + "毫秒");
	    }

	    @Async("taskExecutor")
	    public void doTaskTwo() throws Exception {
	        log.info("开始做任务二");
	        long start = System.currentTimeMillis();
	        log.info(stringRedisTemplate.randomKey());
	        long end = System.currentTimeMillis();
	        log.info("完成任务二,耗时:" + (end - start) + "毫秒");
	    }

	    @Async("taskExecutor")
	    public void doTaskThree() throws Exception {
	        log.info("开始做任务三");
	        long start = System.currentTimeMillis();
	        log.info(stringRedisTemplate.randomKey());
	        long end = System.currentTimeMillis();
	        log.info("完成任务三,耗时:" + (end - start) + "毫秒");
	    }
	
	    
	    @Async("taskExecutor")
	    public Future<String> run1() throws Exception {
	        long sleep = random.nextInt(10000);
	        log.info("开始任务,需耗时:" + sleep + "毫秒");
	        Thread.sleep(sleep);
	        log.info("完成任务");
	        return new AsyncResult<>("test");
	    }
	    @Async("taskExecutor")
	    public Future<String> run2() throws Exception {
	        long sleep = 1000;
	        log.info("开始任务,需耗时:" + sleep + "毫秒");
	        Thread.sleep(sleep);
	        log.info("完成任务");
	        return new AsyncResult<>("test");
	    }
	    
}

2.

import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.thread.util.Threads;

@RestController
public class ThreadController {

	 @Autowired
	    private Threads task;

	   @GetMapping("/aa")
	    public void test() throws Exception {

		   for (int i = 0; i < 50; i++) {
	            task.doTaskOne();
	            task.doTaskTwo();
	            task.doTaskThree();

	            if (i == 9999) {
	                System.exit(0);
	            }
	        }
	    }
	 Logger log = LoggerFactory.getLogger(ThreadController.class);
	 
	 @GetMapping("/bb")
	 public void test() throws Exception {
		 Future<String> futureResult = task.run1();
	     String result = futureResult.get(100, TimeUnit.SECONDS);
	     if(futureResult.isDone()) {
	    	 log.info("我在等待1");
	     }
	     log.info(result);
	     
	     Future<String> futureResult1 = task.run2();
	     String result1 = futureResult1.get(100, TimeUnit.SECONDS);
	     if(futureResult1.isDone()) {
			 log.info("我在等待2"+futureResult1.get());
		 }
	     log.info(result1);
	     
	 }
	
}

3、

 @EnableAsync
	    @Configuration
	    class TaskPoolConfig {

	        @Bean("taskExecutor")
	        public Executor taskExecutor() {
	            ThreadPoolTaskScheduler executor = new ThreadPoolTaskScheduler();
	            executor.setPoolSize(20);
	            executor.setThreadNamePrefix("taskExecutor-");
	            return executor;
	        }

	    }
	 
	 @Bean("taskExecutor")
	 public Executor taskExecutor() {
	     ThreadPoolTaskScheduler executor = new ThreadPoolTaskScheduler();
	     executor.setPoolSize(20);
	     executor.setThreadNamePrefix("taskExecutor-");
	     executor.setWaitForTasksToCompleteOnShutdown(true);
	     executor.setAwaitTerminationSeconds(60);
	     return executor;
	 }
	

 

4.

 

# Redis\u670D\u52A1\u5668\u5730\u5740
spring.redis.host=localhost
# Redis\u670D\u52A1\u5668\u8FDE\u63A5\u7AEF\u53E3
spring.redis.port=6379
# Redis\u670D\u52A1\u5668\u8FDE\u63A5\u5BC6\u7801\uFF08\u9ED8\u8BA4\u4E3A\u7A7A\uFF09
spring.redis.password=
# \u8FDE\u63A5\u8D85\u65F6\u65F6\u95F4\uFF08\u6BEB\u79D2\uFF09
spring.redis.timeout=50000
# \u8FDE\u63A5\u6C60\u6700\u5927\u8FDE\u63A5\u6570\uFF08\u4F7F\u7528\u8D1F\u503C\u8868\u793A\u6CA1\u6709\u9650\u5236\uFF09  
spring.redis.jedis.pool.max-active=8  
# \u8FDE\u63A5\u6C60\u6700\u5927\u963B\u585E\u7B49\u5F85\u65F6\u95F4\uFF08\u4F7F\u7528\u8D1F\u503C\u8868\u793A\u6CA1\u6709\u9650\u5236\uFF09  
spring.redis.jedis.pool.max-wait=-1  
# \u8FDE\u63A5\u6C60\u4E2D\u7684\u6700\u5927\u7A7A\u95F2\u8FDE\u63A5  
spring.redis.jedis.pool.max-idle=8  
# \u8FDE\u63A5\u6C60\u4E2D\u7684\u6700\u5C0F\u7A7A\u95F2\u8FDE\u63A5  
spring.redis.jedis.pool.min-idle=0  

 

 

 

 

 

 

Spring Boot提供了对线程池集成和支持,可以方便地使用线程池来处理并发任务。下面是使用Spring Boot线程池的基本步骤: 1. 导入依赖:在pom.xml文件中添加Spring Boot对线程池的依赖。例如,对于基于Java的应用,可以添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-async</artifactId> </dependency> ``` 2. 配置线程池:在Spring Boot的配置文件(如application.properties或application.yml)中配置线程池的相关属性。例如,可以配置线程池的核心线程数、最大线程数、队列容量等。以下是一个示例配置: ```properties # 线程池配置 spring.task.execution.pool.core-size=10 spring.task.execution.pool.max-size=20 spring.task.execution.pool.queue-capacity=100 ``` 3. 创建异步方法:在Spring Boot应用中创建一个需要异步执行的方法,并使用`@Async`注解标记该方法。例如: ```java @Service public class MyService { @Async public CompletableFuture<String> asyncMethod() { // 异步执行的方法逻辑 return CompletableFuture.completedFuture("异步方法执行完成"); } } ``` 4. 调用异步方法:在需要调用异步方法的地方,直接调用即可。Spring Boot会自动将方法转化为异步执行。例如: ```java @RestController public class MyController { @Autowired private MyService myService; @GetMapping("/async") public String executeAsyncMethod() { CompletableFuture<String> futureResult = myService.asyncMethod(); // 异步方法返回的是一个CompletableFuture对象,可以通过该对象获取异步方法的执行结果 return "异步方法已启动"; } } ``` 这样,通过以上步骤,你就可以在Spring Boot中使用线程池来处理并发任务了。希望对你有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值