We want our microservices to be replicable, replaceable workers that we can easily upgrade or downgrade without any downtime and minimal management. We might say we want them to be our minions. In this article we’ll walk through a simple example to see what Kubernetes can do for us by creating and orchestrating an army of minions. You can code along with this article or clone the project from here.

Prerequisites

We will need to containerize our microservices to run them in Kubernetes—we’ll use Docker for this. Rather than using a cloud-hosted Kubernetes we’ll use Minikube so that we can sandbox locally.

The Aim

Our minion army will be Java microservices. We want different types of minions in our army so that we see what Kubernetes can do for us. So we’ll aim for each microservice to respond to a simple http request with a response like:

We’ll use ASCII art to represent the minion types.

Building a Java Minion Service

We can kickstart our microservice as a Spring Boot Web app using the Spring Initializr with the Web starter dependency:

In the project we’ll create a Controller annoted with @RestController to handle requests. We’ll use an @RequestMapping(method=GET) to provide a response body. So to start with we can do something like:

@RequestMapping( method=GET)
@ResponseBody
public String minion() throws UnknownHostException {
​
   StringBuilder stringBuilder = new StringBuilder();
   stringBuilder.append("Host: ").append(InetAddress.getLocalHost().getHostName()).append("<br/>");
   return stringBuilder.toString();
​
}

But this won’t quite give us what we want. We could output the ASCII art here but which minion type do we choose? For this we can use a trick. We’ll create one app that can take the form of any minion type we choose. To do that we’ll need it to contain a library of ASCII art minions. So we create a class called MinionsLibrary that we annotate with @Component and inside we create a map that we initialise with some minions from this blog :

@Component
public class MinionsLibrary {
​
    private Map<String,String> map = new HashMap<>();
​
    public MinionsLibrary(){
​
      map.put("one-eyed-minion",<COPY-PASTE MINION ASCII ART HERE>);
      map.put("two-eyed-minion",<COPY-PASTE MINION ASCII ART HERE>);
      map.put("sad-minion",<COPY-PASTE MINION ASCII ART HERE>);
      map.put("happy-minion",<COPY-PASTE MINION ASCII ART HERE>);
​
    }
}

#java #devops #microservices #docker #spring boot #kubernetes #introduction #spring boot 2 #minikube #spring boot microservices

Minions in Minikube - A Kubernetes Intro for Java Developers
1.65 GEEK