当前位置: 首页> 娱乐> 影视 > 网络空间安全和信息安全的区别_html5动态网页代码_网站流量数据分析_竞价托管外包公司

网络空间安全和信息安全的区别_html5动态网页代码_网站流量数据分析_竞价托管外包公司

时间:2025/7/19 6:02:59来源:https://blog.csdn.net/fokman/article/details/144715487 浏览次数:0次
网络空间安全和信息安全的区别_html5动态网页代码_网站流量数据分析_竞价托管外包公司

在使用 SpringBoot  开发多线程应用程序时,遵循最佳实践可以确保应用的高效性、可维护性和稳定性。以下是 SpringBoot  中实现多线程的最佳实践:

1. 使用 @Async 注解

Spring 提供了简单的异步方法执行功能,通过 @Async 注解可以轻松实现异步调用。

  • 配置异步支持:在主类或配置类中添加 @EnableAsync 注解以启用异步支持。
  • 定义异步方法:在需要异步执行的方法上添加 @Async 注解。

2. 配置线程池

默认情况下,@Async 使用的是一个简单线程池,但为了更好地控制性能和资源,建议自定义线程池配置。

  • 创建自定义线程池:通过 ThreadPoolTaskExecutor 或 ThreadPoolTaskScheduler 来配置线程池参数。

3. 处理异常

异步方法中的异常不会自动传播到调用方,因此需要特别处理。

  • 使用 CompletableFuture:返回 CompletableFuture 对象,可以在调用方捕获异常。
  • 全局异常处理:实现 AsyncUncaughtExceptionHandler 接口来处理未捕获的异常。

4. 避免阻塞操作

尽量避免在异步方法中进行长时间的阻塞操作(如 I/O 操作),因为这会占用线程资源,影响整体性能。

  • 使用非阻塞 API:例如,使用 WebClient 替代 RestTemplate 进行 HTTP 请求。
  • 结合 Reactor 或 RxJava:利用响应式编程模型来处理异步流数据。

5. 合理设置线程池大小

根据应用的具体需求和服务器硬件资源,合理配置线程池的核心池大小、最大池大小和队列容量,避免过多线程导致资源耗尽或过少线程造成瓶颈。

结合上面的步骤我们写个简单的示例

示例

service

package com.coderlk.mutil.thread;import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;import java.util.Random;
import java.util.concurrent.CompletableFuture;@Slf4j
@Service
public class OrderAsyncService {@Async("dataMigratePool")@SneakyThrowspublic void dataMigrate(String order, String message){Thread.sleep(new Random().nextInt(2000));log.info("The data has migrate to {} successfully .The Order message is {}.",order,message);}@Async("dataMigratePool")@SneakyThrowspublic CompletableFuture<String> blockDataMigrate(String order, String message){Thread.sleep(new Random().nextInt(2000));log.info("The order {} has been migrate successfully sent.The message is {}.",order,message);return CompletableFuture.completedFuture("The order :" + order + " has been successfully migrated." +"The Order message is " + message + ".");}
}

线程池配置

package com.coderlk.mutil.thread;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;@Configuration
@EnableAsync
public class AsyncConfiguration {//定义数据迁移线程池@Bean("dataMigratePool")public Executor dataMigrate() {ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();// 初始化的线程数executor.setCorePoolSize(10);// 线程池最大的线程数,如果在缓冲队列满了就会才会申请超过核心线程数的线程executor.setMaxPoolSize(20);// 用来缓冲执行任务的队列executor.setQueueCapacity(500);// 允许线程的空闲时间60秒,如果超过了核心线程之外的线程在空闲时间到达之后会被销毁executor.setKeepAliveSeconds(60);// 线程池名的前缀:设置好了之后可以方便我们定位处理任务所在的线程池executor.setThreadNamePrefix("data-migrate-pool");// 缓冲队列满了之后的拒绝策略,由调用线程处理(主线程)executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());executor.initialize();return executor;}}

controller

package com.coderlk.mutil.thread;import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.CompletableFuture;@RestController
@Slf4j
public class AsyncController {@Resourceprivate OrderAsyncService orderAsyncService;/*** 订单数据迁移* @return*/@GetMapping("/dataMigrate")@SneakyThrowspublic String dataMigrate() {String[] orders = new String[]{"order-10001", "order-10002", "order-10003", "order-10004", "order-10005"};for(int i = 0 ; i < orders.length ; i++) {orderAsyncService.dataMigrate(orders[i], "Order data Sample");};return "OK";}@GetMapping("/blockDataMigrate")@SneakyThrowspublic String blockDataMigrate() {CompletableFuture<String>[] futures = new CompletableFuture[5];String[] orders = new String[]{"order-10001", "order-10002", "order-10003", "order-10004", "order-10005"};for(int i = 0 ; i < orders.length ; i++) {futures[i] = orderAsyncService.blockDataMigrate(orders[i], "Block order Sample");};//阻塞等待所有CompletableFuture响应结果CompletableFuture.allOf(futures);StringBuffer sb = new StringBuffer();for(int i = 0 ; i < futures.length ; i++){try {sb.append(futures[i].get() + "\n");} catch (Exception e) {throw new RuntimeException(e);}}return sb.toString();}
}

启动

package com.coderlk.mutil.thread;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class AsyncMethodApplication {public static void main(String[] args) {SpringApplication.run(AsyncMethodApplication.class, args);}}

测试

GET http://localhost:8080/dataMigrate
2024-12-25T13:39:36.887+08:00  INFO 55926 --- [a-migrate-pool2] c.c.mutil.thread.OrderAsyncService       : The data has migrate to order-10002 successfully .The Order message is Order data Sample.
2024-12-25T13:39:37.130+08:00  INFO 55926 --- [a-migrate-pool5] c.c.mutil.thread.OrderAsyncService       : The data has migrate to order-10005 successfully .The Order message is Order data Sample.
2024-12-25T13:39:37.300+08:00  INFO 55926 --- [a-migrate-pool3] c.c.mutil.thread.OrderAsyncService       : The data has migrate to order-10003 successfully .The Order message is Order data Sample.
2024-12-25T13:39:38.252+08:00  INFO 55926 --- [a-migrate-pool1] c.c.mutil.thread.OrderAsyncService       : The data has migrate to order-10001 successfully .The Order message is Order data Sample.
2024-12-25T13:39:38.403+08:00  INFO 55926 --- [a-migrate-pool4] c.c.mutil.thread.OrderAsyncService       : The data has migrate to order-10004 successfully .The Order message is Order data Sample.

关键字:网络空间安全和信息安全的区别_html5动态网页代码_网站流量数据分析_竞价托管外包公司

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: