In the work, when we use distributed cache, the first choice is Redis, today we introduce how SpringBoot integrates Redis, respectively using Jedis and Spring-data-Redis two ways.
I. Use Jedis for integration
1. Increase dependency
<! Spring-boot-starter-web is not required, <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> </dependency> <dependency> <! -- Fastjson is not required, Alibaba </groupId> <artifactId>fastjson</artifactId> <version>1.2.73</version> </dependency>Copy the code
2. Configuration items
Redis. host=localhost redis.maxTotal=5 redis.maxIdle=5 redis.testOnBorrow=true #redis.max-total=3 #redis.max-idle=3 #redis.test-on-borrow=trueCopy the code
3. Configure a connection pool
/** * @author Since Jedis instances themselves are not thread-safe, So we use JedisPool */ @configuration public class CommonConfig {@bean @configurationProperties ("redis") public JedisPoolConfig jedisPoolConfig() { return new JedisPoolConfig(); } @Bean(destroyMethod = "close") public JedisPool jedisPool(@Value("${redis.host}") String host) { return new JedisPool(jedisPoolConfig(), host); }}Copy the code
4, test,
/** * @author public class JedisController {@autoWired private JedisPool JedisPool; @RequestMapping("getUser") public String getUserFromRedis(){ UserInfo userInfo = new UserInfo(); userInfo.setUserId("A0001"); Userinfo.setusername (" zhang Sanfeng "); Userinfo.setaddress (" Wudang Mountain "); jedisPool.getResource().set("userInfo", JSON.toJSONString(userInfo)); UserInfo userInfo1 = JSON.parseObject(jedisPool.getResource().get("userInfo"),UserInfo.class); return userInfo1.toString(); }}Copy the code
The running results are as follows:
We can wrap a RedisClient ourselves to simplify our operations
Using the spring – data – redis
1. Introduce dependencies
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
Copy the code
2. Configuration items
Add configuration in application.properties
spring.redis.host=localhost
spring.redis.port=6379
Copy the code
3, use,
/** * @author @restController Public class RedisController {@autoWired private RedisTemplate RedisTemplate; @RequestMapping("getUser2") public String getUserFromRedis(){ UserInfo userInfo = new UserInfo(); userInfo.setUserId("A0001"); Userinfo.setusername (" zhang Sanfeng "); Userinfo.setaddress (" Wudang Mountain "); redisTemplate.opsForValue().set("userInfo", userInfo); UserInfo userInfo1 = (UserInfo) redisTemplate.opsForValue().get("userInfo"); return userInfo1.toString(); }}Copy the code
Yes, you just need to import dependencies and add configurations to use Redis, don’t get too excited, there are some pitfalls
4, may encounter pits
Use the tool to check the contents of the set, we found that there is a string of characters in front of the key, and the value is not visible
why
Using springdataredis, by default is to use an org. Springframework. Data. Redis. Serializer. JdkSerializationRedisSerializer this class to be serialized How does the RedisTemplate code work
/ * * * at the time of initialization, the default serialization class is JdkSerializationRedisSerializer * / public void afterPropertiesSet () {super. AfterPropertiesSet (); boolean defaultUsed = false; if (this.defaultSerializer == null) { this.defaultSerializer = new JdkSerializationRedisSerializer(this.classLoader ! = null ? this.classLoader : this.getClass().getClassLoader()); }... Omit extraneous code}Copy the code
How to solve
It’s easy to define your own RedisTemplate and specify the serialized class
/** * @author */ @configuration public class RedisConfig {@bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(connectionFactory); template.setValueSerializer(jackson2JsonRedisSerializer()); / / use StringRedisSerializer to serialization and deserialization redis template. The key value of setKeySerializer (new StringRedisSerializer ()); template.setHashKeySerializer(new StringRedisSerializer()); template.setHashValueSerializer(jackson2JsonRedisSerializer()); template.afterPropertiesSet(); return template; } @Bean public RedisSerializer<Object> jackson2JsonRedisSerializer() { / / use Jackson2JsonRedisSerializer to serialization and deserialization of redis value value Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper mapper = new ObjectMapper(); mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); serializer.setObjectMapper(mapper); return serializer; }}Copy the code
View the run result:
Sentinels and clusters
You just need to change the configuration items
# sentry spring. Redis. Sentinel. Master = mymaster spring. Redis.. Sentinel nodes = 127.0.0.1:26379127.00 0.1:26380127.00 0.1:26381 # cluster spring. Redis. Cluster. The Max - redirects = 100 Spring. Redis. Cluster nodes = 127.0.0.1:6379127.00 0.1:6380127.00 0.1:6381127.00 0.1:6382127.00 0.1:6383127.00 0.1:6384Copy the code
Summary: This is just a brief introduction to how to integrate, if it helps you, please give it a thumbs up!