Aquí tienes una guía paso a paso para configurar tu entorno que incluye microservicios, un gateway, un microservicio reactivo de productos de panadería y un front-end construido con HTML, CSS y JavaScript. Esta guía te llevará a través de la configuración básica de los componentes mencionados utilizando herramientas y tecnologías comunes.
Requisitos Previos
- Java Development Kit (JDK) 11+
- Maven
- Node.js y npm
- Docker
Estructura del Proyecto
root
|-- gateway-service
|-- product-service
|-- frontend
|-- docker-compose.yml
1. Configuración del Gateway (Spring Cloud Gateway)
- Crear el Proyecto Spring Boot
$ mkdir gateway-service
$ cd gateway-service
$ mvn archetype:generate -DgroupId=com.example -DartifactId=gateway-service -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
- Agregar Dependencias en
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
<version>Hoxton.SR3</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Hoxton.SR3</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
- Configurar el Gateway en
application.yml
server:
port: 8080
spring:
cloud:
gateway:
routes:
- id: product-service
uri: http://localhost:8092
predicates:
- Path=/api/productos/**
filters:
- RewritePath=/api/productos(?<segment>/?.*), /${segment}
- Clase Principal
GatewayServiceApplication.java
package com.example.gatewayservice;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class GatewayServiceApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayServiceApplication.class, args);
}
}
2. Configuración del Microservicio Reactivo de Productos
- Crear el Proyecto Spring Boot
$ mkdir product-service
$ cd product-service
$ mvn archetype:generate -DgroupId=com.example -DartifactId=product-service -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
- Agregar Dependencias en
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
</dependencies>
- Configurar MongoDB en
application.yml
spring:
data:
mongodb:
uri: mongodb://localhost:27017/panaderia
server:
port: 8092
- Definir el Modelo
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "productos")
public class Producto {
@Id
private String id;
private String name;
private String description;
private double precio;
// Getters and Setters
}
- Repositorio
import org.springframework.data.mongodb.repository.ReactiveMongoRepository;
public interface ProductoRepository extends ReactiveMongoRepository<Producto, String> {}
- Servicio
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@Service
public class ProductoService {
@Autowired
private ProductoRepository productoRepository;
public Flux<Producto> findAll() {
return productoRepository.findAll();
}
public Mono<Producto> findById(String id) {
return productoRepository.findById(id);
}
public Mono<Producto> save(Producto producto) {
return productoRepository.save(producto);
}
public Mono<Void> deleteById(String id) {
return productoRepository.deleteById(id);
}
}
- Controlador
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@RestController
@RequestMapping("/api/productos")
public class ProductoController {
@Autowired
private ProductoService productoService;
@GetMapping
public Flux<Producto> getAllProductos() {
return productoService.findAll();
}
@GetMapping("/{id}")
public Mono<Producto> getProductoById(@PathVariable String id) {
return productoService.findById(id);
}
@PostMapping("/crear")
public Mono<Producto> createProducto(@RequestBody Producto producto) {
return productoService.save(producto);
}
@DeleteMapping("/{id}")
public Mono<Void> deleteProducto(@PathVariable String id) {
return productoService.deleteById(id);
}
}
- Clase Principal
ProductServiceApplication.java
package com.example.productservice;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ProductServiceApplication {
public static void main(String[] args) {
SpringApplication.run(ProductServiceApplication.class, args);
}
}
3. Configuración del Front-End (HTML, CSS y JavaScript)
- Estructura de Archivos del Front-End
frontend
|-- index.html
|-- formulario-registro-producto.css
|-- formulario-registro-producto.js
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Registre su producto</title>
<link rel="stylesheet" href="formulario-registro-producto.css">
<script defer src="formulario-registro-producto.js"></script>
</head>
<body>
<form id="registrarProducto">
<div>
<div>
<input type="text" name="name" id="name" placeholder="pan cereal" class="formbold-form-input">
<label for="name" class="formbold-form-label">Nombre</label>
</div>
<div>
<input type="text" name="description" id="description" placeholder="pan cereal con curcuma" class="formbold-form-input">
<label for="description" class="formbold-form-label">Descripción</label>
</div>
</div>
<div class="formbold-input-flex">
<div>
<input type="number" name="precio" id="precio" placeholder="10 euros" class="formbold-form-input">
<label for="precio" class="formbold-form-label">Precio</label>
</div>
</div>
<button id="btnRegistrar" type="submit" class="formbold-btn">Registrar producto</button>
</form>
</body>
</html>
formulario-registro-producto.css
/* Añade tus estilos aquí */
body {
font-family: Arial, sans-serif;
padding: 20px;
}
.formbold-form-input {
display: block;
width: 100%;
padding: 10px;
margin-top: 5px;
margin-bottom: 10px;
}
.formbold-form-label {
font-weight: bold;
}
.formbold-btn {
padding: 10px 20px;
background-color: #007bff;
color: white;
border: none;
cursor: pointer;
}
.formbold-btn:hover {
background-color: #0056b3;
}
formulario-registro-producto.js
document.addEventListener('DOMContentLoaded', () => {
const form = document.getElementById('registrarProducto');
form.addEventListener('submit', async (event) => {
event.preventDefault();
const name = document.getElementById('name').value;
const description = document.getElementById('description').value;
const precio = document.getElementById('precio').value;
const campos = {
name: name,
description: description,
precio: precio
};
try {
const response = await fetch('http://localhost:8080/api/productos/crear', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(campos)
});
if (!response.ok) {
throw new Error('Error en la solicitud: ' + response.statusText);
}
alert("Producto guardado con éxito");
form.reset();
} catch (error) {
console.error('Error:', error);
alert('Hubo un error al guardar el producto. Por favor, intenta nuevamente.');
}
});
});
4. Configuración de Docker y Docker Compose
- Crear Dockerfiles
gateway-service/Dockerfile
FROM openjdk:11-jre-slim
COPY target/gateway-service.jar gateway-service.jar
ENTRYPOINT ["java", "-jar", "gateway-service.jar"]
product-service/Dockerfile
FROM openjdk:11-jre-slim
COPY target/product-service.jar product-service.jar
ENTRYPOINT ["java", "-jar", "product-service.jar"]
- Crear
docker-compose.yml
version: '3.7'
services:
gateway-service:
build: ./gateway-service
ports:
- "8080:8080"
depends_on:
- product-service
product-service:
build: ./product-service
ports:
- "8092:8092"
environment:
SPRING_PROFILES_ACTIVE: docker
mongo:
image: mongo:4.2-bionic
ports:
- "27017:27017"
Pasos Finales
- Construir y Ejecutar los Microservicios
$ docker-compose up --build
-
Verifica los Servicios
Conclusión
Siguiendo esta guía, habrás configurado un entorno completo que incluye un gateway para enrutar las solicitudes a microservicios, un microservicio reactivo para la gestión de productos, y un front-end basado en HTML, CSS y JavaScript. Docker Compose facilita la gestión e interconexión de estos servicios, permitiéndote arrancar todo el stack con un solo comando.