Tuesday 27 April 2021

Caffeine: Asynchronous loading of data

Using AsyncLoadingCache, you can load the non-existed data to the cache asynchronously.

 

Example

AsyncLoadingCache<Integer, Employee> cache = Caffeine.newBuilder().expireAfterWrite(30, TimeUnit.SECONDS)

.maximumSize(100).buildAsync(key -> EmployeeService.getEmployee(key));

 

Extract the data from cache asynchronously

cache.get(1).thenAccept(data -> System.out.println(data));

 

Find the below working application.

 

Employee.java

package com.sample.app.model;

public class Employee {

	private int id;
	private String firstName;
	private String lastName;

	public Employee(int id, String firstName, String lastName) {
		super();
		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 + "]";
	}

}

 

EmployeeService.java

package com.sample.app.service;

import com.sample.app.model.Employee;

public class EmployeeService {

	public static Employee getEmployee(int id){
		System.out.println("Loading from database.....");
		return new Employee(id, "first_name_"+ id, "last_name_"+id);
	}
}

 

App.java

package com.sample.app;

import java.util.concurrent.TimeUnit;

import com.github.benmanes.caffeine.cache.AsyncLoadingCache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.sample.app.model.Employee;
import com.sample.app.service.EmployeeService;

public class App {

	public static void main(String args[]) {

		AsyncLoadingCache<Integer, Employee> cache = Caffeine.newBuilder().expireAfterWrite(30, TimeUnit.SECONDS)
				.maximumSize(100).buildAsync(key -> EmployeeService.getEmployee(key));

		cache.get(1).thenAccept(data -> System.out.println(data));
		
		System.out.println("\nGetting the data from cache again");
		cache.get(1).thenAccept(data -> System.out.println(data));

	}

}

Output

Loading from database.....
Employee [id=1, firstName=first_name_1, lastName=last_name_1]

Getting the data from cache again
Employee [id=1, firstName=first_name_1, lastName=last_name_1]



 

 

 

 

 

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment