Redis as a Java backend interview in a frequently asked test point, and more and more commonly used in the project, so I started to build a demo based on Springboot integration Redis as data cache (Springboot integration Mybatis, Redis, and with add, delete, change query interface). Pay attention to wechat public number [rookie A Du] and reply: redis, available source code. In the future, I will continue to study redis knowledge in depth. I look forward to learning and communicating with you.

Introduction of redis

Key-value pair-based open source in-memory database that supports five data types: string, hash, list, set, and zset. Spring Data Redis provides two templates for Data manipulation: RedisTemplate and StringRedisTemplate. StringRedisTemplate only operates on data whose key values are characters. StringRedisTemplate inherits from RedisTemplate and uses StringRedisSerializer to serialize the key values.

StringRedisTemplate implementation source code

public class StringRedisTemplate extends RedisTemplate<String, String>{ public StringRedisTemplate() { this.setKeySerializer(RedisSerializer.string()); this.setValueSerializer(RedisSerializer.string()); this.setHashKeySerializer(RedisSerializer.string()); this.setHashValueSerializer(RedisSerializer.string()); } } public interface RedisSerializer<T> { static RedisSerializer<String> string() { return StringRedisSerializer.UTF_8; }}Copy the code

The data access method provided by RedisTemplate

methods

instructions

opsForValue()

Manipulate data with only simple attributes

opsForList()

Operates on data containing a list

opsForSet()

Operates on data containing a set

opsForZSet()

Operates on data containing a ZSet(ordered set)

opsForHash()

Manipulate hash data

1. Add reIDS dependencies

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> The < version > against 2.4.1 < / version > < / dependency >Copy the code

2. Encapsulate redis utility classes

The operation method of Redis is encapsulated as a tool class for easy use

@component public class RedisUtil {@autoWired private RedisTemplate<Object, Object> RedisTemplate; / / in the data to the cache public void setValue (String key, value) Object {redisTemplate. OpsForValue (). The set (key, value); } / / get data by key public Object getValue (String key) {return redisTemplate. OpsForValue () get (key); } public void setValueAndExpire(String key, Object value, long time){ redisTemplate.opsForValue().set(key, value,time,TimeUnit.SECONDS); } public void delete(String key){redistemplate. delete(key); }}Copy the code

3. Use redis

If yes, the data in the memory will be returned. If no, the database will be queried and stored in the cache, and the queried data will be returned

@override public User find(int id) {User User =(User) redisUtil. GetValue ("userKey"+id); If (user==null){if(user==null){user= usermapper.find (id); System.out.println(" cache empty, query database "); / / insert the cache, and set the expiration time (in seconds) redisUtil. SetValueAndExpire (" userKey "+ id, the user, 30); System.out.println(" Insert cache "); }else{system.out.println (" cache is not empty "); } return user; }Copy the code

4. Customize the cache serialization method

RedisTemplate default serialization, JdkSerializaationRedisSerializer way for binary data storage, when using redis client tools to check the data is not straightforward, and it is necessary to serialize entity class (implement the Serializable interface). So write redis configuration class to modify RedisTemplate serialization way, will be modified for Jackson2JsonRedisSerialize JdkSerializaationRedisSerializer serialization mode, to save the data in json format. StringRedisTemplate uses StringRedisSerializer by default

@ Configuration public class RedisConfig {/ / using Jackson2JsonRedisSerialize replace the default JDK serialization @ Bean public RedisTemplate<Object,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){ RedisTemplate<Object,Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(redisConnectionFactory); / / key String serialization method redisTemplate. SetKeySerializer (new StringRedisSerializer ()); / / the hash key also USES String serialization way redisTemplate. SetHashKeySerializer (new StringRedisSerializer ()); . / / the value serialization way by Jackson redisTemplate setValueSerializer (new GenericJackson2JsonRedisSerializer ()); / / the hash value of the hash serialization way by Jackson redisTemplate. SetHashValueSerializer (new GenericJackson2JsonRedisSerializer ()); return redisTemplate; }}Copy the code

Default serialization (viewed from the redisClient client)

Data stored in cache after using custom serialization (viewed via redisClient client)

5. Result analysis

The first time, the cache was empty, the database was queried and inserted into the cache with a total of 2941 milliseconds, and the second time, fetched directly from the cache, took just 25 milliseconds

Total time: 2941 Total time: 25 when the cache is not emptyCopy the code

Pay attention to wechat public number [rookie A Du] and reply: redis, available source code

The resource acquisition

Reply keyword (Follow the public number)

describe

redis

Springboot integration redis., Mybatis to add, delete, change to check example source code

easymock

Get the free EasyMock interface service

springboot

Obtain SpringBoot integration Swagger, Mybatis to add, delete, change the sample source code

Redis client

Obtain redis database management software redisClient

Java resource

Get Java multithreading, SpringBoot, SQL optimization, Java interview video resources

Development manual

Alibaba Java Development Manual (Songshan Version)