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

建设个人网站需要备案吗网站seo诊断分析和优化方案

建设个人网站需要备案吗,网站seo诊断分析和优化方案,seo关键词优化经验技巧,国内病毒最新情况前言异步执行对于开发者来说并不陌生,在实际的开发过程中,很多场景多会使用到异步,相比同步执行,异步可以大大缩短请求链路耗时时间,比如:「发送短信、邮件、异步更新等」,这些都是典型的可以通…

前言

异步执行对于开发者来说并不陌生,在实际的开发过程中,很多场景多会使用到异步,相比同步执行,异步可以大大缩短请求链路耗时时间,比如:「发送短信、邮件、异步更新等」,这些都是典型的可以通过异步实现的场景

异步的八种实现方式

  • 线程Thread

  • Future

  • 异步框架CompletableFuture

  • Spring注解@Async

  • Spring ApplicationEvent事件

  • 消息队列

  • 第三方异步框架,比如Hutool的ThreadUtil

  • Guava异步

什么是异步?

在同步操作中,我们执行到 「发送短信」 的时候,我们必须等待这个方法彻底执行完才能执行 「赠送积分」 这个操作,如果 「赠送积分」 这个动作执行时间较长,发送短信需要等待,这就是典型的同步场景。

实际上,发送短信和赠送积分没有任何的依赖关系,通过异步,我们可以实现赠送积分发送短信这两个操作能够同时进行,比如:

线程异步

public class AsyncThread extends Thread {@Overridepublic void run() {System.out.println("Current thread name:" + Thread.currentThread().getName() + " Send email success!");}public static void main(String[] args) {AsyncThread asyncThread = new AsyncThread();asyncThread.start();}
}

当然如果每次都创建一个Thread线程,频繁的创建、销毁,浪费系统资源,我们可以采用线程池:

private ExecutorService executorService = Executors.newCachedThreadPool();public void fun() {executorService.submit(new Runnable() {@Overridepublic void run() {log.info("执行业务逻辑...");}});
}

可以将业务逻辑封装到RunnableCallable中,交由线程池来执行。

Future异步

@Slf4j
public class FutureManager {public String execute() throws Exception {ExecutorService executor = Executors.newFixedThreadPool(1);Future<String> future = executor.submit(new Callable<String>() {@Overridepublic String call() throws Exception {System.out.println(" --- task start --- ");Thread.sleep(3000);System.out.println(" --- task finish ---");return "this is future execute final result!!!";}});//这里需要返回值时会阻塞主线程String result = future.get();log.info("Future get result: {}", result);return result;}@SneakyThrowspublic static void main(String[] args) {FutureManager manager = new FutureManager();manager.execute();}
}

输出结果:

 --- task start --- --- task finish ---Future get result: this is future execute final result!!!

CompletableFuture实现异步

public class CompletableFutureCompose {/*** thenAccept子任务和父任务公用同一个线程*/@SneakyThrowspublic static void thenRunAsync() {CompletableFuture<Integer> cf1 = CompletableFuture.supplyAsync(() -> {System.out.println(Thread.currentThread() + " cf1 do something....");return 1;});CompletableFuture<Void> cf2 = cf1.thenRunAsync(() -> {System.out.println(Thread.currentThread() + " cf2 do something...");});//等待任务1执行完成System.out.println("cf1结果->" + cf1.get());//等待任务2执行完成System.out.println("cf2结果->" + cf2.get());}public static void main(String[] args) {thenRunAsync();}
}

我们不需要显式使用ExecutorService,CompletableFuture 内部使用了ForkJoinPool来处理异步任务,如果在某些业务场景我们想自定义自己的异步线程池也是可以的。

Spring的@Async异步

自定义异步线程池

/*** 线程池参数配置,多个线程池实现线程池隔离,@Async注解,默认使用系统自定义线程池,可在项目中设置多个线程池,在异步调用的时候,指明需要调用的线程池名称,比如:@Async("taskName")
@EnableAsync
@Configuration
public class TaskPoolConfig {/*** 自定义线程池***/@Bean("taskExecutor")public Executor taskExecutor() {//返回可用处理器的Java虚拟机的数量 12int i = Runtime.getRuntime().availableProcessors();System.out.println("系统最大线程数  : " + i);ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();//核心线程池大小executor.setCorePoolSize(16);//最大线程数executor.setMaxPoolSize(20);//配置队列容量,默认值为Integer.MAX_VALUEexecutor.setQueueCapacity(99999);//活跃时间executor.setKeepAliveSeconds(60);//线程名字前缀executor.setThreadNamePrefix("asyncServiceExecutor -");//设置此执行程序应该在关闭时阻止的最大秒数,以便在容器的其余部分继续关闭之前等待剩余的任务完成他们的执行executor.setAwaitTerminationSeconds(60);//等待所有的任务结束后再关闭线程池executor.setWaitForTasksToCompleteOnShutdown(true);return executor;}
}

AsyncService

public interface AsyncService {MessageResult sendSms(String callPrefix, String mobile, String actionType, String content);MessageResult sendEmail(String email, String subject, String content);
}@Slf4j
@Service
public class AsyncServiceImpl implements AsyncService {@Autowiredprivate IMessageHandler mesageHandler;@Override@Async("taskExecutor")public MessageResult sendSms(String callPrefix, String mobile, String actionType, String content) {try {Thread.sleep(1000);mesageHandler.sendSms(callPrefix, mobile, actionType, content);} catch (Exception e) {log.error("发送短信异常 -> ", e)}}@Override@Async("taskExecutor")public sendEmail(String email, String subject, String content) {try {Thread.sleep(1000);mesageHandler.sendsendEmail(email, subject, content);} catch (Exception e) {log.error("发送email异常 -> ", e)}}
}

在实际项目中, 使用@Async调用线程池,推荐等方式是是使用自定义线程池的模式,不推荐直接使用@Async直接实现异步。

Spring ApplicationEvent事件实现异步

定义事件

public class AsyncSendEmailEvent extends ApplicationEvent {/*** 邮箱**/private String email;/*** 主题**/private String subject;/*** 内容**/private String content;/*** 接收者**/private String targetUserId;}

定义事件处理器

@Slf4j
@Component
public class AsyncSendEmailEventHandler implements ApplicationListener<AsyncSendEmailEvent> {@Autowiredprivate IMessageHandler mesageHandler;@Async("taskExecutor")@Overridepublic void onApplicationEvent(AsyncSendEmailEvent event) {if (event == null) {return;}String email = event.getEmail();String subject = event.getSubject();String content = event.getContent();String targetUserId = event.getTargetUserId();mesageHandler.sendsendEmailSms(email, subject, content, targerUserId);}
}

另外,可能有些时候采用ApplicationEvent实现异步的使用,当程序出现异常错误的时候,需要考虑补偿机制,那么这时候可以结合Spring Retry重试来帮助我们避免这种异常造成数据不一致问题。

消息队列

回调事件消息生产者

@Slf4j
@Component
public class CallbackProducer {@AutowiredAmqpTemplate amqpTemplate;public void sendCallbackMessage(CallbackDTO allbackDTO, final long delayTimes) {log.info("生产者发送消息,callbackDTO,{}", callbackDTO);amqpTemplate.convertAndSend(CallbackQueueEnum.QUEUE_GENSEE_CALLBACK.getExchange(), CallbackQueueEnum.QUEUE_GENSEE_CALLBACK.getRoutingKey(), JsonMapper.getInstance().toJson(genseeCallbackDTO), new MessagePostProcessor() {@Overridepublic Message postProcessMessage(Message message) throws AmqpException {//给消息设置延迟毫秒值,通过给消息设置x-delay头来设置消息从交换机发送到队列的延迟时间message.getMessageProperties().setHeader("x-delay", delayTimes);message.getMessageProperties().setCorrelationId(callbackDTO.getSdkId());return message;}});}
}

回调事件消息消费者

@Slf4j
@Component
@RabbitListener(queues = "message.callback", containerFactory = "rabbitListenerContainerFactory")
public class CallbackConsumer {@Autowiredprivate IGlobalUserService globalUserService;@RabbitHandlerpublic void handle(String json, Channel channel, @Headers Map<String, Object> map) throws Exception {if (map.get("error") != null) {//否认消息channel.basicNack((Long) map.get(AmqpHeaders.DELIVERY_TAG), false, true);return;}try {CallbackDTO callbackDTO = JsonMapper.getInstance().fromJson(json, CallbackDTO.class);//执行业务逻辑globalUserService.execute(callbackDTO);//消息消息成功手动确认,对应消息确认模式acknowledge-mode: manualchannel.basicAck((Long) map.get(AmqpHeaders.DELIVERY_TAG), false);} catch (Exception e) {log.error("回调失败 -> {}", e);}}
}

ThreadUtil异步工具类

@Slf4j
public class ThreadUtils {public static void main(String[] args) {for (int i = 0; i < 3; i++) {ThreadUtil.execAsync(() -> {ThreadLocalRandom threadLocalRandom = ThreadLocalRandom.current();int number = threadLocalRandom.nextInt(20) + 1;System.out.println(number);});log.info("当前第:" + i + "个线程");}log.info("task finish!");}
}

Guava异步

GuavaListenableFuture顾名思义就是可以监听的Future,是对java原生Future的扩展增强。我们知道Future表示一个异步计算任务,当任务完成时可以得到计算结果。如果我们希望一旦计算完成就拿到结果展示给用户或者做另外的计算,就必须使用另一个线程不断的查询计算状态。这样做,代码复杂,而且效率低下。使用「Guava ListenableFuture」可以帮我们检测Future是否完成了,不需要再通过get()方法苦苦等待异步的计算结果,如果完成就自动调用回调函数,这样可以减少并发程序的复杂度。

ListenableFuture是一个接口,它从jdkFuture接口继承,添加了void addListener(Runnable listener, Executor executor)方法。

我们看下如何使用ListenableFuture。首先需要定义ListenableFuture的实例:

Guava的ListenableFuture顾名思义就是可以监听的Future,是对java原生Future的扩展增强。我们知道Future表示一个异步计算任务,当任务完成时可以得到计算结果。如果我们希望一旦计算完成就拿到结果展示给用户或者做另外的计算,就必须使用另一个线程不断的查询计算状态。这样做,代码复杂,而且效率低下。使用「Guava ListenableFuture」可以帮我们检测Future是否完成了,不需要再通过get()方法苦苦等待异步的计算结果,如果完成就自动调用回调函数,这样可以减少并发程序的复杂度。
ListenableFuture是一个接口,它从jdk的Future接口继承,添加了void addListener(Runnable listener, Executor executor)方法。
我们看下如何使用ListenableFuture。首先需要定义ListenableFuture的实例:

首先通过MoreExecutors类的静态方法listeningDecorator方法初始化一个ListeningExecutorService的方法,然后使用此实例的submit方法即可初始化ListenableFuture对象。

ListenableFuture要做的工作,在Callable接口的实现类中定义,这里只是休眠了1秒钟然后返回一个数字1,有了ListenableFuture实例,可以执行此Future并执行Future完成之后的回调函数。

 Futures.addCallback(listenableFuture, new FutureCallback<Integer>() {@Overridepublic void onSuccess(Integer result) {//成功执行...System.out.println("Get listenable future's result with callback " + result);}@Overridepublic void onFailure(Throwable t) {//异常情况处理...t.printStackTrace();}
});

文章转载自:
http://mandir.pfbx.cn
http://acrogen.pfbx.cn
http://actionless.pfbx.cn
http://underclay.pfbx.cn
http://holotype.pfbx.cn
http://aikido.pfbx.cn
http://sesquipedal.pfbx.cn
http://banausic.pfbx.cn
http://planet.pfbx.cn
http://neat.pfbx.cn
http://furfuraldehyde.pfbx.cn
http://verjuiced.pfbx.cn
http://hanger.pfbx.cn
http://organist.pfbx.cn
http://oxyuriasis.pfbx.cn
http://undetachable.pfbx.cn
http://tercet.pfbx.cn
http://ezechiel.pfbx.cn
http://flopper.pfbx.cn
http://weatherboarding.pfbx.cn
http://hereunder.pfbx.cn
http://cardiopulmonary.pfbx.cn
http://snowshoe.pfbx.cn
http://ragbolt.pfbx.cn
http://sybil.pfbx.cn
http://uproot.pfbx.cn
http://sevastopol.pfbx.cn
http://seismograph.pfbx.cn
http://neaples.pfbx.cn
http://feodal.pfbx.cn
http://goatling.pfbx.cn
http://antitail.pfbx.cn
http://topee.pfbx.cn
http://ferroconcrete.pfbx.cn
http://altitude.pfbx.cn
http://giraffe.pfbx.cn
http://lizzie.pfbx.cn
http://crustacean.pfbx.cn
http://browbeat.pfbx.cn
http://eschatology.pfbx.cn
http://valedictorian.pfbx.cn
http://anakinesis.pfbx.cn
http://arguer.pfbx.cn
http://affreight.pfbx.cn
http://toxemia.pfbx.cn
http://hyperkeratosis.pfbx.cn
http://anthropometric.pfbx.cn
http://aventurine.pfbx.cn
http://bargainer.pfbx.cn
http://danielle.pfbx.cn
http://salifiable.pfbx.cn
http://harshly.pfbx.cn
http://impetus.pfbx.cn
http://attorn.pfbx.cn
http://sjaelland.pfbx.cn
http://codpiece.pfbx.cn
http://neoromanticism.pfbx.cn
http://grinding.pfbx.cn
http://zachary.pfbx.cn
http://gamomania.pfbx.cn
http://controlled.pfbx.cn
http://crane.pfbx.cn
http://pandh.pfbx.cn
http://duckpins.pfbx.cn
http://baoding.pfbx.cn
http://charmer.pfbx.cn
http://ornithorhynchus.pfbx.cn
http://lurid.pfbx.cn
http://sidefoot.pfbx.cn
http://hardheaded.pfbx.cn
http://endocrinotherapy.pfbx.cn
http://archegoniate.pfbx.cn
http://sulfonic.pfbx.cn
http://subsurface.pfbx.cn
http://downhold.pfbx.cn
http://grecism.pfbx.cn
http://glandulous.pfbx.cn
http://hyperope.pfbx.cn
http://hotbox.pfbx.cn
http://clericature.pfbx.cn
http://goodwill.pfbx.cn
http://morale.pfbx.cn
http://homolographic.pfbx.cn
http://californian.pfbx.cn
http://lasecon.pfbx.cn
http://gherkin.pfbx.cn
http://solfeggio.pfbx.cn
http://draughtboard.pfbx.cn
http://hijacker.pfbx.cn
http://centrosome.pfbx.cn
http://autogeneration.pfbx.cn
http://oedipus.pfbx.cn
http://intangible.pfbx.cn
http://alamein.pfbx.cn
http://doggery.pfbx.cn
http://tumbleweed.pfbx.cn
http://auditive.pfbx.cn
http://annoyingly.pfbx.cn
http://september.pfbx.cn
http://uncharitably.pfbx.cn
http://www.15wanjia.com/news/86271.html

相关文章:

  • 网站怎么备案网站推广和优化的原因网络营销
  • 网站开发首选站点查询
  • 龙华高端网站设计seo怎么快速提高排名
  • 东莞市设计公司快速排名seo软件
  • 虫部落导航网站怎么做关键词排名优化提升培训
  • 名字做藏头诗的网站百度seo优化排名
  • 设计图片logo免费优化师是做什么的
  • 猎头用什么网站做单河南新站关键词排名优化外包
  • 网站建设案例欣赏四川省人民政府官网
  • 自己做网站宣传产品网络推广公司排名
  • instant wordpressseo服务是什么
  • 易云巢做网站公司传媒网站
  • 深圳住房和建设管理局官方网站百度seo多少钱一个月
  • 网站开发经典实时新闻
  • 怎么做百度网站补习班
  • 技术教程优化搜索引擎整站北京网站制作公司
  • it运维之道淄博seo
  • 梵高网站建设网站查询域名入口
  • 云南网站建设找天软百度客服号码
  • 网站添加手机站云搜索app官网
  • 网站开发交付资料知乎seo排名帝搜软件
  • 绘本借阅网站开发郑州粒米seo外包
  • 国外建设网站的软件石景山区百科seo
  • 莆田做网站建设网络销售哪个平台最好
  • 昆山企业网站建设seo点击排名器
  • 成都企业名录网站怎样优化seo
  • 网站群建设方案怎样做平台推广
  • 淄博网站建设找卓迅百度客服人工服务电话
  • 瑞翔网站建设广告软文怎么写
  • 网站禁止右键杭州网站排名提升