很多编程语言框架里都提供了发布订阅的组件,或者叫事件处理机制,而spring框架对这个功能也有支持,主要使用eventlistener
实现订阅,使用applicationeventpublisher
使用发布。这种系统集成的我们先叫它“集成组件”
事实上,发布订阅真的与开发语言没有什么关系,所以出现了另一种产品,消息中间件,或者叫消息队列,它是以发布订阅模式为理论基础的,同时很多消息队列产品又有自己的特色,这种独立的消息队列我们为rabbitmq
为例子。
@async
注解基于以上的介绍,主要帮助大家理解和认识,在什么时候用什么类型的工具。
订阅
@getter @builder(tobuilder = true) @noargsconstructor @allargsconstructor public class createbookevent { private string address; private string title; } @component public class emaileventlistener { @eventlistener @async public void handleevent(createbookevent event) throws exception { system.out.println("email消息:建立图书:" + event.gettitle()); } }
发布
@autowired private applicationeventpublisher applicationeventpublisher; public void publish(){ applicationeventpublisher.publishevent(createbookevent.builder().address("system").title("新建图书").build()); }
订阅
@slf4j @component public class distributorsubscriber { public static final string work_queue = "fx.activity.total"; public static final string exchange = "fx.exchange"; @autowired distributoractivitytotalrepository distributoractivitytotalrepository; @autowired objectmapper objectmapper; @bean public topicexchange phonetotalexchange() { return new topicexchange(exchange); } @bean public queue phonetotalqueue() { return new queue(work_queue); } @bean public binding bindsignqueue() { return bindingbuilder.bind(phonetotalqueue()).to(phonetotalexchange()).with(work_queue); } @rabbitlistener(queues = work_queue) public void phonetotalqueuelistener(string data) { try { logger.debug("fx.activity.total:{}", data); distributoractivitytotal entity = objectmapper.readvalue(data, distributoractivitytotal.class); distributoractivitytotalrepository.incupdate(entity); } catch (exception ex) { logger.error("fx.activity.total.error", ex); } }
发布
@autowired private rabbittemplate rabbittemplate; public void modifysalesperson(salespersondto salespersondto) { try { rabbittemplate.convertandsend( "exchange", "mqname", objectmapper.writevalueasstring(salespersondto) ); logger.debug("enter {},message:{}", "modifysalesperson", salespersondto.tostring()); } catch (exception ex) { logger.error("mq.modifysalesperson.error", ex); } }
如对本文有疑问, 点击进行留言回复!!
荐 厉害了!阿里P8架构师用4大技术文档带你深入解读爆火的中台战略
FlowableException: Error initialising dmn data model报错问题
网友评论