ConcurrentMap Cache in Spring
November 17, 2021
Spring provides Java based cache management using ConcurrentMap
for simple functionalities. Spring provides ConcurrentMapCacheFactoryBean
under the package org.springframework.cache.concurrent
. The SimpleCacheManager
is used to provide the cache manager. The ConcurrentMap
based cache is simple to use and very high in performance but we can not use it for cache eviction. Overall we don't have very much control over ConcurrentMap
based cache. So normally ConcurrentMap
based cache is used for basic functionalities, testing purpose.
Using ConcurrentMapCacheFactoryBean
Find the complete example to useConcurrentMapCacheFactoryBean
class.
spring.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:cache="http://www.springframework.org/schema/cache" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd"> <cache:annotation-driven /> <bean id="employee" class="com.concretepage.Employee"></bean> <bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager"> <property name="caches"> <set> <bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean" p:name="emp"/> </set> </property> </bean> </beans>
package com.concretepage; import org.springframework.cache.annotation.Cacheable; public class Employee { @Cacheable("emp") public String getEmployee(int empId){ System.out.println("execute getEmployee method.."); if(empId==1){ return "Atul"; }else{ return "Sudhir"; } } }
package com.concretepage; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class SpringDemo { public static void main(String... args) { AbstractApplicationContext context = new ClassPathXmlApplicationContext("spring.xml"); Employee employee=(Employee) context.getBean("employee"); //calling getEmployee method first time. System.out.println(employee.getEmployee(1)); //calling getEmployee method second time. This time, method will not execute. System.out.println(employee.getEmployee(1)); } }
execute getEmployee method.. Atul Atul