编程语言
首页 > 编程语言> > 宇智波程序笔记65-Spring的@Async注解

宇智波程序笔记65-Spring的@Async注解

作者:互联网

背景

你可能在你的项目中用过Spring的@Async注解,以此来将部分方法转化为异步执行,从而提高请求的响应效率

但在服务架构不断的演进之中,这种丢入线程池处理的方式带来的缺陷也愈发明显:

思路

使用消息队列作为异步任务的实现方式,这样我们就可以:

实现

为了保证业务代码和实现方案解耦,类似于@Aync方案,我们同样采用注解+拦截器的方式进行逻辑注入

@Around("@annotation(org.springframework.amqp.rabbit.annotation.RabbitListener)")
	public Object cut(ProceedingJoinPoint pjp) throws Throwable {
		...
	}

实现思路大同小异,就是读取注解中的队列声明确认发布-订阅关系,然后以丢入消息队列来替换丢入线程池 

    private String resolveKey(Queue[] queues) {
		String s = this.beanFactory.resolveEmbeddedValue(queues[0].value());
		return (String) resolver.evaluate(s, evalContext);
	}
rabbitTemplate.convertAndSend(resolveKey(queues), args[0]);

为消息队列注入Json转换器,方便对象传输

    @Bean
    public Jackson2JsonMessageConverter producerJackson2MessageConverter() {
        return new Jackson2JsonMessageConverter();
    }

如有需要,我们可以将上下文的用户信息、token等写入消息的Header中

    private MessagePostProcessor beforePublishPostProcessor() {
        return message -> {
//          setting up context to message header
            return message;
        };
    }

被异步调用的service代码:

@Service
@Slf4j
public class DemoService {
    
    @RabbitListener(queuesToDeclare = @Queue("mytestqueue"))
    public void checkSome(List<String> tagTuple) {
        log.warn("check here {}", tagTuple);
    }
}

调用service的controller:

@RestController
public class DemoController {
    
    @Autowired
    private DemoService demoService;
    
    @RequestMapping("check")
    public Integer checkSome() {
        ArrayList<String> tagTuple = new ArrayList<>();
        tagTuple.add("bar");
        tagTuple.add("foo");
        demoService.checkSome(tagTuple);
        return 0;
ptional<Integer> max www.jintianxuesha.com= list.stream(www.huiyinpp3zc.cn).max((a, b) -> a - b);
  
  System.out.println(max.get(www.haoranjupt.com)); www.fudayulpt.cn// 6
  
  //求集合的最小值
  
  System.out.println(list.stream( www.jubooyule.com ).min((www.baihua178.cn b) -> a-b).get()); // 1
  
  System.out.println(www.jucaiyle.cn list.stream(www.tengyueylzc.cn).count(www.baihuayllpt.cn));//
  
  String str =www.qitianylezc.cn"11,22,33,44,55";
  
  System.out.println(Stream.of(str.split(www.longtenghai2.com",")).mapToInt(www.wujiu5zhuce.cn-> Integer.valueOf(x)).sum());
  
  System.out.println(Stream.of(str.split("www.lanboylgw.com,")).mapToInt(Integer::valueOf).sum());
  
  System.out.println(Stream.of(str.split(www.shentuylzc.cn",")).map(x -> Integer.valueOf(x)).mapToInt(x -> x).sum());
  
  System.out.println(Stream.of(str.split(www.xingyunylpt.com",")).map(Integer::valueOf).mapToInt(x -> x).su

执行查看效果

17:00:14.584TRACE[AbstractHandlerMapping.java:411]Mapped to org.smop.duplex.sample.DemoController#checkSome()
17:00:21.263WARN [DemoService.java:16]check here [bar, foo]

如有帮助或启发,还请点个

标签:www,cn,Spring,宇智波,System,65,println,tagTuple,out
来源: https://www.cnblogs.com/woshixiaowang/p/13943561.html