Earlier we introduced the usage of two in-process caches, including the default ones used by Spring Boot ConcurrentMap cache as well as Cache framework EhCache . Although EhCache can be applied to many application scenarios, since EhCache is an in-process caching framework, in cluster mode, the caches between each application server are independent, so there will be cache inconsistencies between processes of different servers. . Even though EhCache provides a cache synchronization strategy in a cluster environment, synchronization still takes a certain amount of time, and temporary cache inconsistencies still exist.
In some systems and applications that require high consistency (any data changes can be queried in time), EhCache can no longer be used to solve the problem. At this time, the use of centralized cache can solve the consistency of cached data very well. question. Next, let's learn how to use Redis to implement data caching in Spring Boot's caching support.
try it out
The implementation of this article will be based on Previous basic engineering. Let's review the program elements in the previous article:
Definition of User entity
@Entity @Data @NoArgsConstructor public class User implements Serializable { @Id @GeneratedValue private Long id; private String name; private Integer age; public User(String name, Integer age) { this.name = name; this.age = age; } }
Data access implementation for User entity (covers cache annotations)
@CacheConfig(cacheNames = "users") public interface UserRepository extends JpaRepository<User, Long> { @Cacheable User findByName(String name); }
Let's start transforming this project:
Step 1: Add related dependencies to pom.xml:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> </dependency>
In earlier versions of Spring Boot 1.x, this dependency was named spring-boot-starter-redis, so in Spring Boot 1.x Basic Tutorial different from here.
Step 2: Add configuration information to the configuration file, take local operation as an example, for example:
spring.redis.host=localhost spring.redis.port=6379 spring.redis.lettuce.pool.max-idle=8 spring.redis.lettuce.pool.max-active=8 spring.redis.lettuce.pool.max-wait=-1ms spring.redis.lettuce.pool.min-idle=0 spring.redis.lettuce.shutdown-timeout=100ms
Regarding the configuration of the connection pool, note a few points:
- The connection pool configuration of Redis is prefixed with spring.redis.pool in version 1.x and is different from Spring Boot 2.x.
- In the 1.x version, jedis is used as the connection pool, and in the 2.x version, lettuce is used as the connection pool
- The above configurations are all default values. In fact, production needs to be further modified according to the deployment situation and business requirements.
Let's try the unit test again:
@Slf4j @RunWith(SpringRunner.class) @SpringBootTest public class Chapter54ApplicationTests { @Autowired private UserRepository userRepository; @Autowired private CacheManager cacheManager; @Test public void test() throws Exception { System.out.println("CacheManager type : " + cacheManager.getClass()); // Create 1 record userRepository.save(new User("AAA", 10)); User u1 = userRepository.findByName("AAA"); System.out.println("First query:" + u1.getAge()); User u2 = userRepository.findByName("AAA"); System.out.println("Second query:" + u2.getAge()); } }
Execute the test output to get:
CacheManager type : class org.springframework.data.redis.cache.RedisCacheManager Hibernate: select next_val as id_val from hibernate_sequence for update Hibernate: update hibernate_sequence set next_val= ? where next_val=? Hibernate: insert into user (age, name, id) values (?, ?, ?) 2020-08-12 16:25:26.954 INFO 68282 --- [ main] io.lettuce.core.EpollProvider : Starting without optional epoll library 2020-08-12 16:25:26.955 INFO 68282 --- [ main] io.lettuce.core.KqueueProvider : Starting without optional kqueue library Hibernate: select user0_.id as id1_0_, user0_.age as age2_0_, user0_.name as name3_0_ from user user0_ where user0_.name=? First query: 10 Second query: 10
can be seen:
- The CacheManager type output in the first line is org.springframework.data.redis.cache.RedisCacheManager instead of EhCacheCacheManager in the previous article
- When querying for the second time, there is no SQL statement output, so it is obtained from the cache.
Integration succeeded!
thinking questions
Since EhCache and other in-process caches have consistency problems, and Redis has good performance and can solve the consistency problem, then we just need to learn to use Redis, why should we learn in-process caches? Leave your thoughts first, and we will discuss this issue together in the next article! Welcome to this series of tutorials: "Spring Boot 2.x Basic Tutorial"
code example
Examples of this article can be found in the chapter5-4 directory in the following repository:
- Github: https://github.com/dyc87112/SpringBoot-Learning/
- Gitee: https://gitee.com/didispace/SpringBoot-Learning/
If you think this article is good, you are welcome to support Star, your attention is the driving force for me to persevere!
This article was first published: Spring Boot 2.x Basic Tutorial: Using Centralized Cache Redis ,Please indicate the source. Welcome to pay attention to my official account: Programmer DD, get exclusive learning resources and daily dry goods push. Click to go directly to the catalog of this series of tutorials.