Spring Boot cache technology (ehcache, SpringData Redis)

Spring boot integrates Ehcache Spring boot integrates spring dataredis I. spring boot integrates Ehcache 1. Import related maven dependencies <pro...
  • Spring boot integrates Ehcache
  • Spring boot integrates spring dataredis



I. spring boot integrates Ehcache

1. Import related maven dependencies

<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> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.10.RELEASE</version> </parent> <groupId>com.bjsxt</groupId> <artifactId>23-spring-boot-ehcache</artifactId> <version>0.0.1-SNAPSHOT</version> <properties> <java.version>1.7</java.version> <thymeleaf.version>3.0.2.RELEASE</thymeleaf.version> <thymeleaf-layout-dialect.version>2.0.4</thymeleaf-layout-dialect.version> </properties> <dependencies> <!-- springBoot Starter --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- springBoot Starter --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <!-- springBoot Starter --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <!-- Starter for test tool --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> <!-- mysql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!-- druid Connection pool --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.9</version> </dependency> <!-- Spring Boot Cache support initiator --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <!-- Ehcache coordinate --> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> </dependency> </dependencies> </project>


2. Create Ehcache configuration file

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd"> <diskStore path="java.io.tmpdir"/> <!--defaultCache:echcache Default cache policy for --> <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" maxElementsOnDisk="10000000" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU"> <persistence strategy="localTempSwap"/> </defaultCache> <!-- Custom cache policy --> <cache name="users" maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" maxElementsOnDisk="10000000" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU"> <persistence strategy="localTempSwap"/> </cache> </ehcache>


3. Modify the application.properties file

spring.datasource.driverClassName=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/ssm spring.datasource.username=root spring.datasource.password=root spring.datasource.type=com.alibaba.druid.pool.DruidDataSource #spring data forward engineering spring.jpa.hibernate.ddl-auto=update #Display sql spring.jpa.show-sql=true #Configure ehcache spring.cache.ehcache.cofnig=ehcache.xml


4. Modify the startup class and add @ EnableCaching on it

package com.bjsxt; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cache.annotation.EnableCaching; @SpringBootApplication @EnableCaching public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } }


5. Create business layer

package com.bjsxt.service; import java.util.List; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import com.bjsxt.pojo.Users; public interface UsersService { List<Users> findUserAll(); Users findUserById(Integer id); Page<Users> findUserByPage(Pageable pageable); void saveUsers(Users users); }
package com.bjsxt.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import com.bjsxt.dao.UsersRepository; import com.bjsxt.pojo.Users; import com.bjsxt.service.UsersService; /** * UsersService Interface implementation class * * */ @Service public class UsersServiceImpl implements UsersService { @Autowired private UsersRepository usersRepository; @Override @Cacheable(value = "users") public List<Users> findUserAll() { return this.usersRepository.findAll(); } @Override //@Cacheable: cache the objects of the current query @Cacheable(value="users") //value corresponds to the name of the custom cache policy public Users findUserById(Integer id) { return this.usersRepository.findOne(id); } }


6. Modify entity class

package com.bjsxt.pojo; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="t_users") public class Users implements Serializable { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") private Integer id; @Column(name="name") private String name; @Column(name="age") private Integer age; @Column(name="address") private String address; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "Users [id=" + id + ", name=" + name + ", age=" + age + ", address=" + address + "]"; } }


7, test

@Autowired private UsersService usersService; @Test public void testFindUserById(){ //First query System.out.println(this.usersService.findUserById(1)); //Second query System.out.println(this.usersService.findUserById(1)); }



II. @ Cacheable and @ CacheEvict

1,@Cacheable
  @ Cacheable function: add the return value of the method to Ehcache for caching
   value property: Specifies the cache policy in an Ehcache configuration file. If no value is given, name indicates the default cache policy

<!-- Custom cache policy --> <cache name="users" maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" maxElementsOnDisk="10000000" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU"> <persistence strategy="localTempSwap"/> </cache>

   Key property: gives a name to the stored value. If there is the same name in the query, the confidant will return the data from the cache

1.1 business layer

@Override @Cacheable(value = "users",key = "#pageable.pageSize") public Page<Users> findUserByPage(Pageable pageable) { return this.usersRepository.findAll(pageable); }


1.2 test code

@Test public void testFindUserByPage(){ Pageable pageable=new PageRequest(0,2); //First query System.out.println(this.usersService.findUserByPage(pageable).getTotalElements()); //Second query System.out.println(this.usersService.findUserByPage(pageable).getTotalElements()); //Third query pageable=new PageRequest(1,2); System.out.println(this.usersService.findUserByPage(pageable).getTotalElements()); }


2,@CacheEvict

@CacheEvict function: clear cache

2.1 business layer

package com.bjsxt.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import com.bjsxt.dao.UsersRepository; import com.bjsxt.pojo.Users; import com.bjsxt.service.UsersService; /** * UsersService Interface implementation class * * */ @Service public class UsersServiceImpl implements UsersService { @Autowired private UsersRepository usersRepository; @Override @Cacheable(value = "users") public List<Users> findUserAll() { return this.usersRepository.findAll(); } @Override //@Cacheable: cache the objects of the current query @Cacheable(value="users") //value corresponds to the name of the custom cache policy public Users findUserById(Integer id) { return this.usersRepository.findOne(id); } @Override @Cacheable(value = "users",key = "#pageable.pageSize") public Page<Users> findUserByPage(Pageable pageable) { return this.usersRepository.findAll(pageable); } @Override @CacheEvict(value = "users",allEntries = true)//Clear cached objects in the cache with users cache policy public void saveUsers(Users users) { this.usersRepository.save(users); } }


2.2 test code

@Test public void testFindAll(){ //First query System.out.println(usersService.findUserAll().size()); Users users=new Users(); users.setAddress("Nanjing"); users.setAge(43); users.setName("Zhu Qi"); this.usersService.saveUsers(users); //Second query System.out.println(usersService.findUserAll().size()); }



III. spring boot integrates spring dataredis

Redis version: 3.2.1
Running environment: windows

1. SpringBoot integrates SpringDataRedis

Spring data redis is a module under spring data. The function is to simplify the operation of redis

1.1. Modify the pom file to add the coordinates of SpringDataRedis

<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> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.10.RELEASE</version> </parent> <groupId>com.bjsxt</groupId> <artifactId>24-spring-boot-redis</artifactId> <version>0.0.1-SNAPSHOT</version> <properties> <java.version>1.7</java.version> <thymeleaf.version>3.0.2.RELEASE</thymeleaf.version> <thymeleaf-layout-dialect.version>2.0.4</thymeleaf-layout-dialect.version> </properties> <dependencies> <!-- springBoot Starter --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- thymeleaf Starter --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <!-- Spring Data Redis Starter --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <!-- Starter for test tool --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> </dependencies> </project>


1.2. Write the configuration class of SpringDataRedis (emphasis)

package com.bjsxt.config; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.StringRedisSerializer; import redis.clients.jedis.JedisPoolConfig; /** * Complete some configuration of Redis integration * * */ @Configuration public class RedisConfig { /** * 1.Create a JedisPoolConfig object. Complete some link pool configuration in this object * @ConfigurationProperties:Creates an entity with the same prefix */ @Bean @ConfigurationProperties(prefix = "spring.redis.pool") public JedisPoolConfig jedisPoolConfig(){ JedisPoolConfig config = new JedisPoolConfig(); //Maximum number of idle config.setMaxIdle(10); //Minimum number of idle config.setMinIdle(5); //Maximum number of links config.setMaxTotal(20); System.out.println("Default value"+config.getMaxIdle()); System.out.println("Default value"+config.getMinIdle()); System.out.println("Default value"+config.getMaxTotal()); return config; } /** * 2.Create JedisConnectionFactory: configure redis link information */ @Bean @ConfigurationProperties(prefix = "spring.redis") public JedisConnectionFactory jedisConnectionFactory(JedisPoolConfig config){ System.out.println("Configuration completed"+config.getMaxIdle()); System.out.println("Configuration completed"+config.getMinIdle()); System.out.println("Configuration completed"+config.getMaxTotal()); JedisConnectionFactory factory = new JedisConnectionFactory(); //Associated link pool configuration object factory.setPoolConfig(config); //Configure the information of Redis //Host address factory.setHostName("127.0.0.1"); //port factory.setPort(6379); return factory; } /** * 3.Create RedisTemplate: method used to perform Redis operation */ @Bean public RedisTemplate<String,Object> redisTemplate(JedisConnectionFactory factory){ RedisTemplate<String, Object> template = new RedisTemplate<>(); //Relation template.setConnectionFactory(factory); //Set serializer for key template.setKeySerializer(new StringRedisSerializer()); //Set serializer for value template.setValueSerializer(new StringRedisSerializer()); return template; } }


1.3 write test code and test integration environment

   1.3.1, write test class

@Autowired private RedisTemplate<String,Object> redisTemplate; //Add a string @Test public void testSet(){ this.redisTemplate.opsForValue().set("key","clothes worn by low-rank officials"); } //Take a string @Test public void testGet(){ String value= (String) this.redisTemplate.opsForValue().get("key"); System.out.println(value); }


2. Extract the configuration information of redis

2.1. Create a new configuration file in the src/main/resource / Directory: application.properties

#Maximum number of idle spring.redis.pool.max-idle=10 #Minimum number of idle spring.redis.pool.min-idle=5 #Maximum number of links spring.redis.pool.max-total=20 #Host ip spring.redis.host=127.0.0.1 #redis port spring.redis.port=6379


2.2. Modify the redis configuration class

package com.bjsxt.config; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.StringRedisSerializer; import redis.clients.jedis.JedisPoolConfig; /** * Complete some configuration of Redis integration * * */ @Configuration public class RedisConfig { /** * 1.Create a JedisPoolConfig object. Complete some link pool configuration in this object * @ConfigurationProperties:Creates an entity with the same prefix */ @Bean @ConfigurationProperties(prefix = "spring.redis.pool") public JedisPoolConfig jedisPoolConfig(){ JedisPoolConfig config = new JedisPoolConfig(); System.out.println("Default value"+config.getMaxIdle()); System.out.println("Default value"+config.getMinIdle()); System.out.println("Default value"+config.getMaxTotal()); return config; } /** * 2.Create JedisConnectionFactory: configure redis link information */ @Bean @ConfigurationProperties(prefix = "spring.redis") public JedisConnectionFactory jedisConnectionFactory(JedisPoolConfig config){ System.out.println("Configuration completed"+config.getMaxIdle()); System.out.println("Configuration completed"+config.getMinIdle()); System.out.println("Configuration completed"+config.getMaxTotal()); JedisConnectionFactory factory = new JedisConnectionFactory(); //Associated link pool configuration object factory.setPoolConfig(config); return factory; } /** * 3.Create RedisTemplate: method used to perform Redis operation */ @Bean public RedisTemplate<String,Object> redisTemplate(JedisConnectionFactory factory){ RedisTemplate<String, Object> template = new RedisTemplate<>(); //Relation template.setConnectionFactory(factory); //Set serializer for key template.setKeySerializer(new StringRedisSerializer()); //Set serializer for value template.setValueSerializer(new StringRedisSerializer()); return template; } }


3. SpringDataRedis operation entity object

   3.1.1 create entity class

/** * Copyright (C), 2015-2019, XXX Limited company * FileName: Users * Author: admin * Date: 2019/5/24 11:25 * Description: * History: * <author> <time> <version> <desc> * Author name modification time version number Description */ package com.bjsxt.pojo; import java.io.Serializable; /** * 〈Brief description of one sentence function < br > * 〈〉 * * @author admin * @create 2019/5/24 * @since 1.0.0 */ public class Users implements Serializable { private Integer id; private String name; private Integer age; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { final StringBuffer sb = new StringBuffer("Users{"); sb.append("id=").append(id); sb.append(", name='").append(name).append('\''); sb.append(", age=").append(age); sb.append('}'); return sb.toString(); } }


3.1.2 test code

/** * Add a Users object */ @Test public void testSetUsers(){ Users users=new Users(); users.setAge(20); users.setName("Zhang Sanfeng"); users.setId(1); //To save, reset the serializer this.redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer()); this.redisTemplate.opsForValue().set("users",users); } /** * Take Users object */ @Test public void testGetUsers(){ //The serializer must be reset for the operation of fetching this.redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer()); Users users= (Users) this.redisTemplate.opsForValue().get("users"); System.out.println(users); }


4. SpringDataRedis stores entity objects in JSON format

   4.1 test code

/** * Saving Users object based on JSON format */ @Test public void testSetUsersUseJSON(){ Users users=new Users(); users.setAge(20); users.setName("Si Feng Li"); users.setId(1); this.redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<>(Users.class)); this.redisTemplate.opsForValue().set("users_json",users); } /** * Take Users object based on JSON format */ @Test public void testGetUseJSON(){ //De serialization this.redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<>(Users.class)); Users users= (Users) this.redisTemplate.opsForValue().get("users_json"); System.out.println(users); }

5 November 2019, 14:18 | Views: 9316

Add new comment

For adding a comment, please log in
or create account

0 comments