Spring 5.0 Microservices(Second Edition)
上QQ阅读APP看书,第一时间看更新

Developing a Spring Boot microservice

The easiest way to develop and demonstrate Spring Boot's capabilities is by using the Spring Boot CLI, a command-line tool.

The following are the steps to set up and run Spring Boot CLI:

  1. Install the Spring Boot command-line tool by downloading the spring-boot-cli-2.0.0.BUILD-M1-bin.zip file from the following location URL:
    https://repo.spring.io/milestone/org/springframework/boot/spring-boot-cli/2.0.0.M1/
  1. Unzip the file into a directory of choice. Open a terminal window, and change the terminal prompt to the bin folder.
Ensure that the /bin folder is added to the system path so that Spring Boot can be run from any location. Otherwise, execute from the bin folder by using the command ./spring.
  1. Verify the installation with the following command. If successful, the Spring CLI version will be printed on the console as shown:
      $spring –-version
Spring CLI v2.0.0.M1
  1. As the next step, a quick REST service will be developed in groovy, which is supported out of the box in Spring Boot. To do so, copy and paste the following code using any editor of choice, and save it as myfirstapp.groovy into any folder:
        @RestController
class HelloworldController {
@RequestMapping("/")
String sayHello(){
return "Hello World!"
}
}
  1. In order to run this groovy application, go to the folder where myfirstapp.groovy is saved, and execute the following command. The last few lines of the server startup log will be as shown in the following command snippet:
      $spring run myfirstapp.groovy 
2016-12-16 13:04:33.208 INFO 29126 --- [ runner-0]
s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on
port(s):
8080 (http)
2016-12-16 13:04:33.214 INFO 29126 --- [ runner-0]
o.s.boot.SpringApplication : Started application in 4.03
seconds (JVM running for 104.276)
  1. Open a browser window, and point the URL to http://localhost:8080; the browser will display the following message:
        Hello World! 

There is no war file created and no Tomcat server was running. Spring Boot automatically picked up Tomcat as the web server, and embedded it into the application. This is a very basic, minimal microservice. The @RestController, used in the previous code, will be examined in detail in the next example.