EhCache is a pure Java in-process caching framework, with fast and lean features, and is the default CacheProvider in Hibernate.
ehcache provides a variety of caching strategies, mainly divided into memory and disk levels, so there is no need to worry about capacity issues.
spring-boot is a fast integration framework designed to simplify the initial construction and development process of new Spring applications. The framework uses a specific way to configure it, so that developers no longer need to define boilerplate configurations.
Since spring-boot does not require any boilerplate configuration files, spring-boot will be slightly different when integrating some other frameworks.
1.spring-boot is a framework for jar packages managed through maven. The dependencies required for integrating ehcache are as follows
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId></dependency><dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> <version>2.8.3</version></dependency>
The specific pom.xml file is as follows
<?xml version="1.0" encoding="UTF-8"?><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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.lclc.boot</groupId> <artifactId>boot-cache</artifactId> <version>0.0.1-SNAPSHOT</version> <!-- Inherit defaults from Spring Boot --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.1.3.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>17.0</version> </dependency> <dependency> <groupId>org.sspringframework</groupId> <artifactId>spring-context-support</artifactId> </dependency> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> <version>2.8.3</version> </dependency> </dependencies> <dependencyManagement> <dependencies> </dependencies> </dependencies> </dependencies> </dependencies> </dependencies> </dependencies> </dependencies> <build> <plugins> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> <repositories> <repository> <id>spring-snapshots</id> <url>http://repo.spring.io/snapshot</url> <snapshots> <enabled>true</enabled> </snapshots> </repository> <repository> <id>spring-milestones</id> <url>http://repo.spring.io/milestone</url> </repository> </repository> </repository> <pluginRepository> <pluginRepository> <id>spring-snapshots</id> <url>http://repo.spring.io/snapshot</url> </pluginRepository> <pluginRepository> <id>spring-milestones</id> <url>http://repo.spring.io/milestone</url> </pluginRepository> </pluginRepositories></project>
2. Using ehcache, we need an ehcache.xml to define some cache attributes.
<?xml version="1.0" encoding="UTF-8"?><ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd" updateCheck="false"> <diskStore path="java.io.tmpdir/Tmp_EhCache" /> <defaultCache eternal="false" maxElementsInMemory="1000" overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="0" timeToLiveSeconds="600" memoryStoreEvictionPolicy="LRU" /> <cache name="demo" eternal="false" maxElementsInMemory="100" overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="0" timeToLiveSeconds="300" memoryStoreEvictionPolicy="LRU" /></ehcache>
Explain the tags in this xml file.
(1).diskStore: is the cache path, ehcache is divided into two levels: memory and disk. This property defines the cache location of the disk. The parameters are explained as follows:
(2).defaultCache: The default cache policy. When ehcache cannot find the defined cache, this cache policy will be used. Only one can be defined.
(3).cache: Custom cache policy, a custom cache policy. The parameters are explained as follows:
SpringBoot supports many caching methods: redis, guava, ehcahe, jcache, etc.
Explain the difference between redis and ehcache:
Redis: It is an independent running program. After installation alone, it is manipulated using Jedis in Java. Because it is independent, if you write a unit test program, put some data in Redis, and then write another program to get the data, you can get the data. ,
ehcache: It is obviously different from Redis, it is bound to java programs. When the java program is alive, it is alive. For example, if you write an independent program to put data, and then write an independent program to get data, you will not get data. Data can only be obtained in independent programs.
3. Expose the ehcache manager to the spring context container.
@Configuration// The annotation starts the cache @EnableCachingpublic class CacheConfiguration { /* * ehcache Main manager*/ @Bean(name = "appEhCacheCacheManager") public EhCacheCacheManager ehCacheCacheManager(EhCacheManagerFactoryBean bean){ return new EhCacheCacheManager (bean.getObject ()); } /* * According to the settings of shared or not, Spring creates an ehcache base through CacheManager.create() or new CacheManager() respectively. */ @Bean public EhCacheManagerFactoryBean ehCacheManagerFactoryBean(){ EhCacheManagerFactoryBean cacheManagerFactoryBean = new EhCacheManagerFactoryBean (); cacheManagerFactoryBean.setConfigLocation (new ClassPathResource ("conf/ehcache-app.xml")); cacheManagerFactoryBean.setShared (true); return cacheManagerFactoryBean; }}@Configuration: Annotated for spring-boot, mainly annotated as a configuration class, and priority is given to scanning.
@Bean: Add bean to the spring container.
All configurations are done so far, and integrating the framework through spring-boot is that simple.
4. Use ehcache
Using ehcache is mainly through the spring cache mechanism. We have implemented the spring cache mechanism using ehcache, so we can use the spring cache mechanism completely in terms of use.
A few notes are involved:
@Cacheable: Responsible for adding the return value of the method to the cache, parameter 3
@CacheEvict: Responsible for clearing cache, parameter 4
Parameter explanation:
Without further ado, just upload the code:
@Servicepublic class CacheDemoServiceImpl implements CacheDemoService { /** * Cache key */ public static final String THING_ALL_KEY = "/"thing_all/""; /** * The value attribute indicates which cache policy to use. The cache policy is in ehcache.xml */ public static final String DEMO_CACHE_NAME = "demo"; @CacheEvict(value = DEMO_CACHE_NAME,key = THING_ALL_KEY) @Override public void create(Thing thing){ Long id = getNextId (); thing.setId (id); data.put (id, thing); } @Cacheable(value = DEMO_CACHE_NAME,key = "#thing.getId()+'thing'") @Override public Things findById(Long id){ System.err.println ("No cache!" + id); return data.get (id); } @Cacheable(value = DEMO_CACHE_NAME,key = THING_ALL_KEY) @Override public List<Thing> findAll(){ return Lists.newArrayList (data.values ()); } @Override @CachePut(value = DEMO_CACHE_NAME,key = "#thing.getId()+'thing'") @CacheEvict(value = DEMO_CACHE_NAME,key = THING_ALL_KEY) public What update(Thing thing){ System.out.println (thing); data.put (thing.getId (), thing); return thing; } @CacheEvict(value = DEMO_CACHE_NAME) @Override public void delete(Long id){ data.remove (id); } }5. You only need to annotate on the service layer method through annotations and you can use the cache, store the cache on find**, and clear the cache on delete** and update**.
Detailed explanation of Cache annotations
@CacheConfig: It is mainly used to configure some common cache configurations that will be used in this class. Here @CacheConfig(cacheNames = "users"): The content returned in the data access object is configured to be stored in the cache object named users. We can also define it directly through @Cacheable's own name of the cache set without using this annotation.
@Cacheable: The return value of the findByName function configured will be added to the cache. At the same time, when querying, it will first get from the cache, and if it does not exist, access to the database will be initiated. This annotation has the following parameters:
In addition to the two annotations used here, there are also the following core annotations:
@CachePut: Configured on a function, it can be cached according to the parameters and defines conditions. Unlike @Cacheable, it really calls the function every time, so it is mainly used for data addition and modification operations. Its parameters are similar to @Cacheable. For specific functions, please refer to the above analysis of @Cacheable parameters.
@CacheEvict: Configured on functions, usually used in deletion methods, to remove corresponding data from cache. In addition to the same parameters as @Cacheable, it has the following two parameters:
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.