microservices
#microservi
ces
Tabla de contenido
Acerca de 1
Capítulo 1: Empezando con microservicios 2
Observaciones 2
Examples 2
Lista de verificación esencial para la plataforma de microservicios 2
Documentación de la API 2
Muestra para documentación de API 6
Capítulo 2: Puerta de enlace API 14
Introducción 14
Examples 14
Visión general 14
Creditos 16
Acerca de
You can share this PDF with anyone you feel could benefit from it, downloaded the latest version
from: microservices
It is an unofficial and free microservices ebook created for educational purposes. All the content is
extracted from Stack Overflow Documentation, which is written by many hardworking individuals at
Stack Overflow. It is neither affiliated with Stack Overflow nor official microservices.
The content is released under Creative Commons BY-SA, and the list of contributors to each
chapter are provided in the credits section at the end of this book. Images may be copyright of
their respective owners unless otherwise specified. All trademarks and registered trademarks are
the property of their respective company owners.
Use the content presented in this book at your own risk; it is not guaranteed to be correct nor
accurate, please send your feedback and corrections to [email protected]
https://riptutorial.com/es/home 1
Capítulo 1: Empezando con microservicios
Observaciones
Esta sección proporciona una descripción general de qué son los microservicios y por qué un
desarrollador puede querer usarlos.
También debe mencionar cualquier tema grande dentro de microservicios y vincular a los temas
relacionados. Dado que la Documentación para microservicios es nueva, es posible que deba
crear versiones iniciales de los temas relacionados.
Examples
Lista de verificación esencial para la plataforma de microservicios
• Pipeline CI / CD
• Servicio centralizado de autenticación y autorización.
• Documentación de la API
• Puerta de enlace API
• Centralizar la herramienta de gestión de registro
• Monitor de servicio
• Automatización de infraestructura
• Servidor de configuración centralizado
Documentación de la API
Utilice Spring REST Docs para documentar sus servicios. Es un marco poderoso que asegura
que la lógica del Servicio esté siempre en línea con la documentación. Para hacerlo, tendría que
escribir pruebas de integración para sus servicios.
Si hay alguna falta de coincidencia en la documentación y el comportamiento del servicio, las
pruebas fallarán.
Aquí hay un ejemplo de ejemplo para generar documentos para un proyecto de Maven.
Agregue esta dependencia en su pom:
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-rest-webmvc</artifactId>
<version>2.6.6.RELEASE</version>
</dependency>
y agregue el complemento asciidoc en la etiqueta build.plugins:
<plugin>
https://riptutorial.com/es/home 2
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctor-maven-plugin</artifactId>
<version>1.5.3</version>
<executions>
<execution>
<id>generate-docs</id>
<phase>prepare-package</phase>
<goals>
<goal>process-asciidoc</goal>
</goals>
<configuration>
<backend>html</backend>
<doctype>book</doctype>
</configuration>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.springframework.restdocs</groupId>
<artifactId>spring-restdocs-asciidoctor</artifactId>
<version>1.2.0.RELEASE</version>
</dependency>
</dependencies>
</plugin>
Ahora vamos a tomar un controlador de muestra que queremos documentar:
package com.hospital.user.service.controller;
import org.springframework.hateoas.Resource;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.hospital.user.service.entity.User;
import com.hospital.user.service.exception.UserNotFoundException;
import com.hospital.user.service.repository.UserCrudRepository;
import com.hospital.user.service.resource.assembler.UserResourceAssembler;
@Controller
@RequestMapping("/api/user")
public class SampleController {
final UserCrudRepository userRepository;
final UserResourceAssembler userResourceAssembler;
final BCryptPasswordEncoder passwordEncoder;
public SampleController(UserCrudRepository userCrudRepository, UserResourceAssembler
userResourceAssembler, BCryptPasswordEncoder passwordEncoder){
this.userRepository = userCrudRepository;
this.userResourceAssembler = userResourceAssembler;
https://riptutorial.com/es/home 3
this.passwordEncoder = passwordEncoder;
}
@RequestMapping(method = RequestMethod.GET, value = "/{userId}", produces = {
MediaType.APPLICATION_JSON_VALUE})
ResponseEntity<Resource<User>> getUser(@PathVariable String userId){
User user = (User) this.userRepository.findOne(userId);
if(user==null){
throw new UserNotFoundException("No record found for userid"+ userId);
}
Resource<User> resource = this.userResourceAssembler.toResource(user);
return new ResponseEntity<Resource<User>>(resource, HttpStatus.OK);
}
}
Ahora escribe un caso de prueba para el servicio:
package com.hospital.user.service;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.restdocs.JUnitRestDocumentation;
import org.springframework.restdocs.mockmvc.RestDocumentationResultHandler;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint;
import static
org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessRequest;
importar estática
org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static
org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get;
import static org.springframework.restdocs.headers.HeaderDocumentation.headerWithName;
import static org.springframework.restdocs.headers.HeaderDocumentation.responseHeaders;
import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath;
import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields;
@RunWith(SpringJUnit4ClassRunner.class)
https://riptutorial.com/es/home 4
@WebAppConfiguration
@EnableWebMvc
@ComponentScan( basePackages = { "com.hospital.user.service" } )
@SpringBootTest
public class SampleControllerTest {
private RestDocumentationResultHandler documentationHandler;
@Rule public final JUnitRestDocumentation restDocumentation = new
JUnitRestDocumentation("target/generated-snippets");
@Autowired private WebApplicationContext context;
private MockMvc mockMvc;
@Before
public void setUp(){
this.documentationHandler = document("{method-name}", //this will create files with
the test method name
preprocessRequest(prettyPrint()), // to print the request
preprocessResponse(prettyPrint()));
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context)
.apply(documentationConfiguration(this.restDocumentation)
.uris()
//.withScheme("https") Specify this for https
.withHost("recruitforceuserservice") //Define the host name
.withPort(8443)
)
.alwaysDo(this.documentationHandler)
.build();
}
@Test
public void getUser() throws Exception {
// tag::links[]
this.mockMvc.perform(get("/api/user/"+"591310c3d5eb3a37183ab0d3").header("Authorization",
"Bearer
eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJiaGFyZHdhai5uaXRpc2gxOSIsInJvbGVzIjpbIkFETUlOIl0sImlzcyI6Imh0dHA6Ly9ob3
.andExpect(status().isOk())
.andDo(this.documentationHandler.document(
responseHeaders(
headerWithName("Content-Type").description("The Content-Type
of the payload: `application/json`") // Asserts that the response should have this header.
),
responseFields(
fieldWithPath("username").description("Unique name for the
record"), // Asserts that the response should have this field
fieldWithPath("password").description("password of the user"),
fieldWithPath("securityAnswer").description("Security answer
which would be used to validate the user while the password is reset."),
fieldWithPath("securityQuestion").description("Security
question to reset the password"),
fieldWithPath("email").description("Email of the user"),
fieldWithPath("roles").description("Assigned roles of the
user"),
fieldWithPath("id").description("Unique identifier of an
https://riptutorial.com/es/home 5
user"),
fieldWithPath("_links").ignored()
)
));
}
Siga esta referencia para obtener más detalles: http://docs.spring.io/spring-
restdocs/docs/current/reference/html5/
Muestra para documentación de API
Utilice Spring REST Docs para documentar sus servicios. Es un marco poderoso que asegura
que la lógica del Servicio esté siempre en línea con la documentación. Para hacerlo, tendría que
escribir pruebas de integración para sus servicios.
Si hay alguna falta de coincidencia en la documentación y el comportamiento del servicio, las
pruebas fallarán.
Aquí hay un ejemplo de ejemplo para generar documentos en un proyecto de Maven:
Agregue esta dependencia en el archivo pom:
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-rest-webmvc</artifactId>
<version>2.6.6.RELEASE</version>
</dependency>
Además, agregue el complemento de documentos ASCII para generar documentos bajo la
etiqueta build.puglin
<plugin>
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctor-maven-plugin</artifactId>
<version>1.5.3</version>
<executions>
<execution>
<id>generate-docs</id>
<phase>prepare-package</phase>
<goals>
<goal>process-asciidoc</goal>
</goals>
<configuration>
<backend>html</backend>
<doctype>book</doctype>
</configuration>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.springframework.restdocs</groupId>
<artifactId>spring-restdocs-asciidoctor</artifactId>
https://riptutorial.com/es/home 6
<version>1.2.0.RELEASE</version>
</dependency>
</dependencies>
</plugin>
Ahora, como ejemplo, creemos un servicio de controlador que queremos documentar.
package com.hospital.user.service.controller;
import org.springframework.hateoas.Resource;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.hospital.user.service.entity.User;
import com.hospital.user.service.exception.UserNotFoundException;
import com.hospital.user.service.repository.UserCrudRepository;
import com.hospital.user.service.resource.assembler.UserResourceAssembler;
@Controller
@RequestMapping("/api/user")
public class SampleController {
final UserCrudRepository userRepository;
final UserResourceAssembler userResourceAssembler;
final BCryptPasswordEncoder passwordEncoder;
public SampleController(UserCrudRepository userCrudRepository, UserResourceAssembler
userResourceAssembler, BCryptPasswordEncoder passwordEncoder){
this.userRepository = userCrudRepository;
this.userResourceAssembler = userResourceAssembler;
this.passwordEncoder = passwordEncoder;
}
@RequestMapping(method = RequestMethod.GET, value = "/{userId}", produces = {
MediaType.APPLICATION_JSON_VALUE})
ResponseEntity<Resource<User>> getUser(@PathVariable String userId){
User user = (User) this.userRepository.findOne(userId);
if(user==null){
throw new UserNotFoundException("No record found for userid"+ userId);
}
Resource<User> resource = this.userResourceAssembler.toResource(user);
return new ResponseEntity<Resource<User>>(resource, HttpStatus.OK);
}
Vamos a escribir un caso de prueba para probar este servicio:
https://riptutorial.com/es/home 7
package com.hospital.user.service;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.restdocs.JUnitRestDocumentation;
import org.springframework.restdocs.mockmvc.RestDocumentationResultHandler;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint;
import static
org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessRequest;
import static
org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static
org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get;
import static org.springframework.restdocs.headers.HeaderDocumentation.headerWithName;
import static org.springframework.restdocs.headers.HeaderDocumentation.responseHeaders;
import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath;
import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@EnableWebMvc
@ComponentScan( basePackages = { "com.hospital.user.service" } )
@SpringBootTest
public class SampleControllerTest {
private RestDocumentationResultHandler documentationHandler;
@Rule public final JUnitRestDocumentation restDocumentation = new
JUnitRestDocumentation("target/generated-snippets");
@Autowired private WebApplicationContext context;
private MockMvc mockMvc;
@Before
public void setUp(){
this.documentationHandler = document("{method-name}", //Documents would be generated
by the test method name.
preprocessRequest(prettyPrint()), //To print request
preprocessResponse(prettyPrint()));
https://riptutorial.com/es/home 8
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context)
.apply(documentationConfiguration(this.restDocumentation)
.uris()
//.withScheme("https") Specify this for https
.withHost("recruitforceuserservice") //To use the hostname
.withPort(8443)
)
.alwaysDo(this.documentationHandler)
.build();
}
@Test
public void getUser() throws Exception {
// tag::links[]
this.mockMvc.perform(get("/api/user/"+"591310c3d5eb3a37183ab0d3").header("Authorization",
"Bearer
eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJiaGFyZHdhai5uaXRpc2gxOSIsInJvbGVzIjpbIkFETUlOIl0sImlzcyI6Imh0dHA6Ly9ob3
.andExpect(status().isOk())
.andDo(this.documentationHandler.document(
responseHeaders(
headerWithName("Content-Type").description("The Content-Type
of the payload: `application/json`")//Asserts that the response has this header.
),
responseFields(
fieldWithPath("username").description("Unique name for the
record"), //Asserts that the response has this field.
fieldWithPath("password").description("password of the user"),
fieldWithPath("securityAnswer").description("Security answer
which would be used to validate the user while the password is reset."),
fieldWithPath("securityQuestion").description("Security
question to reset the password"),
fieldWithPath("email").description("Email of the user"),
fieldWithPath("roles").description("Assigned roles of the
user"),
fieldWithPath("id").description("Unique identifier of an
user"),
fieldWithPath("_links").ignored()
)
));
}
}
Ejecute la prueba de la unidad y algunos archivos se generarán en la carpeta de destino.
https://riptutorial.com/es/home 9
Cree una carpeta de origen como src / main / asciidocs y cree un archivo doc con un prefijo
de adoc para documentar los detalles de su servicio. Archivo doc de muestra
[[resources]]
= Resources
User: Have the information about an User. It has following fields:
include::{snippets}/get-user/response-fields.adoc[]
[[resources-user]]
== User
The User resources has all the information about the application user. This resource
is being used to perform all CRUD operations on User entity.
[[resources-user-retrieve]]
=== Retrieve User
A `GET` request gets a User.
operation::get-user[snippets='response-fields,curl-request,http-response']
La etiqueta de inclusión en el archivo doc es para incluir los fragmentos de código . Puede
especificar el formato que desee para generar el documento.
Una vez que tengas todo en su lugar, ejecuta Maven Build . Ejecutará sus pruebas y el
complemento asciidoc generará su archivo html de documento en la carpeta target.generate-
docs . Su archivo generado se vería así:
https://riptutorial.com/es/home 10
https://riptutorial.com/es/home 11
https://riptutorial.com/es/home 12
Siempre que se ejecute su compilación maven, se generará su último documento que estará
siempre en línea con sus servicios. Simplemente publique este documento a los consumidores /
clientes del servicio.
Feliz codificacion
Lea Empezando con microservicios en línea:
https://riptutorial.com/es/microservices/topic/7719/empezando-con-microservicios
https://riptutorial.com/es/home 13
Capítulo 2: Puerta de enlace API
Introducción
La arquitectura de microservicios ofrece una gran flexibilidad para desacoplar las aplicaciones y
desarrollar aplicaciones independientes. Un microservicio siempre debe ser comprobable y
desplegable de forma independiente.
Pero, como sigue teniendo demasiados servicios, es necesario tener una puerta de enlace API
.
No puede exponer todos sus servicios a clientes externos. Necesita tener alguna capa de
abstracción que actúe como un controlador de acceso para todos sus microservicios. Un punto de
entrada para todos sus servicios.
Examples
Visión general
Supongamos que tiene una nube de comercio electrónico con varios microservicios como servicio
de carrito de compras, servicio de pedidos, servicio de inventario, etc. Debe tener una puerta de
enlace API como servicio perimetral al mundo exterior.
https://riptutorial.com/es/home 14
La puerta de enlace API abstrae los detalles (host y puerto) sobre los microservicios de
subrayado. Ahora, todos sus clientes solo necesitan conocer la URL de un servidor que es su
puerta de enlace API. Cualquier cambio en cualquier otro Miroservice no requeriría ningún cambio
en su aplicación cliente. Cada vez que una puerta de enlace API recibe una solicitud, la enruta a
un Microservicio específico .
Lea Puerta de enlace API en línea: https://riptutorial.com/es/microservices/topic/10904/puerta-de-
enlace-api
https://riptutorial.com/es/home 15
Creditos
S.
Capítulos Contributors
No
Empezando con
1 Community, Dinusha, mohan08p, Nitish Bhardwaj
microservicios
2 Puerta de enlace API Nitish Bhardwaj
https://riptutorial.com/es/home 16