Wednesday, 29 June 2022

spring boot: ehcache hello world example

Ehcache is a high-performance caching library for Java. In this post, I am going to explain how to integrate Ehcache with spring boot application.

 

Step 1: Enable caching in your spring boot application.

 

Step 2: Create ehcache.xml configuration and define the caches there.

<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>

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


</config>

 

Above snippet defines a cache ‘myEmployeeCache’ where key and object are of type Object. An entry can live 10 seconds in the cache.

 

Step 3: Specify cache configuration to spring by adding below property.

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

Find the below working application.

 

Step 1: Create new maven project ‘spring-ehcache-demo’.

 

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-ehcache-demo</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 application.yml file under src/main/resources folder.

 

application.yml

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

 

Step 4: 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>

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


</config>

Step 5: Define 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 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 8: Define main application class.

 

App.java

package com.sample.app;

import java.util.concurrent.TimeUnit;

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 {

	@Autowired
	private EmployeeService empService;

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

	public void getEmployeeDetails() {

		Employee emp = empService.getEmployeeById(1);
		System.out.println(emp);

		emp = empService.getEmployeeByFirstName("Krishna");
		System.out.println(emp);
	}

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

			getEmployeeDetails();

			System.out.println("\nSleeping for 4 seconds");
			TimeUnit.SECONDS.sleep(4);
			getEmployeeDetails();

			System.out.println("\n\nSleeping for 4 seconds");
			TimeUnit.SECONDS.sleep(4);
			getEmployeeDetails();

			System.out.println("\n\nSleeping for 4 seconds");
			TimeUnit.SECONDS.sleep(4);
			getEmployeeDetails();

		};
	}
}

Total project structure looks like below.



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

getEmployeeById: Getting the informaiton from internal list
Employee [id=1, firstName=Ram, lastName=Kota]
getEmployeeByFirstName: Getting the informaiton from internal list
Employee [id=4, firstName=Krishna, lastName=Boppana]

Sleeping for 4 seconds
Employee [id=1, firstName=Ram, lastName=Kota]
Employee [id=4, firstName=Krishna, lastName=Boppana]


Sleeping for 4 seconds
Employee [id=1, firstName=Ram, lastName=Kota]
Employee [id=4, firstName=Krishna, lastName=Boppana]


Sleeping for 4 seconds
getEmployeeById: Getting the informaiton from internal list
Employee [id=1, firstName=Ram, lastName=Kota]
getEmployeeByFirstName: Getting the informaiton from internal list
Employee [id=4, firstName=Krishna, lastName=Boppana]
2022-06-29 21:33:13.603  INFO 4091 --- [ionShutdownHook] org.ehcache.core.EhcacheManager          : Cache 'myEmployeeCache' removed from EhcacheManager.

From the output, you can confirm that employee details are served from internal collection for the first time and, till next 10 seconds data is served from the ehcache.

 

You can download complete working application from this link.


Previous                                                 Next                                                 Home

Tuesday, 28 June 2022

Ehcache: Store the cache data to disk

Ehcache support tiering model to allow storing increasing amounts of data on slower tiers.

 


Example

PersistentCacheManager persistentCacheManager = CacheManagerBuilder.newCacheManagerBuilder()
.with(CacheManagerBuilder.persistence(new File("/Users/Shared/ehcache")))
.withCache("myCache",
		CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
				ResourcePoolsBuilder.newResourcePoolsBuilder().heap(100, EntryUnit.ENTRIES)
						.offheap(2, MemoryUnit.MB).disk(20, MemoryUnit.MB, true)))
.build(true);

 

Above snippet defines a cache

a.   With heap to store 100 entries

b.   Off heap of size 2MB

c.    Disk of size 20MB

 

Objects stored in the Heap are managed by Jvm and unused objects are cleared by garbage collection cycle. On the other hand, the off-heap store refers to objects that are managed by EHCache, but stored outside the heap. Since off-heap memory is also maintained in the in-memory, it is faster than disk but slower than the heap store.

 

Find the below working application.

 

StoreDataToDisk.java

package com.sample.app;

import java.io.File;

import org.ehcache.Cache;
import org.ehcache.PersistentCacheManager;
import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.CacheManagerBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;
import org.ehcache.config.units.EntryUnit;
import org.ehcache.config.units.MemoryUnit;

public class StoreDataToDisk {

	public static void main(String[] args) {
		PersistentCacheManager persistentCacheManager = CacheManagerBuilder.newCacheManagerBuilder()
				.with(CacheManagerBuilder.persistence(new File("/Users/Shared/ehcache")))
				.withCache("myCache",
						CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
								ResourcePoolsBuilder.newResourcePoolsBuilder().heap(100, EntryUnit.ENTRIES)
										.offheap(2, MemoryUnit.MB).disk(20, MemoryUnit.MB, true)))
				.build(true);

		Cache<Long, String> myCache = persistentCacheManager.getCache("myCache", Long.class, String.class);

		for (long i = 1; i < 100000; i++) {
			myCache.put(i, "data -> " + i);
		}

		persistentCacheManager.close();
	}

}

  Run the application, open the directory /Users/Shared/ehcache, you will see below data.

 

$tree /Users/Shared/ehcache
| | |____ehcache
| | | |____file
| | | | |____myCache_5d66446584040b6bac0bd0e2ee4e268602375623
| | | | | |____offheap-disk-store
| | | | | | |____ehcache-disk-store.meta
| | | | | | |____ehcache-disk-store.index
| | | | | | |____ehcache-disk-store.data

  

Previous                                                 Next                                                 Home

Hive: Get the database that user is in the Hive CLI

There are two options to print the database information that user is in.

 

Approach1 : Using the property hive.cli.print.current.db.

Execute below statement once you login to Hive Shell.

 

set hive.cli.print.current.db=true;

 

[cloudera@quickstart conf]$ hive

Logging initialized using configuration in file:/etc/hive/conf.dist/hive-log4j.properties
WARNING: Hive CLI is deprecated and migration to Beeline is recommended.
hive> ;
hive> set hive.cli.print.current.db=true;
hive (default)>

hive (default)>: default is the database name here.

Approach 2: Start hive by executing below command.

hive --hiveconf hive.cli.print.current.db=true

[cloudera@quickstart conf]$ hive --hiveconf hive.cli.print.current.db=true

Logging initialized using configuration in file:/etc/hive/conf.dist/hive-log4j.properties
WARNING: Hive CLI is deprecated and migration to Beeline is recommended.
hive (default)>



Previous                                                    Next                                                    Home

Atlas client: check whether type with given name exists or not

AtlasClientV2#typeWithNameExists() method return true if the type with given name exists, else false.

 

Example

boolean typeWithName1Exists = atlasClient.typeWithNameExists(typeName1);

 

Find the below working application.

 

Define atlas-application.properties file under src/main/resources folder.

 

atlas-application.properties

 

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

 

TypeExistsCheckByName.java

package com.sample.app.types;

import org.apache.atlas.AtlasClientV2;
import org.apache.atlas.AtlasServiceException;

import com.fasterxml.jackson.core.JsonProcessingException;

public class TypeExistsCheckByName {

	public static void main(String[] args) throws AtlasServiceException, JsonProcessingException {

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

		String typeName1 = "gcp_storage_bucket";
		String typeName2 = "testType";

		boolean typeWithName1Exists = atlasClient.typeWithNameExists(typeName1);
		boolean typeWithName2Exists = atlasClient.typeWithNameExists(typeName2);

		System.out.println("typeWithName1Exists : " + typeWithName1Exists);
		System.out.println("typeWithName2Exists : " + typeWithName2Exists);

	}
}

Output

typeWithName1Exists : true
typeWithName2Exists : false



Previous                                                    Next                                                    Home