Category Archives: learning spring boot

Learning Spring Boot 2nd Edition released!

I’ve been working on this for over a year, and today is the day. Learning Spring Boot 2nd Edition released!

What’s in it? A whole lot:

  • Web Development
  • Data Access
  • Testing
  • Developer Tools
  • AMQP Messaging
  • Microservices
  • WebSockets
  • Security
  • more!

To top it off, the WHOLE BOOK is written using the new Reactor paradigm found in Spring Framework 5.0. This means Reactive Web, Reactive Data Access, Reactive Messaging, Reactive WebSockets, and even Reactive Security, all groundbreaking technologies.

In fact, the following key technologies are used through the book:

  • Spring Framework 5.0.0.RELEASE
  • Spring Data Key-RELEASE
  • Reactor Bismuth-RELEASE
  • Spring Boot 2.0.0.M5
  • Spring Cloud Finchley.M3

There isn’t any other book on the market like this. And not only is this a fantastic stack, but in each chapter, we build up a social media platform. Chapter by chapter, we add critical features for demonstration purposes, and in the process, are able to learn how to do these things reactively, in ways you can easily adapt to the problems you are solving today.

In short, not only is it groundbreaking, it’s practical and pragmatic. Coding examples you can put to work immediately in whatever you are trying to solve.

It may take a little bit of time to get pushed all the way the Amazon, so stay tuned.

Happy reading AND happy coding!

Learning Spring Boot – 2nd Edition Rewrite is complete

I have finished updating every chapter of this book to the Reactor-based paradigm. And boy did it take a lot!

In case you missed it, when I embarked upon writing this book for Packt Publishing, I decided to start from scratch. The previous edition, as much as I enjoyed it, wasn’t bold enough. This time, I wanted to build an application chapter by chapter, and make it as real as possible.

So I dug into a demo app I had used at several conferences called Spring-a-Gram. That app started from my desire to snap a picture of the audience and upload it to the website, LIVE. Great eye candy, right? Along the way, I learned lots of aspects of the Spring portfolio that this app could leverage.

And when faced with the prospect of writing a new title on Spring Boot, I picked up and ran with that app. Only this time, EVERYTHING would be done asynchronously and without blocking, i.e. with Reactor, Pivotal’s implementation of the Reactive Streams spec.

So this book is stocked with asynchronous web, data access, AMQP messaging, WebSockets, microservices, security, metrics, developer tools, and production tips. A solid cross section of what developers need to build apps.

The trick with this lauded goal is that when I started writing about 15 months ago, there was no Spring Boot 2.0. Spring WebFlux was being scratched out in an experimental repository. Spring Boot WebFlux starters appeared later in a different repository.

Talk about taking on a risk!

So I started writing the manuscript using Boot 1.4 and servlets, with plans to rewrite everything once the Reactor bits were available. That has been a LOT of effort, but worth it.

Because I’m quite proud of being able to show people how to build apps rooted in Spring, the de facto Java toolkit for application development, but now sitting atop Project Reactor, the bedrock of Reactive Streams apps.

Until yesterday, we were focusing on Spring Boot 2.0.0.M4 as the release target, but decided to wait for 2.0.0.M5 coming in a couple weeks, with plans to polish, revise, and release around the second week of October.

Hopefully we can hold onto that release date! There appears to be high demand for what will be the first book on Spring WebFlux as well as Project Reactor to hit the markets.

I’m excited to get this book into everyone’s hands and watch as people began to write scalable apps with Reactor on top of the Spring portfolio.

So stay tuned! The end is in site.

Streams of messages are the way to go

I have been diligently getting all my code up to date for the release of Learning Spring Boot 2nd Edition this September. Digging into Chapter 8, WebSockets with Spring Boot, I realized I had a bigger challenge than expected.

You see, I’d chatted with Rossen, the lead developer on Spring Web. In the past, his job was overseeing Spring MVC, but in the past year, that has expanded to our new Reactive Streams story and the module Spring WebFlux. In short, Rossen informed me that there was no messaging available with WebSockets in WebFlux.

I’m not sure you’re aware what this means. “Message” was a paradigm invented by Mark Fisher in the early days of Spring Integration with a nice little container class called Message<T> that included a payload and optional headers. This was handy when it came to enterprise service buses, but people spotted the paradigm as more universally applicable.

Hence, they put a messaging layer on top of WebSockets, making it super easy to pipe messages from clients to the server and back. Anywhere in the server side code, you can get your hands on a SimpMessagingTemplate and publish a message, targeted for either a server side or client side endpoint. The runtime would handle it all.

And none of this was available with Spring 5’s WebFlux-based WebSocket solution. As Rossen said, “think of it as streams of WebSocket messages.”

That was tricky.

So I dug in and started learning the API. In the reference docs, they show how to register a WebSocketHandler. You tie that API to a URL and inside the API, are handed a WebSocketSession. I kind of stared at this API for five minutes before noodling around with it.

Unsure about what to do, I cracked open the Spring Framework source code and started reading their unit tests. Since my chapter had a “chat” server (the de facto demo for WebSocket technology), I was ecstatic to see something similar right there in WebFlux’s unit tests. It was an EchoServer.

I copy and pasted the code into my book’s code. Tweaked the JavaScript to hook up. Fired things up, and started sending in messages. And it worked.

Until I opened a second tab sporting a different WebSocket session. That’s when I noticed that the messages posted by one tab didn’t appear in the other.

And then I KNEW what they meant by “EchoServer”. Receiving the messages on a session and sending them right back ONLY WORKS ON THE SAME SESSION.

I shook my head, remembering the fact that Spring 4’s WebSocket configurations SHOWS you configuring a broker. That’s what is needed!

I needed a broker and I didn’t have one. At this point, I had gotten barebones WebSockets registered on the server and my client connected. But to noodle this thing out, I stopped to get a coffee. As the java was brewing, so was my noggin. That’s when the light bulb went off.

I already had a broker. It was right there.

You see, I had gambled on putting Spring Cloud Stream in my book when it was in its infancy. In Chapter 7, AMQP Messaging with Spring Boot, I kick things off with Spring AMQP’s RabbitTemplate, which is great for small stuff. As if often the case Spring’s template approach makes the AMQP APIs very pliable. They also adopted the Message paradigm from Spring Integration so you can either send your own POJOs, or you can do it Message<Pojo> style, which moves your abstraction up a level, making things simpler.

But Spring Cloud Stream is even better. It moves things up even higher. You aren’t thinking in terms of message brokers. Instead, you are thinking about chaining together streams of messages. (Which, by the way, dovetails PERFECTLY with Reactor).

Whether you are using RabbitMQ or Kafka (or whatever) is simply an implementation detail. With a few property settings, you can put together any sort of messaging you want.

And I was already doing that!

Now I’m no genius. This is stuff that had I just spoken with Rossen and Marius (lead for Spring Cloud Stream) they would have pointed out in no time. But there is that thrill of discovering something for yourself that is unbeatable.

So I hammer away at a service that listens for WebSocket messages and pipes them into a broker via Spring Cloud Stream. (Thanks Artem for showing me to do THAT with Reactor!) I code another Spring service that listens for a stream of messages coming from the broker and pipes them out to a WebSocket stream.

And I’m done. In maybe 20 minutes. (I did goof up by not pointing these two servers at the same AMQP exchange).

I fire up my system, and the chat service is working. Flawlessly. A message written in one tab is shipped over a WebSocket to the server. The server pipes it into RabbitMQ. The other service scoops up the message, and pipes it out to the WebSocket client. And this is happening for every WebSocket session that has registered. This thing is a knockout punch, because I knew I architected it right.

Poof! (Plus, the concept feels totally righteous. Streams of messages, flowing through the system.)

That’s when another realization hits me. When I previously drafted this chapter, I attempted to use Spring WebSocket’s RabbitMQ option, but never could get it to properly bind to my RabbitMQ instance. Sadly, I switched to their in memory broker. This meant the solution wouldn’t work if you ran multiple instances in the cloud.

THIS SOLUTION WILL!

Because it’s piping stuff right into RabbitMQ, it will work perfectly. (Partly thanks to Consumer Groups).

To wrap up the chapter, I even went so far as to show off SimpMessagingTemplate’s sendToUser API. It nicely lets you send a message to a single user. I coded a little “@bob Did you get this?” magic, where it would parse the @’d user, and then convertAndSendToUser(parsedUser). Well, I had none of that API, remember?

How can I pull this off? Must be too much, right? Wrong! Since every message is traveling to everyone, and it’s using the Message<T> construct, it takes no effort to add a header including the original user’s name.

The broker-to-client service can simply parse the message and compare against the user or themselves, and decided whether or not to let it on through. (Send a copy to both parties!) It’s basically an extra filter layered on top, which is why Reactor makes this type of thing so easy to apply.

Anywho, with a solid day of work, I manage to code the entire thing, top to bottom, using RabbitMQ, WebSockets, Project Reactor, and even have user-to-user messaging. Freakin’ wicked it was to put it all together.

And I know this is rock solid not because of what I coded. But because of the powerful underlying concepts orchestrated by Rossen, Mark Fisher, Artem, Gary, and Marius.

Can’t wait to apply security filtering in the next chapter to these WebSocket streams.

Learning Spring Boot requiring more tweaks to get off the ground

With things bearing down on my September due date for Learning Spring Boot 2nd Edition, I’ve gotten in gear and started hammering at the codebase.

For one thing, I have strived to catch up ALL the code to Spring WebFlux, no longer using the servlet-based Spring MVC. In the process of doing that, I discovered a breaking change in Spring Framework that conflicts with the latest milestone of Thymeleaf. I switched to snapshots, and moved forward.

The big change coming down the pike has been WebSocket support. In Spring 4, there is incredibly detailed support for various messaging protocols, messaging brokers, and all sorts of goodies involving Spring’s WebSocket support.

With Spring WebFlux, they had to start from scratch and build things up. Suffice it to say, streams of WebSocket messages in and out has a very basic API. Hence, I’m rewriting the code in Chapter 8 to leverage this, chuck aside things like STOMP and SockJS. I rewrote the server side code thanks to the project lead of Spring Integration, and revved up to test it out, only to get stymied by something else.

Somehow, Reactive Web was switched off in favor of Servlet Web.

Huh???

Spending a couple hours on Slack with some super sharp teammates, I uncovered a dependency from Spring Cloud Netflix that pulled in Tomcat along with another transitive dependency on Spring MVC. Excluding them got things humming again on Netty, only to find a bug in Thymeleaf caused by Spring WebFlux + Spring Cloud Stream.

Sigh. I updated the issue filed with Thymeleaf asking about another release to see how to move forward. Until then, this book is paused. Yet again.

When that is fixed, hopefully I can push forward and get the last bits in line.

Cheers!

Learning Spring Boot 2nd Edition delayed – Find out how to get a FREE advanced copy

Having taken a week off after turning in the last chapter, I geared up and started reading all of Learning Spring Boot, top-to-bottom. Some bits were written before Spring Boot 2.0 was even available on Github, so there is much code that needs updating.

That’s when I got word from my published that due to Boot’s schedule, they are delaying the release. Didn’t say when. We haven’t hammered that out. But this makes me feel good. Encourages me to really polish things up and ensure I can get the right message out there.

In the meantime, I’m putting together my Launch Team.

  • get an advanced reader e-copy of my book
  • be a part of a secret Facebook page and get sneak peeks
  • learn more about my writing journey as it happens

Then the Turnquist Techies is for you!! I will send out FREE advanced reader e-copies to the members of my launch team. There will be a secret Facebook page and a private newsletter just for this team.

What do I ask?

I am encouraging the members of the team to participate in this journey with me by sharing their honest opinion in reviews, tweeting and posting about what they are reading, and the like. For the most part, being a part of the Turnquist Techies is about having fun, reading, connecting, and learning more about the technical writing process.

How do I sign up?

Just click on join The Turnquist Techies and fill out this form.

How to write a tech book, or how I stopped worrying and learned to love writing

I just sent in the last chapter of Learning Spring Boot 2nd Edition’s 1st draft. And my brain has collapsed. I’ve been working for several months on this 10-chapter book that embraces Spring Boot 2.0 and reactive programming. There are several books out there on reactive programming, but I believe this will be the first to hit the market about Project Reactor.

I’m not done, not by a long shot. I told my publisher that we’d need at least one big round to make updates to ALL the code, because I started writing when not everything was in place. And it’s still true. But editing, polishing, and updating an existing repository of code and manuscript is easier than creating one out of thin air.

I wanted to write just a little bit about how I approaching writing something like this. Maybe you have been thinking about writing a book yourself, and your curious what goes on. This isn’t the only, but it’s the way that works for me.

Tools

Laptop on a work table with DIY and construction tools all around top view hobby and crafts concept

To write a book, you need a mechanism to capture prose and code. For fiction, I use Scrivener, but when it comes to technical writing, where the code, screenshots, and text are tightly integrated, I use Asciidoctor. With Asciidoctor, the overhead of a word processor is removed, and instead I can focus on pure content.

Also, using Asciidoctor lets me pull in the code to generate the manuscript sent in to my publisher. This way, I have Sublime Text in one window viewing the source prose and IntelliJ open in another viewing the source code. To top it off, I have a Ruby guardfile configure to constantly regenerate an HTML proof of the chapter I’m writing with it refreshing via LiveReload in my browser.

This combination gives me a quick feedback loop as I write.

What to write

This may be the biggest hurdle to some. When you’ve picked the technology, setup your tools, and finally have the editor opened up, what do you type in that black, blank screen?

Waiting for magical words to arrive? Or perhaps you hope elves will scurry in and leave something? Nope. This is where the rubber hits the proverbial road and you have to push yourself to start typing.

What do I do? I actually start earlier than that. From time to time, I have a crazy idea about something I want to show to an audience at a conference. Some demo I want to give with a few pieces of the Spring portfolio. I began to noodle out code to make that happen. Once, I asked “can I snap a picture of the audience and upload it from my phone to a webpage the audience is watching on the overhead?” Thus was born my Spring-a-Gram demo.

That demo has morphed many times to the point that I have built a full blown, cloud native, microservice-based system. And guess what. It’s the system we get to explore in Learning Spring Boot 2nd Edition.

So when I sit down to write a chapter, I first start writing the code I want to walk through. Once it’s humming inside my IDE, I start to typeset it in Asciidoctor. And pages of code fragments, I began to tell a story.

Weaving a story

When writing technical articles, getting started guides, and books, everything is still a story. Even if this isn’t a novel, it’s still a story. People that grant you the honor of reading your work want to be entertained. When it comes to tech work, they want the ooh’s and ahh’s. They want to walk away saying, “That was cool. I could use that right now.”

At least, that’s how I read things. So my goal when I write is to make it fun for me. If it’s fun for me, I trust it will be fun for others.

If I sift through a chapter, and it’s just a boring dump of code, then it’s sad. And that’s not what I want. I can’t promise that all my writing has upheld this lofty goal. But it’s my goal nonetheless.

So oftentimes, I will typeset the code, hand some descriptive details around the code, then read it again, top to bottom, and add extra stuff. Paragraphs talking about why we’re doing this. Mentioning tradeoffs. Issues that maybe exist today and where we have to make a choice. Ultimately, understand not just what the code does but why it does it this way. And what other options are out there.

Letting go

At some point, after all the writing and polishing and fine tuning, you have to turn in your work. I don’t know if there is ever a time where I’m 100% satisfied. I’m kind of picky. But the truth is – you’ll never find every typo, every bug.

My code fidelity is much higher ever since I started using Asciidoctor. But stuff happens. And you have to be happy turning in your work.

You see, if you’ve acquired enough skill to sit down a write a book without someone leaning over your shoulder and coaching you, you might have a lot of good value other developers seek. Eager coders will be able to read what you wrote, look past small mistakes, and most importantly, grok the points you make. That’s what is key.

And one thing is for certain – writing makes you better. I have found that any gaps in my own understanding of certain parts of code lead me to chase down and grasp those bits. And then I want to share them with others. Which is what writing books is all about.

Happy writing!

Learning Spring Boot 2nd Edition 80% complete w/ Reactive Web

This weekend I sent in the first draft for Chapter 2 – Reactive Web with Spring Boot (of Learning Spring Boot). Even though this is Chapter 2, it’s 80% of the book. That’s because I’m writing Chapters 2, 3, and 4 last, due to the amount they depend on Reactive Spring.

This may sound rather awkward given Spring Boot has yet to release any tags for 2.0. Pay it note, there is a lot of action in Spring Framework 5.0.0 such that it’s already had several milestones. A big piece of this book is getting a hold of those reactive bits and leveraging them to build scaleable apps. The other part is how Spring Boot will autoconfigure such stuff.

Thanks to Spring guru Brian Clozel, there is an experimental project that autoconfigures Spring Boot for Reactive Spring, and will eventually get folded into the Spring Framework. Bottom line: Reactive Spring is available for coding today, albeit not with every feature needed. But since the target release date is May, there will be time for spit and polish against the book’s code base.

And now, an excerpt from Chapter 2, for your reading pleasure:


Learning the tenets of reactive programming

To launch things, we are going to take advantage of one of Spring Boot’s hottest new features: Spring 5’s reactive support. The entire Spring portfolio is embracing the paradigm of reactive applications, and we’ll focus on what this means and how we can cash in without breaking the bank.

Before we can do that, the question arises: what is a reactive application?

In simplest terms, reactive applications embrace the concept of non-blocking, asynchronous operations. Asynchronous means that the answer is coming later, whether by polling or by an event pushed backed to us. Non-blocking means not waiting for a response, implying we may have to poll for the results. Either way, while the result is being formed, we aren’t holding up the thread, allowing it to service other calls.

The side effect of these two characteristics is that applications are able to accomplish more with existing resources.

There are several flavors of reactive applications going back to the 1970s, but the current one gaining resonance is reactive streams due its introduction of backpressure.

Backpressure is another way of saying volume control. The consumer controls how much data is sent by using a pull-based mechanism instead of a traditional push-based solution. For example, imagine requesting a collection of images from the system. You could receive one or a hundred thousand. To prevent sthe risk of running out of memory in the latter, people often code page-based solutions. This ripples across the code base, causing a change in the API. And it introduces another layer of handling.

For example, instead having a solution return a risky collection like this:

public interface MyRepository {
List findAll();
}

We would instead switch to something like this:

public interface MyRepository {
Page findAll(Pageable p);
}

The first solution is simple. We know how to iterate over it. The second solution is also iterable (Spring Data Commons’s Page type implements Java’s Iterable interface), but requires passing in a parameter to our API specifying how big a page is and which page we want. While not hard, it introduces a fundamental change in our API.

Reactive streams is much simpler – return a container that lets the client choose how many items to take. Whether there is one or thousands, the client can use the exact same mechanism and take however many it’s ready for.

public interface MyRepository {
Flux findAll();
}

A Flux, which we’ll explore in greater detail in the next section, is very similar to a Java 8 Stream. We can take just as many as we want and lazily waits until we subscribe to it to yield anything. There is no need to put together a PageRequest, making it seemless to chain together controllers, services, and even remote calls.


Hopefully this has whet your appetite to code against Reactive Spring.

Happy coding!

 

How Guidance saved Christmas with Spring Boot

I hope you all have settled down with a hot cup of cocoa. Because it’s time for the most beloved Christmas tale of all. The one where Guidance Saved Christmas with Spring Boot.

Guidance the Elf had seen Santa facing new issues. It seemed like managing the list of children in addition to invoicing and warehouse inventory was harder than ever. Scaling was becoming a bug bear. Guidance was saddened at the challenges faced. But he had to report for duty in the Turnquist household.

One night, after having made his first appearance, Guidance spotted Learning Spring Boot.

“What’s this?” he thought. So he sat down and read the whole thing. (Elves can read entire books in one night, you know). Reading the book, his eyes opened wide. Spring Boot might just do the trick!

The following night, after everyone had gone to sleep, Guidance found Greg’s laptop, and fired up IntelliJ. Using the code examples from the book, he was able to draft up some new ideas.

“Wow! Wait until Santa see this!”

The next night, Guidance watched the Learning Spring Boot video, and saw even more things not covered in the first book. (Guidance used earphones so as not awake anyone while watching the video).

Using new things learned in the video, he made more changes to his demo app. He planned a demo the following night with Santa’s technical team, including how the video showed debugging in the cloud using Spring Tool Suite.

The team was impressed. They began to talk among themselves. Their technical troubles could be cured!

A few nights later on ElfSlack, the senior designer contacted Guidance. The buzz about Spring Boot had spurred him to buy copies of the book and video for the whole team. But that wasn’t what he was calling about. Instead, he wanted to share something more exciting than that.

A 2nd Edition was in progress. A newer version of the book that would include Spring 5 and Spring Boot 2, including its reactive streams-based, non-blocking, async programming model. Guidance blinked with excitement.

Guidance had already coded half a dozen sample app with eagerness. Spring Boot had changed his view of writing software. But the idea that he could seamlessly write reactive code without giving up the existing power of Spring was unbelievable.

This amazed him so much that he logged onto Amazon and pre-ordered his own copy.

He had seen more magic this year than all other Christmases combined.

So much, in fact, that he had a new idea.

“I wonder if I could convince James Watters to made a special trip to the North Pole and give a talk about Pivotal Cloud Foundry.”

The answer to that…is another tale.

Merry Christmas to all and to all a good night!

 

Just finished #LearningSpringBoot 2nd Ed’s @SpringBoot + @SpringSecurity chapter

About 1:00am yesterday morning, I sent in the text for Chapter 9, Securing Your App with Spring Boot to my publisher for Learning Spring Boot. I decided to take things to the next level in security by locking down a microservice-based solution.

I spent about three weeks working on the code. I wanted it just right. Another week was spent crafting the prose to go along with it. Instead of JUST writing a security policy, I introduced a refactoring. After all, when’s the last time YOU secured an app and didn’t have to refactor something due to unforeseen issues?

I also bring in Spring Session. When working with microservices, we need a way to smoothly share the user’s current session and this project does it with elegance.

Of course, there’s a big caveat: no two secured systems ever look identical. Spring Security can handle all your needs, but there is no way to document all permutations. So this introduces one keen solution, as general as I felt could be made. But with strong suggest that the reader delve into other books and the project’s own reference docs.

All in all, I hope my readers enjoy it. It’s the last chapter before we take the app we’ve been building to production (next chapter, Taking Your App to Production with Spring Boot).

Happy reading!

#LearningSpringBoot – 1st edition vs 2nd edition

wayback-machineSomething I have unique insight into is what the approach to the 2014 1st edition vs. the 2017 soon-to-be 2nd edition. Most “next editions” are written by other authors. Not here.

I wrote the first by myself and I’m writing the second one now.

The 1st edition was relatively short. I had pitched ten chapters but Packt would only greenlight five. It’s only fair to point out that Spring Boot had just reached 1.0 GA release only a few months before my pitch. It wasn’t a “proven” technology yet.

learning-spring-bootSo I pushed forward. With just five chapters, I narrowed the scope to the most critical things people wanted.

  • Core stuff: building web apps with Spring MVC, Spring Security, and Spring Data.
  • Given Boot was so new, I spent a chapter on debugging and maintaining apps, and helping people understand autoconfiguration.
  • Also showed the magic of the Groovy-based Spring Boot CLI.
  • Threw in a little about profiles and switching between development and production.

Many things I wanted to cover just didn’t make the cut.

b05771_mockupcover_normalWhich brings me to the 2nd edition. We’ve got ten chapters and a clean slate. The field is wide open. This isn’t some rehash to turn a nickel. (That type of work frankly bores me!)

This edition is aimed at Spring Boot 2.0, which will be based on Spring Framework 5.0. Some of the goodies include:

  • Reactive Streams API found in Spring MVC, Spring Data, and to some degree, Spring Cloud.
  • Spring Cloud was just getting started back in 2014. Today, it’s a staple toolbox used for any cloud native/microservice solutions.
  • Reactive apps use asynchronous, non-blocking paradigms. Messaging and WebSockets with Spring Boot really shines here.
  • Unit testing, embedded integration testing, mock testing, and slice testin
  • Taking your app to production

junior-devAll these things are various facets where Spring Boot kicks major booty. And I plan to cover all of them. My goal is to write a down-to-earth title that helps people build Real World apps. Spring Boot is such a popular tool for serving customer needs, I can’t wait to deliver.