




版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
附录A外文翻译—原文部分Gutierrez,ProSpringBoot2,/10.1007/978-1-4842-3676-5_11SpringIntegrationandSpringCloudStreamwithSpringBootInthischapter,IshowyouoneofthebestintegrationframeworksfortheJavacommunity:theSpringIntegrationproject,whichisbasedontheSpringFramework.IalsopresenttheSpringCloudStream,whichisbasedonSpringIntegration.Itcreatesrobustandscalableevent-drivenmicroservicesconnectedtosharedmessagingsystems—alldonewithSpringBoot.Ifwetakealookatsoftwaredevelopmentandbusinessneeds,asadeveloperoranarchitect,wearealwayslookingathowtointegratecomponentsandsystems,eitherinternalorexternaltoourarchitecture,andprobewhatisfullyfunctional,highlyavailable,andeasytomaintainandenhance.Thefollowingarethemainusescasesthatdevelopersorarchitectstypicallyface.•\ Creatingasystemthatdoesareliablefiletransferorfileanalysis.Mostoftheapplicationsoutthereneedtoreadinformationfromafileandthenprocessit,soweneedtocreaterobustfilesystemsthatsaveandreaddatabutalsoshareanddealwiththesizeofthefiles.•\ Theabilitytousedatainasharedenvironmentwheremultipleclients(systemsorusers)needaccesstothesamedatabaseorthesametableanddooperationsanddealwithinconsistency,duplication,andmore.•\ Remoteaccesstodifferentsystems,fromexecutingremoteprocedures,tosendingalotofinformation.Wealwayswanttohavethisinrealtimeandinanasynchronousway.Theabilitytogetaresponseasfastaspossiblewithoutforgettingthattheremotesystemalwaysneedstobereachable;inotherwords,havethefaulttoleranceandhighavailabilityrequired.•\ Messaging—fromabasicinternalcalltobillionsofmessagespersecondtoremotebrokers.Normally,wedomessaginginanasynchronousway,soweneedtodealwithconcurrency,multithreading,speed(networklatency),highavailability,faulttolerance,andsoforth.Howcanwesolveorimplementalloftheseusecases?Almost15yearsago,softwareengineersGregorHohpeandBobbyWoolfwroteEnterpriseIntegrationPatterns:Designing,BuildingandDeployingMessagingSolutions(Addison-Wesley,2003).ThisbookexposesallthemessagingpatternsneededtosolvetheusecasesthatImentioned.Itgivesabetterunderstandingonhowsystemsinterconnectandwork,andhowyoucancreatearobustintegrationsystemwithapplicationarchitecture,object-orienteddesign,andmessage-oriented.Inthefollowingsections,I’llshowyousomeofthesepatternsusingtheSpringIntegrationprojectfromtheSpringFramework.SpringIntegrationPrimerSpringIntegrationisasimplemodelforimplementingenterpriseintegrationsolutions.Itfacilitatestheasynchronousandmessage-drivenwithinaSpringBootapplication.Itimplementsalltheenterpriseintegrationpatternsforcreatingenterprise,robust,andportableintegrationsolutions.TheSpringIntegrationprojectoffersawaytohavecomponentsthatarelooselycoupledformodularityandtestability.Ithelpstoenforcetheseparationofconcernsbetweenyourbusinessandintegrationlogic.SpringIntegrationexposesthefollowingmaincomponents.•\ Message.ThisisagenericwrapperforanyJavaobject.Itconsistsofheadersandapayload.TheheadersnormallyhaveimportantinformationlikeID,timestamp,correlationID,andreturnaddress;andofcourse,youcanaddyourown.Thepayloadcanbeanytypeofdata,fromanarrayofbytestocustomobjects.Youcanfinditsdefinitioninthespring-messagingmoduleintheorg.springframework.messagingpackage.publicinterfaceMessage<T>{TgetPayload();MessageHeadersgetHeaders();}Asyoucansee,there’snothingfancyinthedefinition.•\ Messagechannel.Pipesandfiltersarchitecture,verysimilartothecommandyouuseinaUNIXsystem.Touseit,youneedtohaveproducersandconsumers;theproducersendsthemessagetothemessagechannelandaconsumerreceivesit(seeFigure11-1).Figure11-1. MessagechannelThismessagechannelfollowsmessagingpatterns,suchasthePoint-to-PointandPublish/Subscribemodels.SpringIntegrationoffersseveralmessagechannels,likepollablechannels(thatallowsyoutohavebufferingmessageswithinaqueue)orsubscribablechannelsfortheconsumers.•\ Messageendpoint.Afilterthatconnectstheapplicationcodetothemessagingframework.MostoftheseendpointsarepartoftheEnterpriseIntegrationPatternsimplementations.•\ Filter.Amessagefilterdetermineswhenamessageshouldbepassedtotheoutputchannel.•\ Transformer.Amessagetransformermodifiesthecontentorstructureofamessageandpassesittotheoutputchannel.•\ Router.Amessagerouterdecideswhattodoandwheretosendthemessagebasedonrules.Theserulescanbeintheheadersorinthesamepayload.Thismessagerouterhasmanypatternsthatcanbeapplied.I’llshowyouatleastoneofthem.•\ Splitter.Amessagesplitteracceptsamessage(inputchannel),anditsplitsandreturnsnewmultiplemessages(outputchannel).•\ Serviceactivator.Thisisanendpointthatactsasaservicebyreceivingamessage(inputchannel)andprocessesit.Itcaneitherendtheflowoftheintegrationoritcanreturnthesamemessageoranentirelynewone(outputchannel).•\ Aggregator.Thismessageendpointreceivedmultiplemessages(inputchannel);itcombinestheminanewsinglemessage(baseonareleasestrategy)andsendsitout(outputchannel).•\ Channeladapters.Thisisaparticularendpointthatconnectsamessagechanneltoothersystemsortransports.SpringIntegrationoffersinboundoroutboundadapters.Wherearesponseisrequired,itoffersagatewayadapter.Youseethatthesearethemostcommonlyused.Why?IfyoursolutionislookingtoconnecttoRabbitMQ,JMS,FTP,aFileSystem,HTTPoranyothertechnology,SpringIntegrationhastheadaptertoconnecttoitwithoutyoucodinganyclient.ItwouldtakeawholenewbooktowriteaboutSpringIntegrationandmessagepatterns,messagingchannels,adapters,andmore,butifyouareinterestinginthistechnology,IrecommendProSpringIntegrationbyDr.MarkLui(Apress,2011).Inthenextsection,I’llshowyousomeofthecomponentsandpatterns,whichareenoughtogetyoustarted.ProgrammingSpringIntegrationWithSpringIntegration,thereareseveralwaystoconfigureallthecomponents(message,messagechannelandmessageendpoints):XML,JavaConfigclasses,annotations,andthenewIntegrationDSL.ToDoAppwithSpringIntegrationLet’sstartwiththewell-knownToDoAppanduseSpringIntegrationrightaway.Youcanstartfromscratchoryoucanfollowalonginthenextsectionstolearnwhatyouneedtodo.Ifyouarestartingfromscratch,thenyoucangotoSpringInitializr(https://start.spring.io)andaddthefollowingvaluestothefields.•\ Group:com.apress.todo•\ Artifact:todo-integration•\ Name:todo-integration•\ PackageName:com.apress.todo•\ Dependencies:SpringIntegration,LombokYoucanselecteitherMavenorGradleastheprojecttype.ThenyoucanpresstheGenerateProjectbutton,whichdownloadsaZIPfile.UncompressitandimporttheprojectinyourfavoriteIDE(seeFigure11-2).Figure11-2. SpringInitializrAsyoucanseefromthedependencies,wearenowusingSpringIntegration.YoucanreuseorcopytheToDoclass(seeListing11-1).Listing11-1. com.apress.todo.domain.ToDo.javapackagecom.apress.todo.domain;importlombok.Data;importjava.time.LocalDateTime;importjava.util.UUID;@DatapublicclassToDo{privateStringid;privateStringdescription;privateLocalDateTimecreated;privateLocalDateTimemodified;privatebooleancompleted;publicToDo(){this.id=UUID.randomUUID().toString();this.created=LocalDateTime.now();this.modified=LocalDateTime.now();}publicToDo(Stringdescription){this();this.description=description;}publicToDo(Stringdescription,booleancompleted){this(description);pleted=completed;}}Listing11-1showsyouwell-knownToDoclass.There’snothingnewaboutit.Next,let’screateaToDoIntegrationclassthathasthefirstSpringIntegrationflowusingDSL(seeListing11-2).Listing11-2. egration.ToDoIntegration.javapackageegration;importcom.apress.todo.domain.ToDo;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importegration.channel.DirectChannel;importegration.config.EnableIntegration;importegration.dsl.IntegrationFlow;importegration.dsl.IntegrationFlows;importegration.dsl.channel.MessageChannels;@EnableIntegration@ConfigurationpublicclassToDoIntegration{@BeanpublicDirectChannelinput(){returnMessageChannels.direct().get();}@BeanpublicIntegrationFlowsimpleFlow(){returnIntegrationFlows.from(input()).filter(ToDo.class,ToDo::isCompleted).transform(ToDo.class,toDo->toDo.getDescription().toUpperCase()).handle(System.out::println).get();}}Listing11-2showsabasicexample.Thisexamplereceivesamessagefromtheinputchannel(aToDoinstance),filtersthismessageifonlytheToDoiscompleted,andthentransformsthemessagebyuppercasingthedescriptionandhandlesitbyprintingitontheconsole.Allofthisiscalledanintegrationflow.Butlet’stakeadeeperlookinside.•\ IntegrationFlow.ExposestheDSLasabean(itisrequiredtohavea@Beanannotation).ThisclassisafactoryfortheIntegrationFlowBuilderanddefinestheflowoftheintegration.Itregistersallthecomponents,suchasmessagechannels,endpoints,andsoforth.•\ IntegrationFlows.ThisclassexposesafluentAPIthathelpsbuildingtheintegrationflow.It’seasytoincorporateendpointssuchastransform,filter,handle,split,aggregate,route,bridge.Withtheseendpoints,youcanuseanyJava8(andabove)lambdaexpressionsasanargument.•\ from.Thisisanoverloadedmethodwhereyounormallypassthemessagesource;inthiscase,wearecallingtheinputmethodthatreturnsaDirectChannelinstancethroughtheMessageChannelsfluentAPI.•\ filter.ThisoverloadedmethodpopulatesMessageFilter.TheMessageFilterdelegatestoaMessageSelectorthatsendsthemessagetothefilter’soutputchanneliftheselectoracceptsthemessage.•\ transform.Thismethodcanreceivealambdaexpression,butactuallyreceivesGenericTransformer<S,T>,whereSisthesourceandtheTisthetypethatitisconvertedto.Herewecanuseout-of-the-boxtransformers,likeObjectToJsonTransformer,FileToStringTransformer,andsoforth.Inthisexample,wearetheclasstype(ToDo)andalambdaisexecuted;inthiscase,gettingtheToDo’sdescriptionandtransformingittouppercase.•\ handle.ThisisanoverloadedmethodthatpopulatesServiceActivatingHandler.Normally,wecanuseaPOJOthatallowsyoutoreceivethemessageandeitherreturnanewmessageortriggeranothercall.Thisisausefulendpointthatwearegoingtoseeinthischapterandinthenextoneasaserviceactivatorendpoint.•\ @EnableIntegration.HereweareusinganewannotationthatsetsupalltheSpringIntegrationbeansthatweneedforourflow.Thisannotationregistersdifferentbeans,likeerrorChannel,LoggingHandler,taskScheduler,andmore.Thesebeanscomplementourflowinanintegrationsolution.ThisannotationisnecessarywhenusingJavaconfigurations,annotations,andDSLinaSpringBootapplication.Don’tworrytoomuchifthislooksdifferentfromwhatyouhaveprobablydoneinthepastwithintegrationsolutions.YouwillgetmorecomfortablewithalltheexamplesthatIshowyounext,anditgetseveneasier.Next,let’screatetheToDoConfigclassinwhichaToDoissentthroughtheinputchannel(seeListing11-3).Listing11-3. com.apress.todo.config.ToDoConfig.javapackagecom.apress.todo.config;importcom.apress.todo.domain.ToDo;importorg.springframework.boot.ApplicationRunner;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.messaging.MessageChannel;importorg.springframework.messaging.support.MessageBuilder;@ConfigurationpublicclassToDoConfig{@BeanpublicApplicationRunnerrunner(MessageChannelinput){returnargs->{input.send(MessageBuilder.withPayload(newToDo("buymilktoday",true)).build());};}}Listing11-3showstheApplicationRunnerbean,whereitisexecutedwhentheapplicationstarts(seethattheMessageChannelisinjected—theonedeclaredintheToDoIntegrationclass).ThismethodisusingaMessageBuilderclassthatoffersafluentAPIthatcreatesmessages.Inthiscase,theclassisusingthewithPayloadmethodthatcreatesanewToDoinstance,markedascompleted.Nowit’stimetorunourapplication.Ifyourunit,youshouldseesomethingsimilartothefollowingoutput....INFO39319-[main]o.s.i.e.EventDrivenConsumer:startedsimpleF.egration.config.ConsumerEndpointFactoryBean#2INFO39319-[main]c.a.todo.TodoIntegrationApplication:StartedTodoIntegrationApplicationin0.998seconds(JVMrunningfor1.422)GenericMessage[payload=BUYMILKTODAY,headers={id=c245b7a3-3191-641b-7ad8-1f6eb950f62e,timestamp=1535772540543}]...Rememberthatamessageisaboutheadersandpayload,whichiswhywegettheGenericMessageclasswithapayloadwherethefinalmessageis“BUYMILKTODAY”andheadersthatincludetheIDandthetimestamp.Thisistheresultofapplyingafilterandtransformingthemessage.
附录B外文翻译—译文部分Spring集成带有SpringBoot的Spring流在本章中,我向大家展示了java社区最好的集成框架之一:基于Spring框架的Spring集成项目。我还介绍了基于Spring集成的Spring流。它创建了连接到共享消息系统的强大和可扩展的事件驱动的微服务——所有这些都是用SpringBoot完成的。如果我们看看软件开发和业务需求,作为一个开发者或建筑师,我们总是在考虑如何集成组件和系统,无论是内部的还是外部的,我们的架构,并探索什么是完全功能的,高度可用的,易于维护和增强。以下是开发者或架构师通常会面对的主要用例。•创建一个能够进行可靠的文件传输或文件分析的系统。大部分的应用程序都需要从文件,然后处理它,所以我们需要创建健壮的文件系统保存和读取数据,并共享和处理文件的大小。*在多个共享环境中使用数据的能力客户(系统或用户)需要访问同一数据库或做同样的操作和处理不一致的问题,重复,还有更多。*从执行远程访问到不同系统程序,发送大量信息。我们一直想拥有这在实时和异步的方式。能够在不忘记远程系统总是需要可到达的情况下尽快得到响应;换句话说,具有所需的容错性和高可用性。•短信——从基本的内部通话到每秒数十亿条短信,再到远程经纪人。通常,我们用异步方式进行消息传递,因此我们需要处理并发、多线程、速度(网络延迟)、高可用性、容错性等问题。我们如何解决或实现所有这些用例?大约15年前,软件工程师GregorHohpe和BobbyWoolf撰写了《企业集成模式:设计、构建和部署消息传递解决方案》(addison-wesley,2003年)。这本书公开了解决我提到的用例所需的所有消息模式。它可以更好地理解系统如何相互连接和工作,以及如何创建一个具有应用程序体系结构、面向对象设计和面向消息的健壮集成系统。在下面的章节中,我将使用Spring框架中的Spring集成项目向您展示其中的一些模式。Spring集成底漆Spring集成是实现企业集成解决方案的一个简单模型。它方便了Spring启动应用程序中的异步和消息驱动。它实现了创建企业、健壮和可移植的集成解决方案的所有企业集成模式。该Spring集成项目提供了一种方法,使组件松散耦合模块化和可测试性。它有助于在业务和集成逻辑之间强制分离关注点。Spring集成公开了以下主要组件。•信息。这是任何java对象的通用包装器。它由头和有效载荷组成。标头通常有重要的信息,如id、时间戳、相关id和返回地址;当然,您可以添加自己的信息。有效负载可以是任何类型的数据,从字节数组到自定义对象。您可以在.org中的春季消息模块中找到它的定义。Spring框架。消息包。publicinterfaceMessage<T>{TgetPayload();MessageHeadersgetHeaders();}正如你所看到的,没有什么花哨的定义。•留言频道。管道和过滤器架构,非常类似于在unix系统中使用的命令。要使用它,你需要有生产者和消费者;生产者将消息发送到消息通道,消费者接收它(见下图)。此消息通道遵循消息传递模式,如点对点和发布/订阅模型。Spring集成为消费者提供了一些消息通道,如可传播的通道(允许您在队列中拥有缓冲消息)或可订阅的通道。•信息终点。将应用程序代码连接到消息传递框架的筛选器。这些端点大多是企业集成模式的实现。•\过滤。消息筛选器决定何时将消息传递到输出通道。•变压器。消息转换器修改消息的内容或结构并将其传递到输出通道。•路由器。消息路由器根据规则决定做什么和向何处发送消息。这些规则可以在标头中,也可以在同一个有效载荷中。这个消息路由器有很多模式可以应用。我至少会给你看其中一个。拆分器。消息拆分器接受消息(输入通道),然后拆分并返回新的多个消息(输出通道)。•服务激活器。这是一个端点,通过接收消息(输入通道)并处理它来充当服务。它既可以结束集成的流,也可以返回相同的消息或一个全新的消息(输出通道)。·\聚合器。此消息端点接收到多个消息(输入通道);它将它们合并到一个新的单一消息(基于发布策略)中并发送出去(输出通道)。•\通道适配器。这是一个特定的端点,将消息通道连接到其他系统或传输。Spring集成提供入站或出站适配器。在需要响应的情况下,它提供网关适配器。你看,这些是最常用的。为什么?如果您的解决方案是要连接到rabbitmq、jms、ftp、一个文件系统、http或任何其他技术,那么Spring集成就可以在不对任何客户端进行编码的情况下连接到它。如果你对这项技术感兴趣,我建议MarkLui博士(apress,2011年)写一本关于Spring集成和消息模式、消息通道、适配器等等的新书。在下一节中,我将向您展示一些组件和模式,这些组件和模式足以让您开始。编程Spring集成有了Spring集成,有几种方法来配置所有的组件(消息、消息通道和消息端点):xml、javaconfig类、注释和新的集成dsl。带有Spring集成的todo应用程序让我们从著名的todo应用程序开始,立即使用Spring集成。你可以从头开始,也可以在接下来的章节里学习你需要做的事情。如果你是从零开始,那么你可以去Spring初始化(https://start)。spring.io),并在字段中添加以下值。•小组讨论•艺术品:整合•名字:整合•包装名称:来吧•依赖:Spring整合,龙目您可以选择maven或gladle作为项目类型。然后您可以按下生成的项目按钮,该按钮可以下载zip文件。解压缩并导入您最爱的代码中的项目(见下图)。从依赖关系中可以看出,我们现在使用的是Spring积分。您可以重用或复制托多类(见清单11-1)。清单11-1.com.apress.todo.domain.ToDo.javapackagecom.apress.todo.domain;importlombok.Data;importjava.time.LocalDateTime;importjava.util.UUID;@DatapublicclassToDo{privateStringid;privateStringdescription;privateLocalDateTimecreated;privateLocalDateTimemodified;privatebooleancompleted;publicToDo(){this.id=UUID.randomUUID().toString();this.created=LocalDateTime.now();this.modified=LocalDateTime.now();}publicToDo(Stringdescription){this();this.description=description;}publicToDo(Stringdescription,booleancompleted){this(description);pleted=completed;}}清单11-1显示你的知名ToDoclass。这没什么新鲜的。接下来,让我们创建一个有第一个使用dsl的Spring集成流的Todo集成类(参见清单11-2)。清单11-2.egration.ToDoIntegration.javapackageegration;importcom.apress.todo.domain.ToDo;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importegration.channel.DirectChannel;importegration.config.EnableIntegration;importegration.dsl.IntegrationFlow;importegration.dsl.IntegrationFlows;importegration.dsl.channel.MessageChannels;@EnableIntegration@ConfigurationpublicclassToDoIntegration{@BeanpublicDirectChannelinput(){returnMessageChannels.direct().get();}@BeanpublicIntegrationFlowsimpleFlow(){returnIntegrationFlows.from(input()).filter(ToDo.class,ToDo::isCompleted).transform(ToDo.class,toDo->toDo.getDescription().toUpperCase()).handle(System.out::println).get();}}清单11-2是一个基本例子。此示例接收来自输入通道(一个todo实例)的消息,如果仅完成该todo,则筛选此消息,然后通过提升描述来转换该消息,并通过在控制台上打印来处理该消息。所有这些都被称为集
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 房地产行业土地购置价格统计表格
- 各行业绿色发展模式与技术创新研究报告
- 2025年白山货运从业资格证模拟考试系统
- 2025年江西货车从业资格考试试题及答案
- 2025年永州考货运资格证模拟试题
- 自动化设备安装与维护技术标准
- 农业机械化技术操作手册
- 2025年贵阳货运从业资格证报考
- PLC控制系统安装与调试手册
- 场地租赁安全协议书
- 专利共有合同范例
- 《ABO血型鉴定》课件
- 苏教版五年级下册数学计算题大全1200道带答案
- 计算机行业人工智能系列深度报告:deepseek研究框架-国海证券-20250214
- JJF1033-2023计量标准考核规范
- 《基于舞弊风险因子的辉山乳业公司财务舞弊案例探析》15000字(论文)
- 2025年山西省国有资本运营有限公司招聘笔试参考题库含答案解析
- 2025年湖南生物机电职业技术学院高职单招职业适应性测试近5年常考版参考题库含答案解析
- DB1331T 102-2025雄安新区应急物资储备库建设规范
- 北京市丰台区2024-2025学年九年级上学期期末道德与法治试题(含答案)
- 医院培训课件:《PET-CT的临床应用》
评论
0/150
提交评论