Monday, 6 July 2020

Monolith vs MicroService Application

In Monolith Application, components are tightly coupled and developed, deployed and managed as a single entity. 



For example, as you see above diagram, all the components user interface, Caching, Service, Logging etc., are tightly coupled.

a.   Since Monolith application holds all the components tightly, to run this application we require powerful servers.

b.   Even though you are doing changes in one of the components, you need to redeploy the entire application.

c.    In-case of high load, you need to scale the system Vertically or horizontally. You can scale the server Vertically by adding some more CPU cores and additional memory.

 

Vertical Scaling

 Adding more memory and cpu cores to the same server.


Vertical Scaling has its own upper limits and not a cost-effective solution.

 

Horizontal Scaling

Adding multiple servers and running multiple instances of the application on different servers.

 

 

Even though horizontal Scaling is an ideal solution, all the components of monolith application may not scale horizontally because of design/technical limitations.

 

a.   Since all the components are tightly coupled, if you develop all the components in some ‘X’ Programming language, new features also must develop in ‘X’ Programming language.

 

Microservice Architecture

In Microservice Architecture, Application is modularized into multiple tiny services called microservices. Each microservice is loosely coupled. Each microservice can communicate with other microservice using some standard like REST.

 

Since these microservices are loosely coupled

a.   we can scale the services that are required and we can develop the services in the preferred language.

b.   We can deploy a microservice without redeploying other microservices

c.    We can scale microservices independently.


As you see above image, Services are written in different languages and scaled according to the load. Below table summarizes the same.

 

Service

Number Of Instances

Implemented language or framework

UI Component

1

Nodejs

Logging Component

1

Go

Caching Layer

2

Java

Messaging Component

1

Rust

Service Component

2

Java

Data Access Component

2

Java

 

Drawbacks of Microservices

Even though Microservices has a number of advantages over Monolith applications, it has downsides also. Suppose take an example, where a complex system is divided into hundreds of microservices,

a.   Deploying and managing these services is not easy.

b.   We need to establish communication between these microservices properly.

c.    Scaling the microservice on demand should be taken care of.

d.   When a microservice is down, another instance of microservice should spin up to make the service available.

e.   Managing the secrets among these services should be handled securely.

f.     Microservices can run in different environments, how to handle them?

g.   How to load balance this microservice?

h.   Redeploying the previous version of microservice in-case of any failure or bugs in current deployment.

 

All the above problems will be addressed using Kubernetes.

Previous                                                    Next                                                    Home

Kubernetes for beginners


      Monolith vs MicroService Application
      Introduction to Kubernetes
      Kuberentes Architecture
      Kubernetes: setup minikube in local
      Kubernetes: Hello World Application
      Hello World Application using dashboard
      What is kubectl?
      get the configuration used by kubectl
      How to check what operations you can perform against Kubernetes?
      Get Cluster information
      pods
      pod Demo
      Define a pod in yaml
      Specify the command to run in pod definition file
      Specify environment variables in Pod definition file
      Specify multiple containers in the same pod definition
      exec: Get bash shell of running container
      Namespaces
      describe: Get current Pod configuration
      kubectl logs: Read the logs
      Get Pods in all the namespaces
      Get the Pods in specific namespace
      Get the labels associated with a Pod
      Port Forwarding: Access Pods
      SecurityContext
      See the pod definition as yaml
      See the pod definition as json
      Deleting all the pods in a namespace
      Jobs
      Cron Jobs
      Limit the resources used by Pod
      Init Containers
      Different states of Pod
      Replication Controllers and ReplicaSets
      ReplicationController, ReplicationSet automatically creates new Pod
      ReplicaSet Monitor the Pods
      ReplicaSet and ReplicationController monitor pods that matches to selector labels
      Changing the Pod template do not have any impact on currently running nodes
      Delete ReplicaSet but not the Pods managed by it
      ReplicaSet can adopt previously created Pods
      Deployments
      Deployment Strategies: Rollback and update
      Rolling Update example
      Labels, Selectors, Annotations and Namespaces
      --show-labels: Get labels associated with a resource
      List specific labels
      Scheduling Pods to specific nodes
      Services
      Expose service using NodePort type
      Create a service using yaml file
      Ingress hello world
      Storage Options
      Configure PV Storage
      ConfigMaps
      Secrets
      Print the supported API resources on the server
      Print the supported API versions on the server
      kubectl explain: Get documentation about resources
      Talk to Kubernetes API Server using CURL command
      list all pods, replicasets, services and deployments
      Delete Everything from current namespace
      Working with labels
      Labels: Working with Selectors
      Health Checks
      Exploring livenessProbe
      Application upgrades
      Troubleshooting the application

Previous                                                    Next                                                    Home

Sunday, 5 July 2020

FreeMarker: Define custom directive by implementing TemplateDirectiveModel interface

In this post, I am going to explain how to define custom directive by implementing TemplateDirectiveModel interface.

 

Step 1: Create ‘LowerCaseFilterWriter’ that extends the Writer class and converts the char. Array to lowercase.

 

LowerCaseFilterWriter.java
package com.sample.app.writers;

import java.io.IOException;
import java.io.Writer;

public class LowerCaseFilterWriter extends Writer {

	private final Writer out;

	public LowerCaseFilterWriter(Writer out) {
		this.out = out;
	}

	public void write(char[] cbuf, int off, int len) throws IOException {
		char[] transformedCbuf = new char[len];
		for (int i = 0; i < len; i++) {
			transformedCbuf[i] = Character.toLowerCase(cbuf[i + off]);
		}
		out.write(transformedCbuf);
	}

	public void flush() throws IOException {
		out.flush();
	}

	public void close() throws IOException {
		out.close();
	}

} 

Step 2: Create ‘StringLowercaseDirective’ by implementing TemplateDirectiveModel interface.

 

StringLowercaseDirective.java

package com.sample.app;

import java.io.IOException;
import java.util.Map;

import com.sample.app.writers.LowerCaseFilterWriter;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;

public class StringLowercaseDirective implements TemplateDirectiveModel {

	@Override
	public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
			throws TemplateException, IOException {
		if (!params.isEmpty()) {
			throw new TemplateModelException("This directive doesn't allow parameters.");
		}
		if (loopVars.length != 0) {
			throw new TemplateModelException("This directive doesn't allow loop variables.");
		}

		if (body == null) {
			throw new RuntimeException("Please provide body");
		}

		body.render(new LowerCaseFilterWriter(env.getOut()));

	}

}

Step 3: Make the directive available to the template.

 

We can do this by adding the instance of the directive to root model object.

 

StringLowercaseDirective directive = new StringLowercaseDirective();

                 

Map<String, Object> modelObject = new HashMap<String, Object>();

modelObject.put("lower", directive);


Create a file ‘stringLowercase.ftl’ in src/main/resources/templates folder.

 

stringLowercase.ftl
HELLO, HOW ARE YOU
<@lower>
  bar
  <#-- All kind of FTL is allowed here -->
  <#list ["RED", "GREEN", "BLUE", "YELLOW", "WHITE"] as color>
    ${color}
  </#list>
  I WILL BE CONVERTED TO LOWER CASE.
</@lower>

Define StringLowercaseDirectivePopulator.

 

StringLowercaseDirectivePopulator.java

package com.sample.app;

import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import com.sample.app.util.FreeMarkerUtil;

public class StringLowercaseDirectivePopulator {
	public static void main(String args[]) throws Exception {
		StringLowercaseDirective directive = new StringLowercaseDirective();
		
		Map<String, Object> modelObject = new HashMap<String, Object>();
		modelObject.put("lower", directive);

		StringWriter stringWriter = FreeMarkerUtil.mergeModelAndTemplate(modelObject, "stringLowercase.ftl");
		System.out.println(stringWriter.toString().trim());

	}
}

Run the application, you will see below messages in the console.

HELLO, HOW ARE YOU
  bar
    red
    green
    blue
    yellow
    white
  i will be converted to lower case.

Previous                                                    Next                                                    Home

FreeMarker: macro: Define Custom Directive

‘macro’ is used to define custom directives.

 

Syntax

<#macro name param1 param2 ... paramN>
  ...
  <#nested loopvar1, loopvar2, ..., loopvarN>
  ...
  <#return>
  ...
</#macro>

‘name’: Name of Macro variable.

param1, param2, ...:  The name of the local variables store the parameter values

paramN: the last parameter may optionally have 3 trailing dots (...), which indicates that the macro takes a variable number of parameters

loopvar1, loopvar2, ...etc.: Optional. The values of loop variables that the nested directive wants to create for the nested content.

 

Example

<#macro quotations>
	- Be yourself; everyone else is already taken.
	- Be the change that you wish to see in the world.
	- Live as if you were to die tomorrow. 
</#macro>

‘macro’ directive itself does not print anything. Information between <#macro quotations> and <#macro> will be executed only when you use the variable ‘quotations’ as a directive.

 

How to use user-defined directive?

Use @symbol to call the directive.

 

Example

<@quotations></@quotations>

 

Find the below working application.

 

Step 1: Define 'macroDef1.ftl' file under src/main/resources/templates folder.

 

macroDef1.ftl

<#macro quotations>
	- Be yourself; everyone else is already taken.
	- Be the change that you wish to see in the world.
	- Live as if you were to die tomorrow. 
</#macro>

Printing Quotations
<@quotations></@quotations>

Printing Quotations Again
<@quotations></@quotations>

Step 2: Define ‘FreeMarkerUtil’ class that takes model class and template file as input and merge them.

 

FreeMarkerUtil.java

package com.sample.app.util;

import java.io.StringWriter;
import java.util.Locale;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;

public class FreeMarkerUtil {

	private static final Configuration FREE_MARKER_CONFIGURATION = new Configuration(Configuration.VERSION_2_3_30);

	static {
		FREE_MARKER_CONFIGURATION.setClassForTemplateLoading(FreeMarkerUtil.class, "/templates/");
		FREE_MARKER_CONFIGURATION.setDefaultEncoding("UTF-8");
		FREE_MARKER_CONFIGURATION.setLocale(Locale.US);
		FREE_MARKER_CONFIGURATION.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
		FREE_MARKER_CONFIGURATION.setFallbackOnNullLoopVariable(false);
	}

	public static StringWriter mergeModelAndTemplate(Object modelObject, String ftlFile) throws Exception {
		StringWriter stringWriter = new StringWriter();

		Template template = FREE_MARKER_CONFIGURATION.getTemplate(ftlFile);

		template.process(modelObject, stringWriter);

		return stringWriter;
	}

}

Step 3: Define MacroDef1Populator.

 

MacroDef1Populator.java

package com.sample.app;

import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import com.sample.app.util.FreeMarkerUtil;

public class MacroDef1Populator {
    public static void main(String args[]) throws Exception {

        Map<String, Object> modelObject = new HashMap<String, Object>();

        StringWriter stringWriter = FreeMarkerUtil.mergeModelAndTemplate(modelObject, "macroDef1.ftl");
        System.out.println(stringWriter.toString().trim());

    }
}

Run the application, you will see below messages in the console.

Printing Quotations
    - Be yourself; everyone else is already taken.
    - Be the change that you wish to see in the world.
    - Live as if you were to die tomorrow. 

Printing Quotations Again
    - Be yourself; everyone else is already taken.
    - Be the change that you wish to see in the world.
    - Live as if you were to die tomorrow.

Passing Parameters to a macro

<#macro sum a b>

    Sum of ${a} and ${b} is ${a+b}

</#macro>

 

You can call the sum macro with parameters 10 and 20 like below.

<@sum 10 20></@sum>

 

You can even call the macro with variable names.

 

For example,

<#macro employee id name age>

    Hi ${name}, your id is ${id} and you are ${age} years old

</#macro>

 

You can call the employee directive like below.

<@employee id=76 name="Ram" age=32></@employee>

 

If you use variable names, then the order of variables doesn’t matter.

 

macroParameters.ftl

<#macro sum a b>
    Sum of ${a} and ${b} is ${a+b}
</#macro>

<@sum 10 20></@sum>
<@sum 20 30></@sum>
<@sum 30 40></@sum>

<#macro employee id name age>
    Hi ${name}, your id is ${id} and you are ${age} years old
</#macro>

<@employee 123 "Krishna" 31></@employee>
<@employee id=76 name="Ram" age=32></@employee>

MacroParametersPopulator.java

package com.sample.app;

import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import com.sample.app.util.FreeMarkerUtil;

public class MacroParametersPopulator {
    public static void main(String args[]) throws Exception {

        Map<String, Object> modelObject = new HashMap<String, Object>();

        StringWriter stringWriter = FreeMarkerUtil.mergeModelAndTemplate(modelObject, "macroParameters.ftl");
        System.out.println(stringWriter.toString());

    }
}

Output

    Sum of 10 and 20 is 30
    Sum of 20 and 30 is 50
    Sum of 30 and 40 is 70


    Hi Krishna, your id is 123 and you are 31 years old
    Hi Ram, your id is 76 and you are 32 years old

Providing default value to variables in a macro

For example, I defined sum macro like below.

 

<#macro sum a=10 b=20>

    Sum of ${a} and ${b} is ${a+b}

</#macro>

 

If you do not pass any values to the macro sum, then 10 is taken as the default value for the variable a, and 20 is taken as the default value for the variable b.

 

<@sum></@sum>: Call the macro sum. Since we do not pass any values a is assigned with value 10 and b is assigned with value 20.

 

<@sum 19></@sum>: Since I passed 19 as an argument, 'a' will be assigned with value 19, and 'b' will be assigned to the default value which is 20.

 

<@sum b=40></@sum>: Since I do not pass any value to the variable 'a', it will be assigned with default value 10.

 

macroDefaultValues.ftl

<#macro sum a=10 b=20>
    Sum of ${a} and ${b} is ${a+b}
</#macro>

<@sum></@sum>
<@sum 19></@sum>
<@sum b=40></@sum>

MacroDefaultValuePopulator.java

package com.sample.app;

import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import com.sample.app.util.FreeMarkerUtil;

public class MacroDefaultValuePopulator {
    public static void main(String args[]) throws Exception {

        Map<String, Object> modelObject = new HashMap<String, Object>();

        StringWriter stringWriter = FreeMarkerUtil.mergeModelAndTemplate(modelObject, "macroDefaultValues.ftl");
        System.out.println(stringWriter.toString());

    }
}

Output

    Sum of 10 and 20 is 30
    Sum of 19 and 20 is 39
    Sum of 10 and 40 is 50

Nested content

We can pass content to a custom directive and it can be accessed using ‘nested’ directive.


For example, I defined a macro as below.

 

<#macro welcome name>

    <#nested> ${name}

</#macro>

 

<@welcome "Krishna">Good Morning</@welcome>

Prints "Good Morning Krishna"

 

<@welcome "Narasimha">Good Afternoon</@welcome>

Prints "Good Afternoon Narasimha"

 

<@welcome "Loopa">Good Evening</@welcome>

Prints "Good Evening Loopa"

 

Find the below working application.

 

macroNestedContent.ftl

<#macro welcome name>
    <#nested> ${name}
</#macro>

<@welcome "Krishna">Good Morning</@welcome>
<@welcome "Narasimha">Good Afternoon</@welcome>
<@welcome "Loopa">Good Evening</@welcome>

MacroNestedContentPopulator.java

package com.sample.app;

import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import com.sample.app.util.FreeMarkerUtil;

public class MacroNestedContentPopulator {
    public static void main(String args[]) throws Exception {

        Map<String, Object> modelObject = new HashMap<String, Object>();

        StringWriter stringWriter = FreeMarkerUtil.mergeModelAndTemplate(modelObject, "macroNestedContent.ftl");
        System.out.println(stringWriter.toString());

    }
}

Output

    Good Morning Krishna

    Good Afternoon Narasimha

    Good Evening Loopa

Note

a.   Local variables of macro do not visible in nested content.



Previous                                                    Next                                                    Home

FreeMarker: Define Custom Directive

There are two ways to define custom directives in FreeMarker.

a.   Using macro directive

b.   By implementing TemplateDirectiveModel interface.



Previous                                                    Next                                                    Home