Spring Boot és un framework gratuït i de codi obert basat en Java desenvolupat per Pivotal Team que s'utilitza per crear un microservei. Un microservei permet desenvolupar i implementar serveis de manera independent.
Spring Boot proporciona una bona plataforma per desenvolupar fàcilment una aplicació independent i d'entorn de producció. S'ha dissenyat especialment per evitar configuracions XML complexes, reduir el temps de desenvolupament i oferir una manera fàcil de començar amb l'aplicació. No cal configurar res, tot es configura automàticament.
En aquest tutorial, t'expliquem com implementar Spring Boot amb Nginx com a servidor intermediari invers a Ubuntu 18.04.
Requisits
- Un servidor al núvol que executi Ubuntu 18.04.
- Una contrasenya root al teu servidor al núvol.
- Java en la versió 8
Comencem
Abans de començar, assegura't que el teu servidor està actualitzat. Si no és així, pots actualitzar el teu servidor amb l'ordre següent:
# apt update && apt upgrade -ySpring Boot és una aplicació basada en Java, per la qual cosa hauràs d'instal·lar Java 8 al teu servidor. Pots instal·lar Java 8 amb l'ordre següent:
# apt install openjdk-8-jdk -yUn cop instal·lat, pots comprovar la versió de Java amb l'ordre següent:
# java -versionHauries de veure el resultat següent:
java version "1.8.0_221"
Java(TM) SE Runtime Environment (build 1.8.0_221-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.221-b11, mixed mode)Instal·la l'eina Spring Boot CLI
A continuació, hauràs d'instal·lar Spring Boot CLI i altres eines com Gradle al teu servidor al núvol. Pots crear un projecte nou fàcilment amb l'eina Spring Boot CLI.
En primer lloc, hauràs d'instal·lar SDKMAN al teu servidor vps al núvol. Pots fer-ho amb l'script següent:
# curl -s https://get.sdkman.io | bashUn cop completada la instal·lació, hauries de veure el resultat següent:
All done!
Please open a new terminal, or run the following in the existing one:
source "/root/.sdkman/bin/sdkman-init.sh"
Then issue the following command:
sdk help
Enjoy!!!A continuació, activa SDKMAN amb l'ordre següent:
# source "/root/.sdkman/bin/sdkman-init.sh"Pots comprovar totes les opcions disponibles amb sdk utilitzant l'ordre següent:
# sdk helpHauries de veure el resultat següent:
==== BROADCAST =================================================================
* 2019-09-13: Micronaut 1.2.2 released on SDKMAN! #micronautfw
* 2019-09-06: Springboot 2.1.8.RELEASE released on SDKMAN! #springboot
* 2019-09-05: Micronaut 1.2.1 released on SDKMAN! #micronautfw
================================================================================
Usage: sdk <command> [candidate] [version]
sdk offline <enable|disable>
commands:
install or i <candidate> [version]
uninstall or rm <candidate> <version>
list or ls [candidate]
use or u <candidate> [version]
default or d <candidate> [version]
current or c [candidate]
upgrade or ug [candidate]
version or v
broadcast or b
help or h
offline [enable|disable]
selfupdate [force]
update
flush <broadcast|archives|temp>
candidate : the SDK to install: groovy, scala, grails, gradle, kotlin, etc.
use list command for comprehensive list of candidates
eg: $ sdk list
version : where optional, defaults to latest stable if not provided
eg: $ sdk install groovy
A continuació, pots instal·lar Spring Boot utilitzant l'ordre que es mostra més avall:
# sdk install springbootUn cop instal·lat, hauries d'obtenir el resultat següent:
###############################################################################
######################################################### 100.0%
Installing: springboot 2.1.8.RELEASE
Done installing!
Setting springboot 2.1.8.RELEASE as default.També pots comprovar la versió de Spring Boot amb l'ordre següent:
# spring versionHauries de veure el resultat següent:
Spring CLI v2.1.8.RELEASEA continuació, instal·la gradle executant l'ordre següent:
# sdk install gradle 4.5.1Crea un fitxer Jar amb Gradle
A continuació, crea un projecte nou anomenat hello-world amb Spring Boot CLI i Gradle executant l'ordre següent:
# spring init --build=gradle --dependencies=web --name=hello hello-worldAquesta ordre crearà un directori de projecte nou anomenat hello-world al teu directori principal, tal com es mostra més avall:
Using service at https://start.spring.io
Project extracted to '/root/hello-world'Pots llistar tots els paràmetres disponibles amb Spring Boot CLI executant l'ordre següent:
# spring init --listHauries de veure el resultat següent:
Project types (* denotes the default)
+-----------------+-----------------------------------------+-----------------------------+
| Id | Description | Tags |
+-----------------+-----------------------------------------+-----------------------------+
| gradle-build | Generate a Gradle build file | build:gradle,format:build |
| gradle-project | Generate a Gradle based project archive | build:gradle,format:project |
| maven-build | Generate a Maven pom.xml | build:maven,format:build |
| maven-project * | Generate a Maven based project archive | build:maven,format:project |
+-----------------+-----------------------------------------+-----------------------------+
Parameters
+-------------+------------------------------------------+------------------------------+
| Id | Description | Default value |
+-------------+------------------------------------------+------------------------------+
| artifactId | project coordinates (infer archive name) | demo |
| bootVersion | spring boot version | 2.1.8.RELEASE |
| description | project description | Demo project for Spring Boot |
| groupId | project coordinates | com.example |
| javaVersion | language level | 1.8 |
| language | programming language | java |
| name | project name (infer application name) | demo |
| packageName | root package | com.example.demo |
| packaging | project packaging | jar |
| type | project type | maven-project |
| version | project version | 0.0.1-SNAPSHOT |
+-------------+------------------------------------------+------------------------------+
A continuació, canvia al directori hello-world i obre el teu fitxer hello-world de Java:
# cd hello-world
# nano src/main/java/com/example/helloworld/HelloApplication.javaFes els canvis següents:
package com.example.helloworld;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
@SpringBootApplication
public class HelloApplication {
public static void main(String[] args) {
SpringApplication.run(HelloApplication.class, args);
}
}
@RestController
class Hello {
@RequestMapping("/")
String index() {
return "Hello world";
}
}
Desa i tanca el fitxer. Després, construeix l'aplicació amb l'ordre següent:
# ./gradlew buildHauries de veure el resultat següent:
Downloading https://services.gradle.org/distributions/gradle-5.6.2-bin.zip
.........................................................................................
Welcome to Gradle 5.6.2!
Here are the highlights of this release:
- Incremental Groovy compilation
- Groovy compile avoidance
- Test fixtures for Java projects
- Manage plugin versions via settings script
For more details see https://docs.gradle.org/5.6.2/release-notes.html
Starting a Gradle Daemon (subsequent builds will be faster)
> Task :test
2019-09-14 06:40:09.170 INFO 6852 --- [ Thread-4] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
BUILD SUCCESSFUL in 38s
5 actionable tasks: 5 executedDesprés, executa l'aplicació amb l'ordre següent:
# java -jar build/libs/hello-world-0.0.1-SNAPSHOT.jarAra la teva aplicació s'està executant en un servlet Tomcat al port 8080, tal com es mostra més avall:
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.1.8.RELEASE)
2019-09-14 07:02:50.820 INFO 14121 --- [ main] com.example.helloworld.HelloApplication : Starting HelloApplication on ubuntu with PID 14121 (/root/hello-world/build/libs/hello-world-0.0.1-SNAPSHOT.jar started by root in /root/hello-world)
2019-09-14 07:02:50.823 INFO 14121 --- [ main] com.example.helloworld.HelloApplication : No active profile set, falling back to default profiles: default
2019-09-14 07:02:51.607 INFO 14121 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
Després, prem CTRL+C per aturar l'aplicació i tornar-la a executar amb Gradle:
# gradle bootRunHauries de veure el resultat següent:
Starting a Gradle Daemon, 1 incompatible Daemon could not be reused, use --status for details
> Task :bootRun
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.1.8.RELEASE)
2019-09-14 07:32:00.883 INFO 15562 --- [ main] com.example.helloworld.HelloApplication : Starting HelloApplication on ubuntu with PID 15562 (/root/hello-world/build/classes/java/main started by root in /root/hello-world)
2019-09-14 07:32:00.886 INFO 15562 --- [ main] com.example.helloworld.HelloApplication : No active profile set, falling back to default profiles: default
2019-09-14 07:32:05.724 INFO 15562 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
Crea un fitxer de servei Systemd per a Spring Boot
A continuació, hauràs de crear un fitxer de servei systemd per gestionar la teva aplicació. Pots fer-ho amb l'ordre següent:
# nano /etc/systemd/system/helloworld.serviceAfegeix les línies següents:
[Unit]
Description=Spring Boot HelloWorld
After=syslog.target
After=network.target
[Service]
User=root
Type=simple
ExecStart=/usr/bin/java -jar /root/hello-world/build/libs/hello-world-0.0.1-SNAPSHOT.jar
Restart=always
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=helloworld
[Install]
WantedBy=multi-user.target
Desa i tanca el fitxer. Aleshores, torna a carregar el dimoni systemd amb l'ordre següent:
# systemctl daemon-reloadA continuació, inicia el servei helloworld i habilita'n l'inici durant l'arrencada utilitzant l'ordre següent:
# systemctl start helloworld
# systemctl enable helloworldAra ja pots comprovar l'estat del teu servei amb l'ordre següent:
# systemctl status helloworldHauries de veure el resultat següent:
● helloworld.service - Spring Boot HelloWorld
Loaded: loaded (/etc/systemd/system/helloworld.service; disabled; vendor preset: enabled)
Active: active (running) since Sat 2019-09-14 07:48:45 UTC; 14s ago
Main PID: 15696 (java)
Tasks: 36 (limit: 4915)
CGroup: /system.slice/helloworld.service
└─15696 /usr/bin/java -jar /root/hello-world/build/libs/hello-world-0.0.1-SNAPSHOT.jar
Sep 14 07:48:46 ubuntu helloworld[15696]: 2019-09-14 07:48:46.264 INFO 15696 --- [ main] com.example.helloworld.HelloApplication :
Sep 14 07:48:46 ubuntu helloworld[15696]: 2019-09-14 07:48:46.268 INFO 15696 --- [ main] com.example.helloworld.HelloApplication :
Sep 14 07:48:47 ubuntu helloworld[15696]: 2019-09-14 07:48:47.195 INFO 15696 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer :
Sep 14 07:48:47 ubuntu helloworld[15696]: 2019-09-14 07:48:47.221 INFO 15696 --- [ main] o.apache.catalina.core.StandardService :
Configura Nginx com a servidor intermediari invers
A continuació, hauràs de configurar Nginx com a servidor intermediari invers per reenviar les peticions del port 80 al 8080. Primer, instal·la el servidor Nginx executant l'ordre següent:
# apt-get install nginx -yUn cop instal·lat, crea un fitxer nou de configuració d'amfitrió virtual per a la teva aplicació amb l'ordre següent:
# nano /etc/nginx/conf.d/helloworld.confAfegeix les línies següents:
server {
listen 80;
listen [::]:80;
server_name example.com;
location / {
proxy_pass http://localhost:8080/;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Port $server_port;
}
}Desa i tanca el fitxer. Després, reinicia el servei Nginx per aplicar els canvis de configuració amb l'ordre següent:
# systemctl restart nginxProva la teva aplicació
L'aplicació Spring Boot ja està instal·lada i configurada amb Nginx. Pots accedir-hi visitant l'URL http://ejemplo.com al teu navegador. Hauries de veure la teva aplicació a la pàgina següent:
Conclusió
Enhorabona! Has instal·lat correctament l'aplicació Spring Boot al teu servidor amb Nginx com a servidor intermediari invers. Per a més informació, pots consultar la documentació de Spring Boot.