= MicroServices = https://dzone.com/articles/microservices-communication-zuul-api-gateway-1 The crux of the microservices pattern is to create an independent service which can be scaled and deployed independently. * http://microservices.io/patterns/index.html * '''Monolithic architecture''' - architect an application as a single deployable unit * '''Microservice architecture''' - architect an application as a collection of loosely coupled, services * '''Decompose by business capability''' - define services corresponding to business capabilities * '''Remote Procedure Invocation''' - use an RPI-based protocol for inter-service communication (RMI, .Net Remoting , REST (JSON), SOAP (XML) * '''Messaging''' - use asynchronous messaging for inter-service communication (JMS, RabbitMQ, Message broker) * '''API gateway''' - a service that provides each client with unified interface to services (spring cloud gateway) * '''Client-side discovery''' - client queries a service registry to discover the locations of service instances * '''Server-side discovery''' - router queries a service registry to discover the locations of service instances (spring cloud gateway) * '''Service registry''' - a database of service instance locations (eureka) * '''Self registration''' - service instance registers itself with the service registry * '''Circuit Breaker''' - invoke a remote service via a proxy that fails immediately when the failure rate of the remote call exceeds a threshold * '''Command Query Responsibility Segregation (CQRS)''' - Split the application into two parts: the command-side and the query-side. The command-side handles create, update, and delete requests and emits events when data changes. The query-side handles queries by executing them against one or more materialized views that are kept up to date by subscribing to the stream of events emitted when data changes. CRUD, command handles CUD and query the R. == Base components == * '''service registry''' (service instances locations, service discovery) * eureka 1.x Services register with Eureka and then send heartbeats to renew their leases every 30 seconds. * '''service instance''' (instances on demand) * '''API gateway''' (route requests to service instances) Zuul or Spring Cloud Gateway * https://thenewstack.io/api-gateways-age-microservices/ == kubernetes == * https://kubernetes.io/docs/concepts/overview/what-is-kubernetes/ Kubernetes has a number of features. It can be thought of as: * a container platform * a microservices platform * a portable cloud platform and a lot more. Kubernetes provides a container-centric management environment. It orchestrates computing, networking, and storage infrastructure on behalf of user workloads. This provides much of the simplicity of Platform as a Service (PaaS) with the flexibility of Infrastructure as a Service (IaaS), and enables portability across infrastructure providers. The New Way is to deploy containers based on operating-system-level virtualization rather than hardware virtualization. These containers are isolated from each other and from the host: they have their own filesystems, they can’t see each others’ processes, and their computational resource usage can be bounded. They are easier to build than VMs, and because they are decoupled from the underlying infrastructure and from the host filesystem, they are portable across clouds and OS distributions. Loosely coupled, distributed, elastic, liberated micro-services: Applications are broken into smaller, independent pieces and can be deployed and managed dynamically – not a monolithic stack running on one big single-purpose machine. * https://kubernetes.io/docs/setup/ You can run Kubernetes almost anywhere, from your laptop to VMs on a cloud provider to a rack of bare metal servers A local-machine solution is an easy way to get started with Kubernetes. You can create and test Kubernetes clusters without worrying about consuming cloud resources and quotas. Community Supported Tools * Minikube is a method for creating a local, single-node Kubernetes cluster for development and testing. Setup is completely automated and doesn’t require a cloud provider account. * Kubeadm-dind is a multi-node (while minikube is single-node) Kubernetes cluster which only requires a docker daemon. It uses docker-in-docker technique to spawn the Kubernetes cluster. * Kubernetes IN Docker is a tool for running local Kubernetes clusters using Docker container “nodes”. It is primarily designed for testing Kubernetes 1.11+. You can use it to create multi-node or multi-control-plane Kubernetes clusters === Install kubectl centos === {{{#!highlight bash cat < /etc/yum.repos.d/kubernetes.repo [kubernetes] name=Kubernetes baseurl=https://packages.cloud.google.com/yum/repos/kubernetes-el7-x86_64 enabled=1 gpgcheck=1 repo_gpgcheck=1 gpgkey=https://packages.cloud.google.com/yum/doc/yum-key.gpg https://packages.cloud.google.com/yum/doc/rpm-package-key.gpg EOF yum install -y kubectl }}} === Install kubectl binary using curl === {{{#!highlight bash curl -LO https://storage.googleapis.com/kubernetes-release/release/$(curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt)/bin/linux/amd64/kubectl chmod +x ./kubectl sudo mv ./kubectl /usr/local/bin/kubectl }}} == Spring cloud Netflix == * https://spring.io/projects/spring-cloud-netflix * '''API Gateway:''' spring cloud gateway, Zuul * '''Service registry:''' Eureka * '''Circuit breaker:''' Hystrix, resilient4j As long as Spring Cloud Netflix and Eureka Core are on the classpath any Spring Boot application with @EnableEurekaClient will try to contact a Eureka server on http://localhost:8761 (the default value of eureka.client.serviceUrl.defaultZone): Eureka server on http://eureka:8761. To run your own server use the spring-cloud-starter-netflix-eureka-server dependency and @EnableEurekaServer. * https://hub.docker.com/r/springcloud/eureka Need to add @EnableZuulProxy annotation to the Main class to make this project a Zuul proxy server. Zuul is a JVM-based router and server-side load balancer from Netflix. == Eureka + Spring Cloud gateway == * Eureka acts as a '''service discovery server''' (locator and registry) * spring cloud gateway acts as an '''API Gateway''' and load balancer === microservice chuck norris === Microservice capable of register itself in an eureka server that has default URL http://127.0.0.1:8761 . Has actuator endpoints for info and health. The HTTP port can be set using -Dserver.port=8082. ==== pom.xml ==== {{{#!highlight xml 4.0.0 bitarus.allowed.org chucknorris 0.1.0 org.springframework.boot spring-boot-starter-parent 2.6.7 org.springframework.boot spring-boot-starter-actuator org.springframework.boot spring-boot-starter-thymeleaf org.springframework.boot spring-boot-starter-web org.springframework.cloud spring-cloud-starter-netflix-eureka-client 3.1.2 com.google.code.gson gson 2.9.0 compile chucknorris.bitarus.allowed.org.Application org.springframework.boot spring-boot-maven-plugin spring-milestone http://repo.spring.io/libs-release spring-milestone http://repo.spring.io/libs-release }}} ==== src/main/java/chucknorris/bitarus/allowed/org/Application.java ==== {{{#!highlight java package chucknorris.bitarus.allowed.org; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.boot.SpringApplication; import org.springframework.context.annotation.ComponentScan; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @ComponentScan //scans for @Component beans @EnableAutoConfiguration @EnableEurekaClient public class Application { private static Logger logger; public static void main(String[] args) { logger = LoggerFactory.getLogger(Application.class); logger.info("Starting application"); SpringApplication.run(Application.class, args); } } }}} ==== src/main/java/chucknorris/bitarus/allowed/org/ChuckNorrisController.java ==== {{{#!highlight java package chucknorris.bitarus.allowed.org; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.ResponseBody; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.env.Environment; import com.google.gson.Gson; import java.util.stream.Collectors; import java.util.List; import java.util.ArrayList; @Controller public class ChuckNorrisController { private final Logger logger = LoggerFactory.getLogger(ChuckNorrisController.class); @Value("${server.port}") private String serverPort; private Environment env; public ChuckNorrisController(Environment env) { logger.info("ChuckNorrisController created"); this.env = env; } @RequestMapping("/chucknorris") @ResponseBody // http://localhost:8080/chucknorris public JokeResponse chucknorris() { String ret = ""; Gson gson = new Gson(); try { URL url = new URL("https://api.chucknorris.io/jokes/random"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.connect(); logger.info(Integer.toString(connection.getResponseCode())); try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"))) { StringBuilder response = new StringBuilder(); String responseLine = null; while ((responseLine = br.readLine()) != null) { response.append(responseLine.trim()); } Joke joke = gson.fromJson(response.toString(), Joke.class); List jokesList = new ArrayList(); jokesList.add(joke); List jokesList2 = jokesList.stream().map(item -> { item.setValue(item.getValue().toUpperCase()); return item; }).collect(Collectors.toList()); joke = jokesList2.get(0); ret = joke.getValue(); } } catch (Exception ex) { logger.error("error", ex); } JokeResponse jr = new JokeResponse(); jr.setResponse(ret); jr.setServerPort(serverPort); return jr; } } }}} ==== src/main/java/chucknorris/bitarus/allowed/org/Joke.java ==== {{{#!highlight java package chucknorris.bitarus.allowed.org; import com.google.gson.annotations.SerializedName; public class Joke { @SerializedName("categories") private String[] categories; @SerializedName("created_at") private String createdAt; @SerializedName("icon_url") private String iconUrl; @SerializedName("id") private String id; @SerializedName("updated_at") private String updatedAt; @SerializedName("url") private String url; @SerializedName("value") private String value; public String[] getCategories() { return this.categories; } public String getCreatedAt() { return this.createdAt; } public String getIconUrl() { return this.iconUrl; } public String getId() { return this.id; } public String getUpdatedAt() { return this.updatedAt; } public String getUrl() { return this.url; } public String getValue() { return this.value; } public void setCategories(String[] categories) { this.categories = categories; } public void setCreatedAt(String createdAt) { this.createdAt = createdAt; } public void setIconUrl(String iconUrl) { this.iconUrl = iconUrl; } public void setId(String id) { this.id = id; } public void setUpdatedAt(String updatedAt) { this.updatedAt = updatedAt; } public void setUrl(String url) { this.url = url; } public void setValue(String value) { this.value = value; } } }}} ==== src/main/java/chucknorris/bitarus/allowed/org/JokeResponse.java ==== {{{#!highlight java package chucknorris.bitarus.allowed.org; import com.google.gson.annotations.SerializedName; public class JokeResponse { @SerializedName("response") private String response; @SerializedName("serverPort") private String serverPort; public String getResponse() { return this.response; } public void setResponse(String response) { this.response = response; } public String getServerPort() { return this.serverPort; } public void setServerPort(String serverPort) { this.serverPort = serverPort; } } }}} ==== src/main/resources/application.properties ==== {{{ server.port=8080 spring.application.name=chuck-norris management.endpoints.enabled-by-default=false management.endpoint.health.enabled=true management.endpoint.info.enabled=true management.endpoints.web.exposure.include=info, health }}} === eureka-server === Acts as a '''service discovery''' (service registry and locator). Listens to port 8761. Each microservice when it's launched registers itself in the eureka server. ==== pom.xml ==== {{{#!highlight xml 4.0.0 bitarus.mooo.com eurekaserver 0.1.0 org.springframework.boot spring-boot-starter-parent 2.6.7 org.springframework.cloud spring-cloud-starter-netflix-eureka-server 3.1.2 eurekaserver.bitarus.mooo.com.Application org.springframework.boot spring-boot-maven-plugin spring-milestone http://repo.spring.io/libs-release spring-milestone http://repo.spring.io/libs-release }}} ==== src/main/java/eurekaserver/bitarus/mooo/com/Application.java ==== {{{#!highlight java package eurekaserver.bitarus.mooo.com; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; import org.springframework.boot.SpringApplication; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @SpringBootApplication @EnableEurekaServer public class Application { private static Logger logger; public static void main(String[] args) { logger = LoggerFactory.getLogger(Application.class); logger.info("Starting application eureka server"); SpringApplication.run(Application.class, args); } } }}} ==== src/main/resources/application.properties ==== {{{ server.port=8761 spring.application.name=eureka-server eureka.client.registerWithEureka=false eureka.client.fetchRegistry=false }}} === springcloud-gw-server === Acts as a '''load balancer and API gateway'''. Routes requests to the micro services registered in the eureka server. Listens to port 8111 . Example URL http://localhost:8111/chucknorris/ . ==== pom.xml ==== {{{#!highlight xml 4.0.0 bitarus.mooo.com spring-cloud-gw-server 0.1.0 org.springframework.boot spring-boot-starter-parent 2.6.7 org.springframework.boot spring-boot-actuator org.springframework.boot spring-boot-starter-webflux org.springframework.cloud spring-cloud-starter-gateway 3.1.2 org.springframework.cloud spring-cloud-starter-netflix-eureka-client 3.1.2 springcloudgwserver.bitarus.mooo.com.Application org.springframework.boot spring-boot-maven-plugin spring-milestone http://repo.spring.io/libs-release spring-milestone http://repo.spring.io/libs-release }}} ==== src/main/java/springcloudgwserver/bitarus/mooo/com/Application.java ==== {{{#!highlight java package springcloudgwserver.bitarus.mooo.com; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.boot.SpringApplication; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @SpringBootApplication @EnableEurekaClient public class Application { private static Logger logger; public static void main(String[] args) { logger = LoggerFactory.getLogger(Application.class); logger.info("Starting application spring cloud gw server"); SpringApplication.run(Application.class, args); } } }}} ==== src/main/resources/application.yaml ==== When a request made to http://localhost:8111/chucknorris/ is caught it is routed to one of the available micro services with the application name CHUCK-NORRIS . {{{#!highlight yaml server: port: 8111 spring: application: name: spring-cloud-gateway cloud: gateway: routes: - id: chuckNorrisId uri: lb://CHUCK-NORRIS predicates: - Path=/chucknorris/** eureka: client: serviceUrl: defaultZone: http://localhost:8761/eureka registry-fetch-interval-seconds: 20 management: endpoints: web: exposure: include: "*" # http://localhost:8111/chucknorris/ }}} == micro service identify language using Lucene (based on the chuck norris one) == * https://github.com/vborrego/springboot-usvc-test