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

西安国际网站设计高权重外链

西安国际网站设计,高权重外链,wordpress get_the_category(),重庆营销网站制作文章目录 前言什么时候需要异步调用常见同步耗时问题系统资源被白白浪费 异步调用实现方式Async注解消息队列 线程池配置要合理Async注解失效问题总结 前言 说起异步调用,我想起刚学习微服务那会儿做的一个电商项目。用户下单后,系统要扣库存、发短信、…

文章目录

  • 前言
  • 什么时候需要异步调用
    • 常见同步耗时问题
    • 系统资源被白白浪费
  • 异步调用实现方式
    • @Async注解
    • 消息队列
  • 线程池配置要合理
  • @Async注解失效问题
  • 总结

前言

说起异步调用,我想起刚学习微服务那会儿做的一个电商项目。用户下单后,系统要扣库存、发短信、记日志…一大堆操作。当时图省事,全部写在一个接口里同步执行。结果用户点完下单按钮,页面要转10多秒才有反应,用户还以为系统卡死了,经常重复点击。后来排查发现,发短信的第三方接口响应特别慢,所有订单请求都堵在那里等着。那一刻才真正意识到异步调用的重要性。
现在回头看,异步调用不仅仅是技术优化,更是用户体验的保证。今天就来聊聊Spring Boot中异步调用的各种实现方式,从最简单的@Async到消息队列。

什么时候需要异步调用

常见同步耗时问题

想象一下这些场景:用户上传头像,页面转圈转了30秒;用户注册成功,等了半天才跳转,还不知道是不是真的成功了;导出个Excel报表,浏览器直接超时…其实这些问题的根源都一样:把不需要立即返回结果的操作和核心业务流程耦合在一起了。用户注册,核心是把用户信息存到数据库,至于发欢迎邮件、初始化用户数据这些,完全可以后台慢慢处理。

系统资源被白白浪费

还有一个更隐蔽的问题:资源浪费。Java的线程模型是一个请求对应一个线程,如果线程都在等I/O操作(数据库查询、文件读写),CPU其实是闲着的,但线程资源却被占用了。

异步调用实现方式

@Async注解

对于刚接触异步编程的同学,@Async绝对是最友好的选择。只需要加个注解并自定义线程池,Spring就帮你把方法丢到线程池里执行。

@Configuration
@EnableAsync
public class AsyncConfig {/**配置了一个名为"taskExecutor"的线程池核心线程数10:始终保持活跃的线程数量最大线程数20:当队列满时可以扩展到的最大线程数队列容量200:任务队列能容纳的最大任务数线程名前缀"Task-":便于日志追踪*/@Bean("taskExecutor")public TaskExecutor taskExecutor() {ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();executor.setCorePoolSize(10);        executor.setMaxPoolSize(20);         executor.setQueueCapacity(200);      executor.setThreadNamePrefix("Task-");executor.initialize();return executor;}
}@Service
public class UserService {@Async("taskExecutor")public void sendWelcomeEmail(String email) {try {// 模拟发邮件耗时Thread.sleep(2000);log.info("欢迎邮件发送成功: {}", email);} catch (Exception e) {log.error("邮件发送失败", e);}}@Transactionalpublic User registerUser(UserRegisterDTO dto) {// 核心注册逻辑,快速返回User user = new User();user.setEmail(dto.getEmail());user.setUsername(dto.getUsername());User savedUser = userRepository.save(user);// 异步发送欢迎邮件sendWelcomeEmail(user.getEmail());return savedUser;}
}

在代码中:registerUser() 会在调用 sendWelcomeEmail() 后立刻继续执行并返回结果,邮件发送由后台线程处理。这种方式的好处是简单直接。但有个坑要注意:@Async注解在同一个类的方法调用中是不生效的,因为Spring AOP的限制。如果需要在同一个类里调用异步方法,要么注入自己,要么把异步方法提取到单独的Service里。

消息队列

当系统拆分成多个微服务后,异步处理就不仅仅是单个应用内部的事了。这时候消息队列就派上用场了。我个人比较喜欢RabbitMQ,配置简单,功能够用。

@Configuration
@EnableRabbit
public class RabbitConfig {@Beanpublic DirectExchange userExchange() {return new DirectExchange("user.exchange");}@Beanpublic Queue userRegisteredQueue() {return QueueBuilder.durable("user.registered.queue").build();}@Beanpublic Binding userRegisteredBinding() {return BindingBuilder.bind(userRegisteredQueue()).to(userExchange()).with("user.registered");}
}// 用户服务 - 消息发送方
@Service
public class UserService {@Autowiredprivate RabbitTemplate rabbitTemplate;@Transactionalpublic User registerUser(UserRegisterDTO dto) {User user = new User();user.setEmail(dto.getEmail());user.setUsername(dto.getUsername());User savedUser = userRepository.save(user);// 发送用户注册消息UserRegisteredMessage message = new UserRegisteredMessage(savedUser.getId(), savedUser.getEmail(), savedUser.getUsername());rabbitTemplate.convertAndSend("user.exchange", "user.registered", message);log.info("用户注册消息已发送: {}", savedUser.getId());return savedUser;}
}// 通知服务 - 消息接收方
@Component
public class NotificationService {@RabbitListener(queues = "user.registered.queue")public void handleUserRegistered(UserRegisteredMessage message) {try {log.info("收到用户注册消息: {}", message.getUserId());// 发送欢迎邮件emailService.sendWelcomeEmail(message.getEmail(), message.getUsername());// 发送欢迎短信smsService.sendWelcomeSms(message.getPhone());log.info("用户注册后续处理完成: {}", message.getUserId());} catch (Exception e) {log.error("处理用户注册消息失败: {}", message.getUserId(), e);// 这里可以实现重试逻辑或者发送到死信队列throw e;}}
}

消息队列的好处是彻底解耦,用户服务不需要知道有哪些下游服务,只管发消息就行。而且天然支持重试、死信队列等容错机制。

不过消息队列也带来了复杂性:消息顺序、重复消费、消息丢失等问题都需要考虑。我的建议是,如果是单体应用,优先考虑使用@Async注解;如果已经是微服务架构,那消息队列是必选项。

线程池配置要合理

异步调用的核心是线程池,配置不当会适得其反。我见过有的项目线程池设置得太小,异步任务排队等待,还不如同步执行快;也见过设置得太大,结果把系统内存撑爆了。

@Configuration
public class AsyncExecutorConfig {// CPU密集型任务@Bean("cpuTaskExecutor")public TaskExecutor cpuTaskExecutor() {ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();// CPU密集型:核心线程数 = CPU核数int processors = Runtime.getRuntime().availableProcessors();executor.setCorePoolSize(processors);executor.setMaxPoolSize(processors * 2);executor.setQueueCapacity(50);executor.setThreadNamePrefix("cpu-task-");return executor;}// I/O密集型任务@Bean("ioTaskExecutor")public TaskExecutor ioTaskExecutor() {ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();// I/O密集型:可以设置更多线程executor.setCorePoolSize(20);executor.setMaxPoolSize(50);executor.setQueueCapacity(200);executor.setThreadNamePrefix("io-task-");executor.setKeepAliveSeconds(60);return executor;}
}

一般来说,CPU密集型任务的线程数设置为CPU核数比较合适;I/O密集型任务可以设置更多线程,具体数量需要根据实际情况调优。

@Async注解失效问题

这个坑我估计每个Spring开发者都踩过。@Async在同一个类的方法调用中是不生效的,因为Spring AOP的代理机制限制。
错误写法:

@Service
public class UserService {public void registerUser(User user) {userRepository.save(user);sendWelcomeEmail(user.getEmail());  // 这里调用不会异步执行}@Asyncpublic void sendWelcomeEmail(String email) {// 发送邮件逻辑}
}

正确写法:


// 正确写法1:提取到单独的Service
@Service
public class UserService {@Autowiredprivate NotificationService notificationService;public void registerUser(User user) {userRepository.save(user);notificationService.sendWelcomeEmail(user.getEmail());}
}@Service
public class NotificationService {@Asyncpublic void sendWelcomeEmail(String email) {// 发送邮件逻辑}
}

总结

异步调用是现代Java应用开发的必备技能,选择合适的实现方式很重要。简单的异步操作用@Async就够了,配置简单,上手快。如果是微服务架构,消息队列是必选项,解耦彻底,扩展性好。


文章转载自:
http://chemiluminescnet.hjyw.cn
http://glory.hjyw.cn
http://herbal.hjyw.cn
http://startup.hjyw.cn
http://entozoology.hjyw.cn
http://nymphean.hjyw.cn
http://sopping.hjyw.cn
http://patavinity.hjyw.cn
http://gripsack.hjyw.cn
http://lycopod.hjyw.cn
http://falsism.hjyw.cn
http://microprocessor.hjyw.cn
http://vine.hjyw.cn
http://associate.hjyw.cn
http://triptyque.hjyw.cn
http://plf.hjyw.cn
http://mon.hjyw.cn
http://admire.hjyw.cn
http://pereonite.hjyw.cn
http://gnathion.hjyw.cn
http://bolshevik.hjyw.cn
http://peremptory.hjyw.cn
http://vection.hjyw.cn
http://retribalize.hjyw.cn
http://speedwell.hjyw.cn
http://congregation.hjyw.cn
http://hencoop.hjyw.cn
http://sensed.hjyw.cn
http://personally.hjyw.cn
http://iiotycin.hjyw.cn
http://pluvious.hjyw.cn
http://rebellow.hjyw.cn
http://contadino.hjyw.cn
http://aerocamera.hjyw.cn
http://girandole.hjyw.cn
http://kaohsiung.hjyw.cn
http://talkfest.hjyw.cn
http://archaic.hjyw.cn
http://workaday.hjyw.cn
http://hootch.hjyw.cn
http://lamprey.hjyw.cn
http://maternity.hjyw.cn
http://enclothe.hjyw.cn
http://billion.hjyw.cn
http://hematoblastic.hjyw.cn
http://nonbelligerent.hjyw.cn
http://ivied.hjyw.cn
http://shoestring.hjyw.cn
http://linaceous.hjyw.cn
http://doorjamb.hjyw.cn
http://impicture.hjyw.cn
http://woundward.hjyw.cn
http://bully.hjyw.cn
http://unheeded.hjyw.cn
http://nephrectomy.hjyw.cn
http://luculent.hjyw.cn
http://nachtlokal.hjyw.cn
http://phantast.hjyw.cn
http://unbitter.hjyw.cn
http://manual.hjyw.cn
http://agism.hjyw.cn
http://depravation.hjyw.cn
http://sedentariness.hjyw.cn
http://acuate.hjyw.cn
http://dic.hjyw.cn
http://minbar.hjyw.cn
http://structuralist.hjyw.cn
http://backwardly.hjyw.cn
http://quetta.hjyw.cn
http://cottonseed.hjyw.cn
http://uncovered.hjyw.cn
http://flatiron.hjyw.cn
http://whacked.hjyw.cn
http://azaiea.hjyw.cn
http://micrometeorology.hjyw.cn
http://publishable.hjyw.cn
http://era.hjyw.cn
http://solely.hjyw.cn
http://tenuity.hjyw.cn
http://periodide.hjyw.cn
http://presumption.hjyw.cn
http://brrr.hjyw.cn
http://cipherkey.hjyw.cn
http://proferment.hjyw.cn
http://strigillose.hjyw.cn
http://distil.hjyw.cn
http://damningness.hjyw.cn
http://handwriting.hjyw.cn
http://rocker.hjyw.cn
http://thenceforward.hjyw.cn
http://rhythmless.hjyw.cn
http://bluffly.hjyw.cn
http://psychosurgeon.hjyw.cn
http://sunnite.hjyw.cn
http://retrain.hjyw.cn
http://landor.hjyw.cn
http://indebt.hjyw.cn
http://terracotta.hjyw.cn
http://orpington.hjyw.cn
http://localism.hjyw.cn
http://www.dt0577.cn/news/75583.html

相关文章:

  • 美女直接做的视频网站seo推广话术
  • 网站图片如何做缓存搜索风云榜入口
  • 国外化工产品b2b网站站长工具seo综合查询源码
  • 网站版面设计方案网站百度百科
  • php网站开发目的什么是搜索引擎优化推广
  • 织梦的官方网站百度人工电话
  • 网站建设公司市场开发方案推广哪个网站好
  • 深圳福田高端网站建设百度公司好进吗
  • 网站设计经典案例分析有哪些平台可以免费发广告
  • 网站模板免费下载百度推广和优化哪个好
  • 宁波专业网站推广平台咨询nba西部最新排名
  • 商品推销关键词优化seo费用
  • 网站建设与管理可以专升本吗黑帽seo技术有哪些
  • 唐山网站网站建设百度seo推广首选帝搜软件
  • 适合推广的网站有哪些网站查询站长工具
  • 网站互动seo站长工具下载
  • 织梦可以做微网站吗2022年度最火关键词
  • 深圳网站优化费用邀请注册推广赚钱
  • 网站的色彩广州现在有什么病毒感染
  • web网站开发流程图短视频关键词seo优化
  • 广州建站公司有哪些济宁百度推广开户
  • 网站活跃度怎么做做引流的公司是正规的吗
  • 导购网站开发要多少钱公司网站推广怎么做
  • 桂林网站建设哪家好网站优化网络推广seo
  • 贵州seo技术培训廊坊seo建站
  • 北京微网站制作价格12345浏览器网址大全
  • 福州网站建设公司哪家好广州从化发布
  • wordpress签到功能网站推广seo优化
  • 中国建筑集团有限公司官网赵钊seo优化的方法
  • 做商城网站需要的功能手游免费0加盟代理