Reactive Spring. Josh Long, Pivotal

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
I am I am too loud for myself all right everybody come on in have a seat get relaxed get a seat please join me we have very very little time not a lot of time at all very very little time so I want you to come on in have a seat sit down relax take your shoes off maybe don't take your shoes off it might smell but you know everything else just do what you're gonna do be relaxed be comfortable and you know take a photo of this slide this slide is the one side that you should focus on it's the one slide that you should care about because it has all the information about what you are going to need and in order to be able to follow along later on so here we have my git repository we have my twitter coordinates we have my email so how many of you are using Twitter I'm just curious Twitter 2019 Twitter 2019 Twitter all right the rest of you get on it what are you doing it's a great place to be it's the new IRC it's one of the developers that drive the open source that power your business are so you should be there join us it's it's a it's our perp our privilege and pleasure to talk to you what about email how many of you are using email anybody no good moving on I'm not really a big email fan I think I have too soft in my position on this a little bit I have to take a less adamant a less rigorous position on email I'm not a big fan of email but I prefer it to slack so that's nice I have a I have a brand-new MacBook Pro this is a macbook pro with 32 gigs of ram i bought it last year so that I could run both slack and chrome at the same time 32 gigs of ram that's very nice for me now a little bit about me my name is Josh long I work on the spring team I'm an open source contributor and you know number one contributor of bugs but still number one number one contributor to all the bugs in all of the spring projects there he's got if you're on WeChat that there's that I have training videos on Safari it's an all-you-can-eat technical marketplace lots of videos these are 5 6 7 8 hours long different in detail in depth discussions of different topics I have a book called cloud native Java that I wrote in 2017 it's available in 4 languages English Chinese Korean and Russian so that's cool I think I'm doing a book signing afterwards so find that the book is something that I'm very proud of it's something that I worked on for a long time the book is all about how to build applications that work in the cloud with spring boot spring cloud and of course Cloud Foundry and this this book is something that I expected to be able to finish with my co-author very quickly I expected maybe 6 months but it did take a little bit longer than that it took just a little bit longer than 6 months in order to finish this book and there's a lot of reasons why a book like this might be delayed I cannot say exactly what is the cause but there's just it was only a little bit of a delay a very tiny delay not a very big delay at all ok it was just a little bit more than 6 months I was thinking 6 months maybe a little longer and it was not it was not a big deal not a big deal and a very small delay not a not a ok it was like two years ok it's two years delayed 2 extra years to get this darn book out the door but there's a reason for this ok the reason is that we spent a lot of time as authors we had a long debate a long debate that went back and forth over and over deciding eventually for 18 months in almost two years deciding on the animal on the cover now anybody who knows anything about O'Reilly books knows that it does not matter what's in the book itself nobody cares if you look at the reviews for all the different books if you look at the different comments all the all the comments are all about the animal on the cover and so we eventually discovered what animal we wanted on the cover of this book we chose a blue eared Kingfisher a bird with blue ears a bird that is only found in the Indonesian Java Islands it's a bird that's only found in the Indonesian Java Island its name to the Java Islands right so it's a bird that's only found in the indonesian java island and it's a bird and birds fly yes through the clouds through the clouds so it's a bird that is native to java that flies through the clouds it's a cloud native java bird it's a berta never mind it'll come it'll come give it time so there's that I have a podcast every Friday a podcast on iTunes and Google Play whatever it's called a beautiful podcast you can find it there and subscribe in your podcast listener different people the episode that was just made available yesterday every Friday yesterday the episode was on growl and JVM Zinj it's with Chris ballinger from Twitter so there's that and of course I do videos every Wednesday is a new introduction to a new topic on YouTube it's called spring tips you can find the playlist there and finally I've got a new book called reactive spring and this book is all about how to build applications that take advantage of reactive programming you have heard about reactive programming some at this wonderful conference right you've heard about reactive programming a few different times if I'm not mistaken you've heard a lot of good stuff and there's even one more talk coming after this I think from I think it's all a right so that'll be cool lots of good stuff and reactive programming reactive programming is a new answer to an old question an old problem the problem is how do I handle more users how do I handle more scale and the reason that we have this problem is because we have Internet of Things we have Micro Services we have mobile clients api's API driven applications things like iphone and android and html5 browser clients the more it the more clients that we have the more demand that we have on our services so we need to handle more demand and so the question is how do we handle more demand well one one way to do this of course if you have an application that is a 12 factor sort of micro service it's stateless it has easy replication and it's it's not hard to to scale out horizontally if you have this kind of micro service then one easy answer is to just add more instances of the service and put it in the load balancer right that's a nice answer because when you do that you have to buy more application instances I love that answer that answer makes me happy because I work for a cloud computing company we love it when you buy more app instances but is that the best answer no right so think about why we need more app instances well why can't we just have more users with the same computer the same instance the same node and the reasons we can't have more instances is because at some point we run out of the ability to handle more users at the same time the number one reason that we run out of that capacity is because we don't have more threads in a traditional application threads are linked to our number of users so we have one user we have one thread if one I have more users we have to have more threads this is a bit of a problem it means that you're going to very quickly run out of users that you can handle so you have to spin up and quit more instances so the thing is we need to be more efficient with those threads we need to make better use of those threads one way to do this one way to do this is to make sure that we don't spend a lot of time on those threads so that others can reuse those threads okay so what do we do what do we spend time on threads for what takes the most time right input and output that's what most of us spend time doing on threads we call other micro services we talk to other databases we're waiting for data to come back over the network as we're doing this we're sitting there waiting for the bytes where are those bytes where is my data as the data comes we wait we wait we wait meanwhile other people are trying to get in and access the server they're trying to make requests we need more threads and you're just sitting there waiting you've got a thread all to yourself and nobody else can reuse it this is because most of the software that we have written uses traditional synchronous blocking input and output there's an alternative here though there's asynchronous i/o asynchronous i/o is this idea that instead of walking and waiting for the data we ask for the data and then we get off the thread we finish immediately we don't get the data back immediately the data comes eventually in an interrupt or a callback when the data is there then we process it this is a different style of programming and unfortunately it's a little bit more complicated and so in order to deal with this kind of programming we needed a different way of describing data instead of using Java util collections or arrays these things are good for synchronous and blocking and small amounts of data but they're not good for large unlimited potentially asynchronous latent data so we need something that allows us to describe that this is why several years ago for four years ago or so many of the different companies in this space pivotal Netflix light Bend the Eclipse Foundation all these different organizations we got together and we created the the reactive streams specification for very simple interfaces are those reactive streams types enough are we done is that enough can you go to production with just that probably not right and the reason is because those types are very simple they don't support operations they don't support flat map and map and filter and all these kinds of things that we want to do on streams of data so what do we do well there's a project reactor from pivotal reactor provides operators that sit on top of the reactive streams types that makes life easier is that enough still no right because again we need these things to be integrated in the different technologies that we use to build software our data access our web tier our security layer etc all the micro services that we built so if it's not available at every layer then we're not gonna use it right it's not going to be very convenient if it doesn't work well in those environments that it makes no sense so the question is what do we do there in 2017 the spring team released Spring Framework 5 the first version of spring to support reactive programming end-to-end natively then we released spring data kay and spring security 5 and spring butoh and bring cloud Finchley and all these oh yeah good stuff we released all that different software to support these api's now we have the ability to build end-to-end systems with reactive programming and so my friends that's what we're going to talk about today is how to build reactive programs and to build a reactive systems using the spring ecosystem and of course in order to do that we're going to start here at my second favorite place on the Internet my second favorite place after production I love production you should love production you should goes early and often as possible bring the kids bring the family the weather is amazing it's the happiest place on earth it's better than Disneyland but if you have not been to production you can begin your journey here at start that spring that I oh that was cool there's music if you need inspiration in the early morning before a cup of tea or coffee start that spring try oh if your children are restless and they cannot sleep start that spring today oh and if you suffer from indigestion a sour stomach after a long night of alcohol abuse and WebSphere start that spring that I oh so we're gonna build a new application we're gonna use spring boot 2.0 2.2 om 3 ok there's this we're gonna bring an application we call this a reservation - service like that good we're gonna use Lombok we're gonna use the reactive web support we're gonna use the reactive MongoDB support and we're gonna use our socket support ok that's enough for now I'm happy with my selections so I'm gonna hit generate and that's gonna give me a new project then I'm gonna open up in my IDE so here it is ueo a reservation service zip I'll open this up and that's gonna open my ID it doesn't matter what IDE you use I'm using IntelliJ NetBeans works just fine eclipse works just fine all of them work just fine okay there's nothing special about them you need to support at least Java 8 or later and and of course Gradle if you want or maven and and then there you go right so you have a brand new project very simple project we're gonna build you application we're gonna go to our build I forgot to specify Java 11 so now the only sane version you should be using is 11 or 12 ok so Java 8 is very very old very very old dead basically expired no longer available terrible idea don't use this at all ok how many of using Java 12 Java 7 ah this makes me want to take a shower no no no don't use Java 7 here we go I've got now a a program I'm gonna make the font a little bit bigger here let's see 22 can you see this everybody ok good stuff so we've got a brand new application and we're gonna be using a we're gonna build an application that writes data to the database I've got MongoDB running in the background so I'm gonna say private string ID private string name and it's going to be a document object it's going to have a field here called at ID and it's just gonna be a very simple object that writes data to the database that has a primary key and it's gonna have a name field now I want to have getters and setters and to string and equals and hashcode so I could do this I could just create all that I could do the constructor there we go I can create the getters in the Centers good stuff equals and hashcode so modern look at that oh look at this all this code for nothing look at all that nonsense this is why people leave IT because of this no no no instead I want to use Lombok Lombok is a nice compile time annotation processor it allows me to synthesize or to create the information at compile time so that's kind of nice now i'm gonna create a repository that repository is an object that handles the the data access logic so repository is going to extend the reactive crud repository it's going to have a entity of type reservation whose primary keys of type string this interface provides methods that will be automatically provided for us when spring starts up it'll create an implementation of this interface that supports the common method save save all find find by ID check if it exists count deletes etc all these methods will return certain types of values and accept certain types of ayahs the first is a publisher a publisher is part of the reactive streams it's a specification that as I said was created by four different companies the reactive stream specification provides a publisher which publishes data a single item or multiple items of type T T is the generic part and it gets published to a subscriber when the subscriber consumes the data it is given the next data in the on next method when there are any errors those are passed in the on error method and when the method is done processing when the when the subscriber is done processing all the data the on complete method is called so these are callbacks that are called by the publisher on the subscriber now notice that we call these errors because remember errors when you do this kind of processing when you process streams of data it's very functional errors are not special they're not exceptional right they don't have their own control flow mechanism you handle errors in the same way that you handle any other kind of data with a callback when you are given a subscriber I'm sorry when you are said when you subscribe to a publisher you are given a subscription and the subscription is very important the subscription is probably the most important part you see now we are not we are no longer pulling the data from the producer of the data we're no longer taking it from the thing that is giving us the data instead the producer of the data is pushing us it's pushing the data to us asynchronously at whatever frequency whatever interval it wants and so we don't know when we are going to get the next record and so we have to be very careful that we don't get surprised we don't want to have too much day we don't want to have a billion records all in one nanosecond right and so this is why you use request requests allows the subscriber to request more records from the producer it allows the subscriber to ask the producer to slow down okay this is very useful it's called flow control it's not a new idea right ever since there was one computer on the internet talking to another you had flow control now in the context of flow control we call this flow control but this is also called back pressure back pressure is a marketing term it's not a technical term it's a marketing term that means the same thing as flow control so here we have flow control this helps us build more reliable systems our api's are given the opportunity to focus on the fact that there are errors which is true right there are errors we now have a built-in way to think about that and there is flow control which is also true but we now have a way to think about that in our code if we want to cancel the production of data we call cancel good stuff huh so those types are from the reactive stream spec it there's also a fourth type called processor and processor is just a bridge it's a source and a sink a producer and a consumer a subscriber and a publisher that's it that's all four types that's the entire reactive stream specification if you understand that congratulations you are certified reactive go ahead go to move to Silicon Valley startup startup raise a billion dollars in funding and then burn out in six months right you're ready you already know that more than most engineers in Silicon Valley if you understand this but is that enough I think these types are nice but they're very basic they're like Java arrays most of us don't write code using Java arrays we think about things using higher-order operators things like the job eight streams API right so this is why when you use reactor from pivotal you have two specializations one is called a mano a mano is also a publisher right see it extends core publisher which extends publisher or react to streams a mono is a publisher that produces zero or one record so it's like a completable future but it supports asynchronous processing and it's also got back pressure okay there's also a flux a flux is also a publisher but it provides zero into a lid on limited data so zero one two three five ten a thousand records it could be a trillion records it could be unlimited records but either way it's also a publisher this is like a Java eight stream but it also supports asynchronous programming and it supports back pressure so these are both specializations of publisher so our advice is that you accept publishers but you return fluxes and Manos right that way you can accept anything that produces a publisher so remember Netflix's rx Java to vertex from the Eclipse Foundation akka streams from light Bend and reactor all these different api's can all speak publisher they all understand this this basic API so you can interoperate with so now we have this interface and it supports data access let's write some sample data to the database okay and it's going to be a thing that listens for an event like this go and we're going to start the application it's just gonna be a spring mean it's gonna listen for event and what I'm gonna do is I'm gonna inject inject a reference to my reservation repository here now I want to inject this into the constructor I can do that like this if I want or or I can do required args constructor that's Lombok again I quite like that so what I'm gonna do is I'm gonna say flux dot just and I'm gonna create some names so it'll be um let's see all they're good we got Josh good we've got Marcin good and then I don't know I'm trying to think of some other names here oh yeah Jacob there we go so there's some names we've got some other engineers in the spring team and the reactive ecosystem team okay good and good okay so we've got now eight names I've just created a reactive stream with names in it and what I want to do is I want to visit each one of those names and turn them into a new reservation so named new reservation no name okay and there's our reservation objects okay and so I'm creating streams as I go now I wanna say for each one of these I want to save each one into the database using the repository now save here returns a mono write it's a mono and when I create map what I get is actually a flux of mono of reservation I don't want that so instead I use flat map and the result is I get rid of the intermediate to publisher okay so now I've got a stream of data here that is gonna be written to the database now this is actually very verbose normally I don't keep these in three different lines in this case you just compose it so you say var names that's Java 11 and then you say get rid of this get rid of that okay much better so now what happens if I run this code right now nothing will happen you see this code is a cold stream it's not hot it's like a like pipes you put the pipes together there's no water going through the pipes yet we have connected the pipes we have defined the flow but there's no water going through it yet so we call this a cold stream in order to activate the stream you subscribe so you provide a new subscriber or a consumer right and a consumer lets you log out the result so I'm gonna create a logger using Lombok and I'll say log dot info reservation okay now of course this can be re-written as a lambda and that as a method reference nicer okay now what happens if I run this well if I run this one time then we're gonna see that in MongoDB we're gonna have a document that in a document is a single row in a collection a collection is like a table so I'm gonna write data to MongoDB if I run at one time we'll see eight different names in the database if I run it two times we'll see 16 3 times 24 etc so this will go on forever and never never I don't want to do that I want to delete all the data and reset the database so I want to say this that resident padre dot delete all well that gives me a mono if I have a mono I have to subscribe don't I but subscriptions are asynchronous when I subscribe this could be on thread one and this could be on thread - we don't know and so as a result this may finish after this right there's no guarantee here so I want to force I want to force one thing to execute before the other can I do this yeah here I have this nice reactive API but I'm blocking no no no this is a terrible idea instead of doing that you use the operators so here I have an operator called then many and then many lets me take things like this publisher here and then this here I'm gonna subscribe to that here okay so now what I'm doing is I'm deleting everything first on what in and it could be on one thread then I'm writing everything to the database that could be on another thread and then I'm reading all the data and I'm logging each result as it comes back I don't have to worry about whether it's gonna execute correctly because I've used these operators even though there's multi-threading involved I don't have to worry about getting the the flow correct I don't have to worry about whether one thing will be ordered before the other it's guaranteed to work I have the operators and all that already in place so now I can just run this and go now I am using I am using these reactive api's because I don't want to worry about threading I don't want to worry about you know cyclic barriers and phasers and countdown latches and runner bowls and semaphores and threads and executor z' and executor services and so on I don't need to worry about that it's just done for me automatically so did it work did it work look at that look at that my friends it worked what about here in MongoDB that find ok there we are it's in MongoDB as well all that data is there it worked just fine of course it worked it was a demo what were you expecting that was always going to work that's not why we're here what I wanted to talk to you about is this this is the spring boot ASCII art work and this art work took a long time to get right but we on the spring team have many people who are doctors phd's people who used to work in nuclear physics very smart people so it makes me very happy to imagine that someday somewhere somehow there was a github issue and they said we need better ask you at work and I think you can agree they did a great job so it's for this reason that I want to take out one moment just one moment to talk about what I consider to be a very serious bug in the IntelliJ JetBrains product do you see this right here this bug this one right here do you see it do you see it that that one right there this one this one right here do you see that that right there do you see that that right there do you see that check box when you click that check box it disables the out ask you out worker what the hell why is this there that's a bug I don't even know why they put that there nobody even asked you jetbrains okay nobody even asked for this it's a terrible feature so I did what all people would do in this situation I went on internet and I cried and I sent out a message of pain and has given a message of hope from my friend yawns Ebron yawn suborn is a software developer by passion at JetBrains this is him right here right here right here right here right here Boop yawns abrin he sent me this message of hope which I want to share with you here today this is the message that he shared with me today or that made me happy he says I shall distribute a patch that fixes this to the correct behavior as soon as possible disabled by order of Josh long and I wouldn't believe him you know he's a friend I want to trust him I want to believe that he's right that he's not lying to me you know I have known him for a long time he keeps saying Josh don't worry it'll be in the next release it'll be fixed just relax Josh it's gonna be fixed soon just relax the next one will have it fixed but you know what I'm starting to think just maybe just maybe maybe maybe he's not being true I don't know I don't know whatever anyway we have amazing ass Kirk asked at work we have data in the database now so far I have been using MongoDB now among spring supports spring data supports a number of different reactive databases we support MongoDB which is a great choice because it has support for transactions and for taalib all queries and all that kind of stuff it supports it supports geospatial record to sports all that good stuff and it does so very nicely in the reactive API that's nice we also have support for Couchbase for Redis and for Cassandra right so all of them are natively reactive this is not the same as the regular spring data drivers these are reactive driver implementations that are built on top of native reactive or native asynchronous IO drivers so that allows them to go faster but not everybody is using MongoDB right it's a good choice but I think a lot of us are probably still using sequel how many of you are using SQL okay yeah that's not gonna go anywhere and so the question is how do we use SQL from a reactive application you cannot use JDBC JDBC blocks it's synchronous and blocking if you want to have more users you have to create more threads which is a problem we can't do that so one way to get around that is to use a natively reactive sequel data store and so we have a project here called r2 DB c r2 DB c and r2 DB c is an API that provides an implementation of an SPI and some drivers Microsoft sequel server PostgreSQL h2 and there's even a my sequel one right and there are more coming these are different drivers that talk to these two databases built on natively asynchronous database drivers okay so we can use that in our application now keep in mind our 2d BC is not yet GA it's not yet integrated into spring boot and so we need to do a little bit of work here we need to go here and add some code to our application mentally okay so I'm gonna add these manually I'll go back to my build I'm gonna comment out this part right here put a comment out MongoDB I'm gonna add our 2d BC so I'll add this down here that's the spring boot dependencies RTB see Bill of Materials maven BOM BOEM Bill of Materials ok and we're gonna add this property here so spring that are TBC that URL and I'm gonna point it to my local database and then we have our TBC Postgres we have our TBC pool and we have the spring boot starter our to bc and spring boot starter data our TBC with that there and with this connection string we can write code that now connects to our 2d BC so I'm gonna say our 2d BC configuration I'm going to create a beam whoops of type connection factory and connection in factories target I'm gonna inject the spring our TBC URL so spring that our 2d BCT URL string URL ok so here we go good stuff so there's our configuration class that defines how to connect to our Postgres database and we need to change some things of course this is no longer a MongoDB document and also we're not using a UUID we're using a primary key an auto auto monotonically incrementing primary key so we create that and make that an integer and then this will be an integer as well so here we go now I have MongoDB here piece equal orders orders you can see I've got this bunch of stuff so delete from reservation ok reservation and there's the schema it's got an integer and a car name so name is var car ID is an integer and that's the same thing as I have here integer ID name string so I'm going to now run this program again we've changed it to use our - DBC oops I have to get rid of all the old types that don't make any sense anymore and then rerun it I had to clean out the imports okay and so now select all from reservation there we go so now we're using a sequel data store in a reactive way as well okay so good we've got data in the database I want to build a web API okay now by the way it's important to know there's also support for transaction management here right you can do resource local transactions there's a there's a generic API that you can use to to read and write data in a transactional way for both MongoDB and for RT BC it's the same API so you can use the transactional operator to enclose units of work in a transactional boundary or you can use at transactional on your methods and that'll work just fine now I want to create a Web API and so one way to do this of course is to use spring MVC style so reservation rest controller like so and I can inject the reservation repository and we create an endpoint here called at get mapping forward slash reservations and it's going to be a publisher of reservation and so you just use that right I'm just gonna say find all and there's my new endpoint I'm gonna inject that argument into the constructor and there's my spring MVC style can controller when somebody comes and asks HTTP GET they're gonna call this endpoint and they're gonna get reservations and that works just fine you know it's okay but the thing is reservations the thing is that I don't really I don't you know I don't always want to use this style right I might want to use the new functional reactive style so this is okay but since we have Java 8 we can use the new function reactive style and that looks like this you just create a beam class HTTP config duration okay that beam router function server responds routes and it's a configuration class right so you say return route dot get four slash reservations good stuff and we're gonna just now create a handler function that responds to the data I'm gonna say return a new server response dot okay dot body and we're gonna inject the reservation repository so there's my repository as a collaborating object as a collaborating function dot find all reservation dot class and there we go that's good stuff good stuff good much cleaner okay so now I have an HTTP endpoint listens for HTTP GET four slash reservations and then this land back gets invoked and I can add other ones I can do post and delete and whatever I can do as much as I want right I can quit I can have all the routes in one beam and then I can use method reference as well this is a lambda but I can also use a method reference and so that that's just fine also this could have lived here I could have just done that as well it doesn't have to be in a separate class now I've got the new API let's go ahead and restart this this is fine right all I've done is I've showed you how to use the new spring web flux API to create HTTP endpoints that are reactive but this is only eight records right not a lot of data who cares about eight records I could have done this with this servlet API and spring MVC remember this is not the servlet API there's no servlet engine on this class path we're using Neddie right this is a brand new reactive web runtime built from the ground up to support asynchronous streams of data now all of that is pretty simple I could have done this before is this what I want well no I want to actually take advantage of asynchronous i/o asynchronous i/o is one I know is great for long connections so what can I do besides this well one thing I could do is web sockets so web socket config okay I'm going to create a simple URL hand remapping and a simple oh sorry web socket handler adapter new and a web socket handler okay like that now I am going to use this simple URL Hendra mapping to tell spring how to map this application to a endpoint so beatings like this and I'm gonna inject WebSocket handler WSH there WSH and i'll say set order equals 10 and there we go so there's my mapping and the WebSocket handler is this beam right here and so what I'm gonna do is I'm gonna create a endpoint that produces a greeting every second so to be a greetings producer okay so I'm going to create a greeting here public or just a flux really and it's gonna be an object that produces a greeting type Green's requests greeting response whenever somebody asks me for a greeting with a greeting request I'll send them a greeting response with a message in it okay so here's the data and it'll be at data at all args constructor an aurochs constructor just copy and paste good stuff there we go and I'm gonna create a new thing greetings request greet greetings request okay and I'm gonna make this a spring bean good stuff so now I've got this and I'm gonna just create a reactive stream that's infinite so I'll say from stream generate a new stream like this and I'm gonna stagger each element by one second so it's gonna be a new greetings response a noose new greens with response here we go wrong one like that like this bad okay uh and then hello and then we'll use the name in the request at instant dot now okay okay so there we go I'm greeting somebody every second forever it'll just keep going it's an infinite stream of data so here's my actual code okay new it's a new stream of data every second it'll produce a new value I'm gonna use that greetings producer here in my WebSocket code so here's my greetings producer I'm gonna inject that here to depend on that and I'm going to create a WebSocket application so when the client connects to the WebSocket service I'll get a new WebSocket session and then I can use the session to say oh let's receive any incoming messages map the incoming messages to some text turn each one of those each one of those texts as a into a request right so this is the name of the person we want to greet so it's a new greetings request and then turn each one of those requests into a stream of greetings right so here we go GP greet greeting request and then we want to send that back by the way I can use lambdas here then I want to send each one of those back so I'm gonna take each one and turn it into string and I'm gonna send each one of those back as a WebSocket text message so I have this string and turn it into a session dot text message okay string good stuff so there's my entire session my intern entire interaction with a WebSocket service and client so it responds okay and I'm gonna send that to the the client using session dot send there you go that's my entire WebSocket application it's a chat basically I send a name in it sends me greetings back ok now this of course could be var that's nice good now in order for me to test this in order for me to demonstrate it to you I need to create a I need to do something that I'm not proud of something that I'm not I'm a little ashamed of something that I don't want you to do but I need to do it to show you how to do it okay I need to write some JavaScript so here we go static static file WS dot HTML HTML body script window dot add event listener load function e and then here web socket localhost eighty-four WS for such greetings I'm quitting a WebSocket client and when the wed WebSocket object is connected I'll get an on open callback and then when there is new data I'll get the on message callback okay so this is the message I'm gonna log out the result when the new messages arrives new greeting message data and when there is data when the socket is connected I'll use the socket to send a request I'll say var name to greet equals window dot prompt who should we greet okay name to greet so I'll send that and then it as a response has come I'll I'll log them out here so let's restart this application and the application is at WS dot HTML who'd wanna greet let's say Kim Lee my daughter there you go so look at that right new greeting every second in the WebSocket application a new WebSocket stream this is gonna create new values forever it has no end okay it's an endless stream but in between each second that thread that's being used to produce the data somebody else can use it we're not wasting time on the thread keeping that thread forever somebody else can reuse that thread to produce data to handle more requests so reactive programming gives us a way to handle more users with the same computer with the same hardware with the same CPU so you can do two things either you reduce the cost of your data center bill because you can reduce it by a lot or you can handle many more users either way it's a good situation now this is a WebSocket service and an HTTP service I want to build a an edge service okay an edge service is a thing that is the it's the first port of call it's the first door into your architecture from the outside so your iPhone your PlayStation your Xbox your Android devices all of these things will talk to the edge service and then the edge service forwards the request to the downstream micro services and so these micro services are all similar but the edge service can take the different clients and normalize them so that they are the same for the downstream services so we're gonna build a new client here like so I'm going to build a new service a new client called reservation - client client ok I mean these are socket they're Lombok reactive web ok might use gateway and there we go so I'm just gonna build a very simple gateway a very simple edge service here we go ok open that up come on it's thinking really hard there it is so now in my reservation client I want to build a thing that's gonna listen for requests coming from the outside and we're gonna send them a client specific view this is where you can create views of the data that clients can look at and work with ok so let's say that we want to create a new HTTP endpoint that only returns the JSON names so not the whole reservation object just the name so I'm going to create a endpoint here I'm gonna create a reservation client that's gonna call our micro service and this reservation client is going to take data of type reservation from the service and then process it ok so here we go in order for us to do that I'm going to use a reactive HTTP client called web client so this is a spring beam web client I'll inject that here good stuff and I want to have reservation so I have to do something that I'm not proud of something that you should never ever do ever not even when you are all by yourself at home and no one is looking I I'm gonna copy and paste code ok Oh terrible so sad so greetings response greetings requests there we go so I've copied and pasted my types my data types here I don't need anything else and with that I can create a reservation client and the client is gonna return the data I'm gonna say dot get dot URI localhost:8080 four slash reservations that retrieve body dot to flux reservation class there's my reservation client and now I can use that to create a edge service a view of the data so reservation HTTP or whatever actually I can do it in here why not beam router function server response routes route build alright get forward slash reservations and so what we're gonna do is when actually a we're gonna return just the names so it's not the reservations it's the names in order to do that I'm going to make a call to the downstream service using the reservation client RC so I'll say returns server response ok DUP body RC dot and we're going to call the downstream service we're gonna say RC get reservations dot map to the string name okay so there's our stream of data okay I'm gonna send that back so map string dot class okay now I'm making a network call here I'm making a call over the network is this always going to work if I make a call over the network well of course not right I'm using the network things are going to fail when you build distribute systems fayette things may fail so you have operators here you can say oh if something happens then i want to handle the exception i get a new function and i say when there's a throwable then I get a chance to produce a new value so I can say eek right so now I'm handling the degree I'm degrading gracefully I'm handling it I can also say look you should we try 10 times the service might not respond the first time but maybe it will respond the second time and if it does you know if it doesn't keep you trying or even better I can do retry and then a back off I can say it retry ten times and then each time wait one more second longer alright like this so I'm waiting one more second so you have lots of ways to build robust code here so this makes your services more reliable but ok I've got a an end point ok see what that looks like localhost:8080 sorry this is gonna run to the wrong port I have to change the port so server that port will be 90 90 okay go 90 90 /res evasions four slash names come on oh I need to define the bean web client so here's this builder builder good restart so now so there's our names right no it's just the names it's not the whole JSON thing that's interesting now this is a very simple example of me streaming data I'm sending data from from the server to the client this is great for HTTP but what if I want to do more efficient communication from one node to another what if I want one service to talk to the other one more quickly what if I want to support bi-directional communication instead of sending text files I want to send binary data right what if I want to do a stream of data in and a stream of data out well these things are all much harder to do with HTTP so for a lot of organizations they're looking for ways to scale out and go faster Google created G RPC for example that's kind of interesting how many of you've heard of G RPC G RPC okay Google created that it doesn't do reactive it supports asynchronous but not reactive i/o so one thing that Salesforce have done there's another company they created a reactor based compiler plug-in that generates reactor based services for G RPC that's kind of interesting there's another company called Facebook you know Facebook anybody have Facebook I don't really use it I don't know what it's for but apparently it's pretty popular they are trying to build services at scale as well and so they created us a protocol called our socket now our socket is a binary protocol and it supports for message exchange patterns single value in single value out single value in multiple values out multiple values in multiple values out and single valuing and no value out okay so you can do all sorts of different things with it it's a binary protocol so I'm going to create a our socket server this is not HTTP it's our socket and it's possible because I have spring boots our socket on the classpath so I'll say controller class our socket greetings controller and I'll say that this is gonna be mapped to the greetings endpoint and I'm gonna return a publisher of greeting responses so you saw that I've got that that already set up there and I'm gonna do is I'm gonna just inject my greetings producer here like that so I'll say it returned this stub producer greet greetings request there you go there's my our socket server the only thing I need to do to use that as I need to have an AR socket server port so I'll say 70 70 good I'm gonna restart this and then on the client side I want to create a new endpoint that will stream that data so when somebody goes to the greetings endpoints and I want to send server-sent events on the client okay so I'll pass on a name here new handler function and the handler function is gonna use this new client that I'm gonna build called the greetings client and the greetings client will act as an our socket client not a web client so I'll use the our socket requester this is the equivalent of the web client but it for our socket I'm gonna inject that there it's gonna be a regular spring bean I'll have the required args constructor and here I'll just say flux of greetings response greet when somebody sends me a greetings request okay so I'll say return this dot requester dot route greetings dot data and the data that I'm gonna send in is the request and the data that I expect to come back will be a greetings response dot class okay so there's that greetings client in order for this to work I need to have a beam of type our socket requester just like I have a web client here so I'll say our socket requester I'm gonna say our socket requester dot builder builder I'll say builder dot connect TCP client transport dot create 7070 okay so there's my new thing there dot block good and then in order to use that I'm going to create I'm gonna call that service I'm going to call the our socket service in my code here I'm gonna inject the our socket greeting his client greetings client GC i'll say g c dot greet and i'll get the path name equals server request dot path variable name okay string name and i'll say create a new greetings request with the name and that'll give me a stream of greetings responses and i want to send that never-ending stream back to the web client using server sent events this is a a a way of sending data that it's a it's pretty inefficient but it's a good demo so we use that okay so greetings response dot class and the only thing I need now is content type equals text event stream so I'm actually bridging I'm actually calling our socket for my service to service communication and then adapting it to HTTP very easily in my edge service and go so now localhost SSE greetings names greetings and I'll use mints okay so there's my endpoint whoops oh it's unimportant 9090 isn't it so that's the edge service there we go so now I'm bridging reactive streams data coming from our socket for efficient communication for my services but if I have open web clients they can talk to the edge service and that works just fine reactive programming allows us to build more robust systems that are also more efficient and they don't take more code thank you so much for your time boy boy some like that I appreciate it thank you so much I'm signing a book I think after this so please find me there I'm not sure where that is do you know I don't know if you want to sign the book could you do it at that place near the conference there you go i buy the by the ball pin yeah oh that's some they're all gonna be distracted but the they're gonna want to go swimming in the ball pin that's gonna be very hard to compete with are there any questions I'm happy to answer them yes sir the first thing thank you for your speech thank you the second is as I understand right now Spring Framework do not officially support relational databases right so when do we expect to see the official support for a relational database missiles we do support relational databases in a blocking way right we've had that for 15 years but for reactive we have our 2d BC I hope that'll be done this year right I hope that'll be in the release train but we those projects the experimental project that's coming from people on the spring team we've already got it working our 2d BC is something that we developed right we it's open source we have contributors but we started the project and so we fully intend to support it and I expect by this year that'll all be in GA got it thank you no problem thank you good question other questions comments feedback who learned something new oh good okay I never know maybe maybe you all know this stuff already I never know when I come to great great communities like this one you know wouldn't surprise me all right thank you
Info
Channel: Devoxx
Views: 14,495
Rating: 4.8895707 out of 5
Keywords:
Id: Z5q-CXbvM1E
Channel Id: undefined
Length: 57min 12sec (3432 seconds)
Published: Thu May 30 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.