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?
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?
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. RedisTemplate
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.
<!-- redis --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
The above has introduced the dependency of redis, please add the other dependencies by yourself
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
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<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { // 配置redisTemplate RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(redisConnectionFactory); // 设置序列化 Jackson2JsonRedisSerializer<Object> 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; } }
We inject a file named redisTemplate, a Bean of type RedisTemplate
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<String, Object> 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; } }
We wrote the get and set methods for testing
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; }
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")); } }
We store a data with key "user" and value as UserInfo object into Redis, and then obtain the data based on key
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!