Home> Database> Redis> body text

How SpringBoot integrates Redis to serialize and store Java objects

WBOY
Release: 2023-05-29 08:43:10
forward
1331 people have browsed it

1. Background

1. Thinking

Through our previous study, we can already store strings in Redis, so what should we do to store Java objects in Redis? What to do?

2. Solution

We can convert Java objects into JSON objects, then into JSON strings, and store them in Redis. Then when we take out the data from Redis, we only Can take out a string and convert it into a Java object. Does this series of operations seem a bit troublesome?

2. Source code analysis

How SpringBoot integrates Redis to serialize and store Java objects

  • The above is the source code fragment in the RedisAutoConfiguration class. It can be seen that SpringBoot automatically configures Redis. At that time, redisTemplate and stringRedisTemplate

  • were injected into the container. RedisTemplatemeans that the key type is Object and the value type is Object, but what we often need is RedisTemplate , this requires us to re-inject a RedisTemplate Bean, its generic type is RedisTemplate , and set the serialization method of key and value

  • After seeing this @ConditionalOnMissingBean annotation, you know that if there is a RedisTemplate object in the Spring container, this automatically configured RedisTemplate will not be instantiated. Therefore, we have the ability to write custom configuration classes to configure RedisTemplate.

3. Inject RedisTemplate

1. Introduce dependencies

  org.springframework.boot spring-boot-starter-data-redis 
Copy after login

The above has introduced the dependency of redis, please add the other dependencies by yourself

2. Redis connection information

spring: # Redis配置 redis: host: 127.0.0.1 port: 6379 database: 10 jedis: pool: # 连接池最大连接数(使用负值表示没有限制) max-active: 50 # 连接池最大阻塞等待时间(使用负值表示没有限制) max-wait: 3000ms # 连接池中的最大空闲连接数 max-idle: 20 # 连接池中的最小空闲连接数 min-idle: 5 # 连接超时时间(毫秒) timeout: 5000ms
Copy after login

3. Redis core configuration class

We place the core configuration of Redis in the RedisConfig.java file

package com.zyxx.redistest.common; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; /** * @ClassName RedisConfig * @Description * @Author Lizhou * @Date 2020-10-22 9:48:48 **/ @Configuration public class RedisConfig { /** * RedisTemplate配置 */ @Bean public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) { // 配置redisTemplate RedisTemplate redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(redisConnectionFactory); // 设置序列化 Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY); jackson2JsonRedisSerializer.setObjectMapper(om); // key序列化 redisTemplate.setKeySerializer(new StringRedisSerializer()); // value序列化 redisTemplate.setValueSerializer(jackson2JsonRedisSerializer); // Hash key序列化 redisTemplate.setHashKeySerializer(new StringRedisSerializer()); // Hash value序列化 redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer); redisTemplate.afterPropertiesSet(); return redisTemplate; } }
        
Copy after login

We inject a file named redisTemplate, a Bean of type RedisTemplate , the key uses the StringRedisSerializer serialization method, and the value uses the Jackson2JsonRedisSerializer serialization method

4, Redis tool class

We will conduct a series of Redis The series of operations are placed in the RedisUtils.java file

package com.zyxx.redistest.common; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Component; /** * @ClassName RedisUtils * @Description * @Author Lizhou * @Date 2020-10-22 10:10:10 **/ @Slf4j @Component public class RedisUtils { @Autowired private RedisTemplate redisTemplate; /** * 根据key读取数据 */ public Object get(final String key) { if (StringUtils.isBlank(key)) { return null; } try { return redisTemplate.opsForValue().get(key); } catch (Exception e) { e.printStackTrace(); } return null; } /** * 写入数据 */ public boolean set(final String key, Object value) { if (StringUtils.isBlank(key)) { return false; } try { redisTemplate.opsForValue().set(key, value); log.info("存入redis成功,key:{},value:{}", key, value); return true; } catch (Exception e) { log.error("存入redis失败,key:{},value:{}", key, value); e.printStackTrace(); } return false; } }
Copy after login

We wrote the get and set methods for testing

4. Test

1. Create a Java entity class UserInfo

package com.zyxx.redistest.common; import lombok.Data; import java.io.Serializable; import java.util.Date; /** * @ClassName UserInfo * @Description * @Author Lizhou * @Date 2020-10-22 10:12:12 **/ @Data public class UserInfo implements Serializable { /** * id */ private Integer id; /** * 姓名 */ private String name; /** * 创建时间 */ private Date createTime; }
Copy after login

2. Test case

package com.zyxx.redistest; import com.zyxx.redistest.common.RedisUtils; import com.zyxx.redistest.common.UserInfo; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.util.Date; @SpringBootTest class RedisTestApplicationTests { @Autowired private RedisUtils redisUtil; @Test void contextLoads() { UserInfo userInfo = new UserInfo(); userInfo.setId(1); userInfo.setName("jack"); userInfo.setCreateTime(new Date()); // 放入redis redisUtil.set("user", userInfo); // 从redis中获取 System.out.println("获取到数据:" + redisUtil.get("user")); } }
Copy after login

We store a data with key "user" and value as UserInfo object into Redis, and then obtain the data based on key

3. Test results

How SpringBoot integrates Redis to serialize and store Java objects

It can be seen that we successfully stored Java object data in Redis and successfully obtained the object.

The above is the detailed content of How SpringBoot integrates Redis to serialize and store Java objects. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!