Thursday, 30 June 2022

Atlas client: Create new type definition

In this post, I am going to explain how to create a new entity type definition in Atlas using the bulk api ‘createAtlasTypeDefs’.

 

Step 1: Get an instance of AtlasClientV2.

AtlasClientV2 atlasClient = new AtlasClientV2(new String[] { "http://localhost:21000" }, new String[] { "admin", "admin" });

 

Step 2: Define an instance of AtlasEntityDef.

AtlasEntityDef atlasEntityDef = new AtlasEntityDef();
atlasEntityDef.setName("tablet");
atlasEntityDef.setCreatedBy("Krishna");
atlasEntityDef.setUpdatedBy("krishna");
atlasEntityDef.setDescription("Represent a laptoo specification");

 

Set super types to the entity that we want to create.

Set<String> superTypes = new HashSet<>();
superTypes.add("DataSet");
atlasEntityDef.setSuperTypes(superTypes);

 

Define and attach attribute definitions.

AtlasAttributeDef attributeDef1 = new AtlasAttributeDef();
attributeDef1.setName("screen_size");
attributeDef1.setTypeName("string");
attributeDef1.setCardinality(AtlasAttributeDef.Cardinality.SINGLE);
attributeDef1.setIsIndexable(true);
attributeDef1.setIsUnique(false);

AtlasAttributeDef attributeDef2 = new AtlasAttributeDef();
attributeDef2.setName("operating_system");
attributeDef2.setTypeName("string");
attributeDef2.setCardinality(AtlasAttributeDef.Cardinality.SINGLE);
attributeDef2.setIsIndexable(true);
attributeDef2.setIsUnique(false);

atlasEntityDef.setAttributeDefs(Arrays.asList(attributeDef1, attributeDef2));

Step 3: Define an instance of AtlasTypesDef and attach the entity definition to it.

AtlasTypesDef atlasTypesDef = new AtlasTypesDef();
atlasTypesDef.getEntityDefs().add(atlasEntityDef);

Step 4: Define new type using ‘createAtlasTypeDefs’ method.

AtlasTypesDef atlasTypesDefResponse = atlasClient.createAtlasTypeDefs(atlasTypesDef);

Find the below working application.

 

Step 1: Create atlas-application.properties file in src/main/resources folder.

 

atlas-application.properties

atlas.client.readTimeoutMSecs=30000
atlas.client.connectTimeoutMSecs=30000

Step 2: Define JsonUtil and CreateNewType classses.

 

JsonUtil.java

package com.sample.app.util;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

public class JsonUtil {
  public static String marshal(Object obj) throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    return mapper.writeValueAsString(obj);
  }

  public static <T> T unmarshal(Class<T> clazz, String json)
      throws JsonParseException, JsonMappingException, IOException {
    ObjectMapper mapper = new ObjectMapper();
    return (T) mapper.readValue(json, clazz);
  }

  public static String prettyPrintJson(Object obj) throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    return mapper.writeValueAsString(obj);
  }
}

CreateNewType.java

package com.sample.app.types;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import org.apache.atlas.AtlasClientV2;
import org.apache.atlas.AtlasServiceException;
import org.apache.atlas.model.typedef.AtlasEntityDef;
import org.apache.atlas.model.typedef.AtlasStructDef.AtlasAttributeDef;
import org.apache.atlas.model.typedef.AtlasTypesDef;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.sample.app.util.JsonUtil;

public class CreateNewType {
	public static void main(String[] args) throws AtlasServiceException, JsonProcessingException {
		AtlasClientV2 atlasClient = new AtlasClientV2(new String[] { "http://localhost:21000" },
				new String[] { "admin", "admin" });

		AtlasAttributeDef attributeDef1 = new AtlasAttributeDef();
		attributeDef1.setName("screen_size");
		attributeDef1.setTypeName("string");
		attributeDef1.setCardinality(AtlasAttributeDef.Cardinality.SINGLE);
		attributeDef1.setIsIndexable(true);
		attributeDef1.setIsUnique(false);

		AtlasAttributeDef attributeDef2 = new AtlasAttributeDef();
		attributeDef2.setName("operating_system");
		attributeDef2.setTypeName("string");
		attributeDef2.setCardinality(AtlasAttributeDef.Cardinality.SINGLE);
		attributeDef2.setIsIndexable(true);
		attributeDef2.setIsUnique(false);

		AtlasEntityDef atlasEntityDef = new AtlasEntityDef();
		atlasEntityDef.setName("tablet");
		atlasEntityDef.setCreatedBy("Krishna");
		atlasEntityDef.setUpdatedBy("krishna");
		atlasEntityDef.setDescription("Represent a laptoo specification");
		atlasEntityDef.setAttributeDefs(Arrays.asList(attributeDef1, attributeDef2));

		Set<String> superTypes = new HashSet<>();
		superTypes.add("DataSet");
		atlasEntityDef.setSuperTypes(superTypes);

		AtlasTypesDef atlasTypesDef = new AtlasTypesDef();

		atlasTypesDef.getEntityDefs().add(atlasEntityDef);

		AtlasTypesDef atlasTypesDefResponse = atlasClient.createAtlasTypeDefs(atlasTypesDef);

		String json = JsonUtil.prettyPrintJson(atlasTypesDefResponse);
		System.out.println(json);

	}
}

Output

{
  "enumDefs" : [ ],
  "structDefs" : [ ],
  "classificationDefs" : [ ],
  "entityDefs" : [ {
    "category" : "ENTITY",
    "guid" : "e7201b2c-a87d-49ef-aac0-c228b92f9763",
    "createdBy" : "admin",
    "updatedBy" : "admin",
    "createTime" : 1644561370044,
    "updateTime" : 1644561370044,
    "version" : 1,
    "name" : "tablet",
    "description" : "Represent a laptoo specification",
    "typeVersion" : "1.0",
    "attributeDefs" : [ {
      "name" : "screen_size",
      "typeName" : "string",
      "isOptional" : false,
      "cardinality" : "SINGLE",
      "valuesMinCount" : 1,
      "valuesMaxCount" : 1,
      "isUnique" : false,
      "isIndexable" : true,
      "includeInNotification" : false,
      "searchWeight" : -1
    }, {
      "name" : "operating_system",
      "typeName" : "string",
      "isOptional" : false,
      "cardinality" : "SINGLE",
      "valuesMinCount" : 1,
      "valuesMaxCount" : 1,
      "isUnique" : false,
      "isIndexable" : true,
      "includeInNotification" : false,
      "searchWeight" : -1
    } ],
    "superTypes" : [ "DataSet" ],
    "subTypes" : [ ],
    "relationshipAttributeDefs" : [ {
      "name" : "inputToProcesses",
      "typeName" : "array<Process>",
      "isOptional" : true,
      "cardinality" : "SET",
      "valuesMinCount" : -1,
      "valuesMaxCount" : -1,
      "isUnique" : false,
      "isIndexable" : false,
      "includeInNotification" : false,
      "searchWeight" : -1,
      "relationshipTypeName" : "dataset_process_inputs",
      "isLegacyAttribute" : false
    }, {
      "name" : "pipeline",
      "typeName" : "spark_ml_pipeline",
      "isOptional" : true,
      "cardinality" : "SINGLE",
      "valuesMinCount" : -1,
      "valuesMaxCount" : -1,
      "isUnique" : false,
      "isIndexable" : false,
      "includeInNotification" : false,
      "searchWeight" : -1,
      "relationshipTypeName" : "spark_ml_pipeline_dataset",
      "isLegacyAttribute" : false
    }, {
      "name" : "schema",
      "typeName" : "array<avro_schema>",
      "isOptional" : true,
      "cardinality" : "SET",
      "valuesMinCount" : -1,
      "valuesMaxCount" : -1,
      "isUnique" : false,
      "isIndexable" : false,
      "includeInNotification" : false,
      "searchWeight" : -1,
      "relationshipTypeName" : "avro_schema_associatedEntities",
      "isLegacyAttribute" : false
    }, {
      "name" : "model",
      "typeName" : "spark_ml_model",
      "isOptional" : true,
      "cardinality" : "SINGLE",
      "valuesMinCount" : -1,
      "valuesMaxCount" : -1,
      "isUnique" : false,
      "isIndexable" : false,
      "includeInNotification" : false,
      "searchWeight" : -1,
      "relationshipTypeName" : "spark_ml_model_dataset",
      "isLegacyAttribute" : false
    }, {
      "name" : "meanings",
      "typeName" : "array<AtlasGlossaryTerm>",
      "isOptional" : true,
      "cardinality" : "SET",
      "valuesMinCount" : -1,
      "valuesMaxCount" : -1,
      "isUnique" : false,
      "isIndexable" : false,
      "includeInNotification" : false,
      "searchWeight" : -1,
      "relationshipTypeName" : "AtlasGlossarySemanticAssignment",
      "isLegacyAttribute" : false
    }, {
      "name" : "outputFromProcesses",
      "typeName" : "array<Process>",
      "isOptional" : true,
      "cardinality" : "SET",
      "valuesMinCount" : -1,
      "valuesMaxCount" : -1,
      "isUnique" : false,
      "isIndexable" : false,
      "includeInNotification" : false,
      "searchWeight" : -1,
      "relationshipTypeName" : "process_dataset_outputs",
      "isLegacyAttribute" : false
    } ],
    "businessAttributeDefs" : { }
  } ],
  "relationshipDefs" : [ ],
  "businessMetadataDefs" : [ ]
}

You can confirm the same by login to Atlas UI.




Previous                                                    Next                                                    Home

HIVE: Create table

In this post, I am going to explain how to create and manage table using hive interactive shell.

 

Step 1: Open terminal and execute the command hive.

 

Step 2: Execute following command to create employee table.

create table employee(id int, name string);

hive> create table employee(id int, name string);
OK
Time taken: 1.356 seconds

Execute the command ‘show tables’ to list out all the tables.

hive> show tables;
OK
employee
Time taken: 0.111 seconds, Fetched: 1 row(s)

You can get more information about the employee table by executing the command ‘describe employee’.

hive> describe employee;
OK
id                    int                                       
name                  string                                    
Time taken: 0.113 seconds, Fetched: 2 row(s)

 show create table {table_name}

Above statement return the create statement that we used to create given table and the location where this table is located in hdfs.

hive> show create table employee;
OK
CREATE TABLE `employee`(
  `id` int, 
  `name` string)
ROW FORMAT SERDE 
  'org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe' 
STORED AS INPUTFORMAT 
  'org.apache.hadoop.mapred.TextInputFormat' 
OUTPUTFORMAT 
  'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat'
LOCATION
  'hdfs://localhost:9000/user/hive/warehouse/employee'
TBLPROPERTIES (
  'bucketing_version'='2', 
  'transient_lastDdlTime'='1610682814')
Time taken: 0.103 seconds, Fetched: 14 row(s)

As you see above snippet, employee table is located at hdfs location /user/hive/warehouse/employee. You can confirm the same by querying hdfs file system.

$hdfs dfs -ls /user/hive/warehouse/
Found 1 items
drwxr-xr-x   - krishna supergroup          0 2021-01-15 09:23 /user/hive/warehouse/employee

 

From the above output, you can confirm that when you create a table ‘employee’ using hive create command, a directory structure /user/hive/warehouse/employee is created in hdfs.

 

Get extended information about the table

Syntax

describe extended table_name

 

Example

hive> describe extended employee;
OK
id                    int                                       
name                  string                                    
     
Detailed Table Information  Table(tableName:employee, dbName:default, owner:krishna, createTime:1610682814, lastAccessTime:0, retention:0, sd:StorageDescriptor(cols:[FieldSchema(name:id, type:int, comment:null), FieldSchema(name:name, type:string, comment:null)], location:hdfs://localhost:9000/user/hive/warehouse/employee, inputFormat:org.apache.hadoop.mapred.TextInputFormat, outputFormat:org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat, compressed:false, numBuckets:-1, serdeInfo:SerDeInfo(name:null, serializationLib:org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe, parameters:{serialization.format=1}), bucketCols:[], sortCols:[], parameters:{}, skewedInfo:SkewedInfo(skewedColNames:[], skewedColValues:[], skewedColValueLocationMaps:{}), storedAsSubDirectories:false), partitionKeys:[], parameters:{totalSize=0, numRows=0, rawDataSize=0, COLUMN_STATS_ACCURATE={\"BASIC_STATS\":\"true\",\"COLUMN_STATS\":{\"id\":\"true\",\"name\":\"true\"}}, numFiles=0, transient_lastDdlTime=1610682814, bucketing_version=2}, viewOriginalText:null, viewExpandedText:null, tableType:MANAGED_TABLE, rewriteEnabled:false, catName:hive, ownerType:USER)  
Time taken: 0.095 seconds, Fetched: 4 row(s)



Previous                                                    Next                                                    Home

Spring boot: ehcache: Receive cache events by implementing CacheEventListener

In this post, I am going to explain how to get the cache events by implementing CacheEventListener.

 

Supported event types

org.ehcache.event.EventType enum define below event types.

 

a.   EVICTED : Represents a cache entry being evicted

b.   EXPIRED : Represents a cache entry being expired

c.    REMOVED : Represents a cache entry being removed

d.   CREATED : Represents a cache entry being created

e.   UPDATED : Represents a cache entry being updated

 

Supported event firing modes

org.ehcache.event.EventFiring enum defines below event firing modes.

 

a.   ASYNCHRONOUS: Events will fire asynchronously. The mutating thread does not have to wait for firing to complete.

b.   SYNCHRONOUS: Events will fire synchronously. The mutating thread will wait for firing to complete.

 

Supported event ordering modes

org.ehcache.event.EventOrdering define below event ordering modes.

a.   UNORDERED: Events may be observed out of order.

b.   ORDERED: Ordering of events is guaranteed on a per-key basis.

 

Let’s define custom cache event listener by implementing CacheEventListener interface.

public class MyCacheEnventListener implements CacheEventListener<Object, Object> {
	private static final Logger LOGGER = LoggerFactory.getLogger(MyCacheEnventListener.class);

	public void onEvent(CacheEvent<? extends Object, ? extends Object> cacheEvent) {
		LOGGER.info("\n-----------------------------------------------");
		LOGGER.info("Event received");
		LOGGER.info("event type: {}", cacheEvent.getType());
		LOGGER.info("event key: {}", cacheEvent.getKey());
		LOGGER.info("old value: {}", cacheEvent.getOldValue());
		LOGGER.info("new value: {}", cacheEvent.getNewValue());
		LOGGER.info("-----------------------------------------------");

	}
}

 

Next configure this ‘MyCacheEnventListener’ in ehcache.xml file.

 

ehcache.xml

 

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://www.ehcache.org/v3"
	xmlns:jsr107="http://www.ehcache.org/v3/jsr107"
	xsi:schemaLocation="
            http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core-3.0.xsd
            http://www.ehcache.org/v3/jsr107 http://www.ehcache.org/schema/ehcache-107-ext-3.0.xsd">

	<cache alias="myEmployeeCache">
		<key-type>java.lang.Object</key-type>
		<value-type>java.lang.Object</value-type>
		<expiry>
			<ttl unit="seconds">10</ttl>
		</expiry>

		<listeners>
			<listener>
				<class>com.sample.app.listeners.MyCacheEnventListener</class>
				<event-firing-mode>SYNCHRONOUS</event-firing-mode>
				<event-ordering-mode>UNORDERED</event-ordering-mode>
				<events-to-fire-on>CREATED</events-to-fire-on>
				<events-to-fire-on>EXPIRED</events-to-fire-on>
			</listener>
		</listeners>

		<resources>
			<heap unit="entries">2</heap>
			<offheap unit="MB">10</offheap>
		</resources>


	</cache>


</config>

 

As you observe the definition of xml file, I set event-firing-mode to SYNCHRONOUS for the demo purpose, you can set this to 'ASYNCHRONOUS' in production.

 

Specify ehcache.xml file location in application.yml file.

spring:
  cache:
    jcache:
      config: classpath:ehcache.xml 

 

Follow below step-by-step procedure to build complete working application.

 

Step 1: Create new maven project ‘spring-cache-event-listener’.

 

Step 2: Update pom.xml with maven dependencies.

 

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.sample.app</groupId>
	<artifactId>spring-cache-event-listener</artifactId>
	<version>1</version>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.6.6</version>
	</parent>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-cache</artifactId>
		</dependency>

		<dependency>
			<groupId>org.ehcache</groupId>
			<artifactId>ehcache</artifactId>
		</dependency>

		<dependency>
			<groupId>javax.cache</groupId>
			<artifactId>cache-api</artifactId>
		</dependency>

	</dependencies>
</project>

Step 3: Create ehcache.xml file under src/main/resources folder.

 

ehcache.xml

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://www.ehcache.org/v3"
	xmlns:jsr107="http://www.ehcache.org/v3/jsr107"
	xsi:schemaLocation="
            http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core-3.0.xsd
            http://www.ehcache.org/v3/jsr107 http://www.ehcache.org/schema/ehcache-107-ext-3.0.xsd">

	<cache alias="myEmployeeCache">
		<key-type>java.lang.Object</key-type>
		<value-type>java.lang.Object</value-type>
		<expiry>
			<ttl unit="seconds">10</ttl>
		</expiry>

		<listeners>
			<listener>
				<class>com.sample.app.listeners.MyCacheEnventListener</class>
				<event-firing-mode>SYNCHRONOUS</event-firing-mode>
				<event-ordering-mode>ORDERED</event-ordering-mode>
				<events-to-fire-on>EVICTED</events-to-fire-on>
				<events-to-fire-on>EXPIRED</events-to-fire-on>
				<events-to-fire-on>REMOVED</events-to-fire-on>
				<events-to-fire-on>CREATED</events-to-fire-on>
				<events-to-fire-on>UPDATED</events-to-fire-on>

			</listener>
		</listeners>

		<resources>
			<heap unit="entries">2</heap>
			<offheap unit="MB">10</offheap>
		</resources>


	</cache>


</config>

Step 4: Create application.yml file under src/main/resources folder.

 

application.yml

spring:
  cache:
    jcache:
      config: classpath:ehcache.xml

Step 5: Create Employee model class.

 

Employee.java

package com.sample.app.model;

import java.io.Serializable;

public class Employee implements Serializable{
	private int id;
	private String firstName;
	private String lastName;

	public Employee(int id, String firstName, String lastName) {
		this.id = id;
		this.firstName = firstName;
		this.lastName = lastName;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	@Override
	public String toString() {
		return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + "]";
	}

}

Step 6: Define EmployeeService class.

 

EmployeeService.java

package com.sample.app.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.sample.app.model.Employee;

@Service
@CacheConfig(cacheNames = "myEmployeeCache")
public class EmployeeService {

	private static List<Employee> emps = new ArrayList<>();

	static {
		emps.add(new Employee(1, "Ram", "Kota"));
		emps.add(new Employee(2, "Raj", "Majety"));
		emps.add(new Employee(3, "PTR", "Navakotla"));
		emps.add(new Employee(4, "Krishna", "Boppana"));
	}

	@Cacheable(key = "{#id}")
	public Employee getEmployeeById(int id) {
		System.out.println("getEmployeeById: Getting the informaiton from internal list");
		
		for (Employee emp : emps) {
			if (id == emp.getId()) {
				return emp;
			}
		}
		return null;
	}

	@Cacheable(key = "{#name}")
	public Employee getEmployeeByFirstName(String name) {
		System.out.println("getEmployeeByFirstName: Getting the informaiton from internal list");
		
		for (Employee emp : emps) {
			if (name.equals(emp.getFirstName())) {
				return emp;
			}
		}
		return null;
	}
}

Step 7: Define MyCacheEnventListener class.

MyCacheEnventListener.java

package com.sample.app.listeners;

import org.ehcache.event.CacheEvent;
import org.ehcache.event.CacheEventListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MyCacheEnventListener implements CacheEventListener<Object, Object> {
	private static final Logger LOGGER = LoggerFactory.getLogger(MyCacheEnventListener.class);

	public void onEvent(CacheEvent<? extends Object, ? extends Object> cacheEvent) {
		LOGGER.info("\n-----------------------------------------------");
		LOGGER.info("Event received");
		LOGGER.info("event type: {}", cacheEvent.getType());
		LOGGER.info("event key: {}", cacheEvent.getKey());
		LOGGER.info("old value: {}", cacheEvent.getOldValue());
		LOGGER.info("new value: {}", cacheEvent.getNewValue());
		LOGGER.info("-----------------------------------------------");

	}
}

 

Step 8: Define CacheConfig class.

 

CacheConfig.java

package com.sample.app.config;

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableCaching
public class CacheConfig {

} 

 

Step 9: Define main application class.

 

App.java

package com.sample.app;

import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import com.sample.app.model.Employee;
import com.sample.app.service.EmployeeService;

@SpringBootApplication
public class App {

	private static final Logger LOGGER = LoggerFactory.getLogger(App.class);

	@Autowired
	private EmployeeService empService;

	public static void main(String[] args) {
		SpringApplication.run(App.class, args);
	}

	public void getEmployeeDetails() {

		System.out.println("\n");
		LOGGER.info("\nGetting employee details with id 1");
		Employee emp = empService.getEmployeeById(1);
		LOGGER.info("emp : {}", emp);

		System.out.println("\n");
		LOGGER.info("Getting employee details with name 'Krishna'");
		emp = empService.getEmployeeByFirstName("Krishna");
		LOGGER.info("emp : {}", emp);
	}

	@Bean
	public CommandLineRunner demo() {
		return (args) -> {

			getEmployeeDetails();

			LOGGER.info("Sleeping for 4 seconds");
			TimeUnit.SECONDS.sleep(4);
			getEmployeeDetails();

			LOGGER.info("Sleeping for 4 seconds");
			TimeUnit.SECONDS.sleep(4);
			getEmployeeDetails();

			LOGGER.info("Sleeping for 4 seconds");
			TimeUnit.SECONDS.sleep(4);
			getEmployeeDetails();

		};
	}
}

 

Total project structure looks like below.

 


 

Run App.java, you will see below messages in console.

Getting employee details with id 1
getEmployeeById: Getting the informaiton from internal list
2022-06-30 16:15:17.063  INFO 82133 --- [e [_default_]-0] c.s.app.listeners.MyCacheEnventListener  : 
-----------------------------------------------
2022-06-30 16:15:17.064  INFO 82133 --- [e [_default_]-0] c.s.app.listeners.MyCacheEnventListener  : Event received
2022-06-30 16:15:17.064  INFO 82133 --- [e [_default_]-0] c.s.app.listeners.MyCacheEnventListener  : event type: CREATED
2022-06-30 16:15:17.064  INFO 82133 --- [e [_default_]-0] c.s.app.listeners.MyCacheEnventListener  : event key: [1]
2022-06-30 16:15:17.064  INFO 82133 --- [e [_default_]-0] c.s.app.listeners.MyCacheEnventListener  : old value: null
2022-06-30 16:15:17.064  INFO 82133 --- [e [_default_]-0] c.s.app.listeners.MyCacheEnventListener  : new value: Employee [id=1, firstName=Ram, lastName=Kota]
2022-06-30 16:15:17.064  INFO 82133 --- [e [_default_]-0] c.s.app.listeners.MyCacheEnventListener  : -----------------------------------------------
2022-06-30 16:15:17.065  INFO 82133 --- [           main] com.sample.app.App                       : emp : Employee [id=1, firstName=Ram, lastName=Kota]


2022-06-30 16:15:17.065  INFO 82133 --- [           main] com.sample.app.App                       : Getting employee details with name 'Krishna'
getEmployeeByFirstName: Getting the informaiton from internal list
2022-06-30 16:15:17.066  INFO 82133 --- [e [_default_]-0] c.s.app.listeners.MyCacheEnventListener  : 
-----------------------------------------------
2022-06-30 16:15:17.066  INFO 82133 --- [e [_default_]-0] c.s.app.listeners.MyCacheEnventListener  : Event received
2022-06-30 16:15:17.066  INFO 82133 --- [e [_default_]-0] c.s.app.listeners.MyCacheEnventListener  : event type: CREATED
2022-06-30 16:15:17.066  INFO 82133 --- [e [_default_]-0] c.s.app.listeners.MyCacheEnventListener  : event key: [Krishna]
2022-06-30 16:15:17.066  INFO 82133 --- [e [_default_]-0] c.s.app.listeners.MyCacheEnventListener  : old value: null
2022-06-30 16:15:17.066  INFO 82133 --- [e [_default_]-0] c.s.app.listeners.MyCacheEnventListener  : new value: Employee [id=4, firstName=Krishna, lastName=Boppana]
2022-06-30 16:15:17.066  INFO 82133 --- [e [_default_]-0] c.s.app.listeners.MyCacheEnventListener  : -----------------------------------------------
2022-06-30 16:15:17.066  INFO 82133 --- [           main] com.sample.app.App                       : emp : Employee [id=4, firstName=Krishna, lastName=Boppana]
2022-06-30 16:15:17.067  INFO 82133 --- [           main] com.sample.app.App                       : Sleeping for 4 seconds


2022-06-30 16:15:21.069  INFO 82133 --- [           main] com.sample.app.App                       : 
Getting employee details with id 1
2022-06-30 16:15:21.077  INFO 82133 --- [           main] com.sample.app.App                       : emp : Employee [id=1, firstName=Ram, lastName=Kota]


2022-06-30 16:15:21.078  INFO 82133 --- [           main] com.sample.app.App                       : Getting employee details with name 'Krishna'
2022-06-30 16:15:21.078  INFO 82133 --- [           main] com.sample.app.App                       : emp : Employee [id=4, firstName=Krishna, lastName=Boppana]
2022-06-30 16:15:21.078  INFO 82133 --- [           main] com.sample.app.App                       : Sleeping for 4 seconds


2022-06-30 16:15:25.079  INFO 82133 --- [           main] com.sample.app.App                       : 
Getting employee details with id 1
2022-06-30 16:15:25.080  INFO 82133 --- [           main] com.sample.app.App                       : emp : Employee [id=1, firstName=Ram, lastName=Kota]


2022-06-30 16:15:25.080  INFO 82133 --- [           main] com.sample.app.App                       : Getting employee details with name 'Krishna'
2022-06-30 16:15:25.080  INFO 82133 --- [           main] com.sample.app.App                       : emp : Employee [id=4, firstName=Krishna, lastName=Boppana]
2022-06-30 16:15:25.080  INFO 82133 --- [           main] com.sample.app.App                       : Sleeping for 4 seconds


2022-06-30 16:15:29.082  INFO 82133 --- [           main] com.sample.app.App                       : 
Getting employee details with id 1
2022-06-30 16:15:29.085  INFO 82133 --- [e [_default_]-0] c.s.app.listeners.MyCacheEnventListener  : 
-----------------------------------------------
2022-06-30 16:15:29.085  INFO 82133 --- [e [_default_]-0] c.s.app.listeners.MyCacheEnventListener  : Event received
2022-06-30 16:15:29.085  INFO 82133 --- [e [_default_]-0] c.s.app.listeners.MyCacheEnventListener  : event type: EXPIRED
2022-06-30 16:15:29.085  INFO 82133 --- [e [_default_]-0] c.s.app.listeners.MyCacheEnventListener  : event key: [1]
2022-06-30 16:15:29.085  INFO 82133 --- [e [_default_]-0] c.s.app.listeners.MyCacheEnventListener  : old value: Employee [id=1, firstName=Ram, lastName=Kota]
2022-06-30 16:15:29.085  INFO 82133 --- [e [_default_]-0] c.s.app.listeners.MyCacheEnventListener  : new value: null
2022-06-30 16:15:29.085  INFO 82133 --- [e [_default_]-0] c.s.app.listeners.MyCacheEnventListener  : -----------------------------------------------
getEmployeeById: Getting the informaiton from internal list
2022-06-30 16:15:29.087  INFO 82133 --- [e [_default_]-0] c.s.app.listeners.MyCacheEnventListener  : 
-----------------------------------------------
2022-06-30 16:15:29.087  INFO 82133 --- [e [_default_]-0] c.s.app.listeners.MyCacheEnventListener  : Event received
2022-06-30 16:15:29.087  INFO 82133 --- [e [_default_]-0] c.s.app.listeners.MyCacheEnventListener  : event type: CREATED
2022-06-30 16:15:29.087  INFO 82133 --- [e [_default_]-0] c.s.app.listeners.MyCacheEnventListener  : event key: [1]
2022-06-30 16:15:29.087  INFO 82133 --- [e [_default_]-0] c.s.app.listeners.MyCacheEnventListener  : old value: null
2022-06-30 16:15:29.087  INFO 82133 --- [e [_default_]-0] c.s.app.listeners.MyCacheEnventListener  : new value: Employee [id=1, firstName=Ram, lastName=Kota]
2022-06-30 16:15:29.087  INFO 82133 --- [e [_default_]-0] c.s.app.listeners.MyCacheEnventListener  : -----------------------------------------------
2022-06-30 16:15:29.087  INFO 82133 --- [           main] com.sample.app.App                       : emp : Employee [id=1, firstName=Ram, lastName=Kota]


2022-06-30 16:15:29.087  INFO 82133 --- [           main] com.sample.app.App                       : Getting employee details with name 'Krishna'
2022-06-30 16:15:29.088  INFO 82133 --- [e [_default_]-0] c.s.app.listeners.MyCacheEnventListener  : 
-----------------------------------------------
2022-06-30 16:15:29.088  INFO 82133 --- [e [_default_]-0] c.s.app.listeners.MyCacheEnventListener  : Event received
2022-06-30 16:15:29.088  INFO 82133 --- [e [_default_]-0] c.s.app.listeners.MyCacheEnventListener  : event type: EXPIRED
2022-06-30 16:15:29.088  INFO 82133 --- [e [_default_]-0] c.s.app.listeners.MyCacheEnventListener  : event key: [Krishna]
2022-06-30 16:15:29.088  INFO 82133 --- [e [_default_]-0] c.s.app.listeners.MyCacheEnventListener  : old value: Employee [id=4, firstName=Krishna, lastName=Boppana]
2022-06-30 16:15:29.088  INFO 82133 --- [e [_default_]-0] c.s.app.listeners.MyCacheEnventListener  : new value: null
2022-06-30 16:15:29.088  INFO 82133 --- [e [_default_]-0] c.s.app.listeners.MyCacheEnventListener  : -----------------------------------------------
getEmployeeByFirstName: Getting the informaiton from internal list
2022-06-30 16:15:29.089  INFO 82133 --- [e [_default_]-0] c.s.app.listeners.MyCacheEnventListener  : 
-----------------------------------------------
2022-06-30 16:15:29.089  INFO 82133 --- [e [_default_]-0] c.s.app.listeners.MyCacheEnventListener  : Event received
2022-06-30 16:15:29.089  INFO 82133 --- [e [_default_]-0] c.s.app.listeners.MyCacheEnventListener  : event type: CREATED
2022-06-30 16:15:29.089  INFO 82133 --- [e [_default_]-0] c.s.app.listeners.MyCacheEnventListener  : event key: [Krishna]
2022-06-30 16:15:29.089  INFO 82133 --- [e [_default_]-0] c.s.app.listeners.MyCacheEnventListener  : old value: null
2022-06-30 16:15:29.089  INFO 82133 --- [e [_default_]-0] c.s.app.listeners.MyCacheEnventListener  : new value: Employee [id=4, firstName=Krishna, lastName=Boppana]
2022-06-30 16:15:29.089  INFO 82133 --- [e [_default_]-0] c.s.app.listeners.MyCacheEnventListener  : -----------------------------------------------
2022-06-30 16:15:29.089  INFO 82133 --- [           main] com.sample.app.App                       : emp : Employee [id=4, firstName=Krishna, lastName=Boppana]
2022-06-30 16:15:59.100  INFO 82133 --- [ionShutdownHook] org.ehcache.core.EhcacheManager          : Cache 'myEmployeeCache' removed from EhcacheManager.

 

You can download complete working application from this link.


 

 

Previous                                                 Next                                                 Home