Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

A case study of SpringBoot integrating Redis and Redis tool classes

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

SpringBoot integrates the case analysis of Redis and Redis tool classes. In view of this problem, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible method.

There are a lot of SpringBoot blogs integrating Redis, but many of them are not what I want. Because I just need to manipulate Redis after the integration is complete, and I don't need to use it with cache-related annotations (such as @ Cacheable). After reading a lot of blogs, I successfully integrated and wrote a Redis operation tool class. It is specially recorded here for follow-up reference.

I. Maven dependence

(1) the version of SpringBoot used in this article is as follows

Org.springframework.boot spring-boot-starter-parent 2.0.2.RELEASE

(2) add Redis related dependencies

Org.springframework.boot spring-boot-starter-data-redis II. Add redis related configuration # Redis database index (default is 0) spring.redis.database=0 # Redis server address spring.redis.host=192.168.0.24 # Redis server connection port spring.redis.port=6379 # Redis server connection password (default is empty) spring.redis.password= # maximum number of connections to the connection pool (use negative values for unlimited) spring.redis.pool.max- Active=200 # connection pool maximum blocking wait time (using negative values for unlimited) maximum idle connections in spring.redis.pool.max-wait=-1 # connection pool minimum idle connection spring.redis.pool.min-idle=0 # connection timeout (milliseconds) spring.redis.timeout=1000 3. Write a redis configuration class

(1) talk about the automatic configuration of RedisTemplate

In fact, you can inject RedisTemplate into your code now, so why can it be injected directly? Take a look at the source code first. The following picture is a screenshot in the RedisAutoConfiguration class, and the code is also posted to prevent the image from becoming invalid.

Code:

@ Configuration@ConditionalOnClass (RedisOperations.class) @ EnableConfigurationProperties (RedisProperties.class) @ Import ({LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class}) public class RedisAutoConfiguration {@ Bean @ ConditionalOnMissingBean (name = "redisTemplate") public RedisTemplate redisTemplate (RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {RedisTemplate template = new RedisTemplate (); template.setConnectionFactory (redisConnectionFactory); return template } @ Bean @ ConditionalOnMissingBean public StringRedisTemplate stringRedisTemplate (RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {StringRedisTemplate template = new StringRedisTemplate (); template.setConnectionFactory (redisConnectionFactory); return template;}}

As you can see from the source code, SpringBoot automatically helps us generate a RedisTemplate and a StringRedisTemplate in the container. However, the generics of this RedisTemplate are that it is not convenient to write code, and you need to write a lot of type conversion code; we need a RedisTemplate in the form of generics. Also, this RedisTemplate does not set the serialization of key and value when the data exists in Redis.

After seeing this @ ConditionalOnMissingBean annotation, you know that if there is a RedisTemplate object in the Spring container, the automatically configured RedisTemplate will not be instantiated. So we can directly write our own configuration class to configure RedisTemplate.

(2) since automatic configuration is not easy to use, reconfigure a RedisTemplate

The code is as follows:

Package com.zxy.demo.redis;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.data.redis.connection.RedisConnectionFactory;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;import org.springframework.data.redis.serializer.StringRedisSerializer;import com.fasterxml.jackson.annotation.JsonAutoDetect;import com.fasterxml.jackson.annotation.PropertyAccessor;import com.fasterxml.jackson.databind.ObjectMapper / * redis configuration class * @ author ZENG.XIAO.YAN * @ date June 6, 2018 * * / @ Configurationpublic class RedisConfig {@ Bean @ SuppressWarnings ("all") public RedisTemplate redisTemplate (RedisConnectionFactory factory) {RedisTemplate template = new RedisTemplate (); template.setConnectionFactory (factory); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer (Object.class); ObjectMapper om = new ObjectMapper () Om.setVisibility (PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping (ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper (om); StringRedisSerializer stringRedisSerializer = new StringRedisSerializer (); / / key uses String serialization method template.setKeySerializer (stringRedisSerializer); / / hash key also uses String serialization method template.setHashKeySerializer (stringRedisSerializer) / / jackson template.setValueSerializer (jackson2JsonRedisSerializer) is used for value serialization; / / jackson template.setHashValueSerializer (jackson2JsonRedisSerializer) is used for value serialization of hash; template.afterPropertiesSet (); return template;}} IV. Write a Redis tool class

Operating Redis directly with RedisTemplate requires a lot of lines of code, so encapsulating a RedisUtils directly makes it easier to write code. This RedisUtils is instantiated by the Spring container and is directly annotated and injected when used.

The tool class code is as follows:

Package com.zxy.demo.redis;import java.util.List;import java.util.Map;import java.util.Set;import java.util.concurrent.TimeUnit;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.stereotype.Component;import org.springframework.util.CollectionUtils / * Redis tools * @ author ZENG.XIAO.YAN * @ date June 7, 2018 * / @ Componentpublic final class RedisUtil {@ Autowired private RedisTemplate redisTemplate / / = = common== / * specify cache expiration time * @ param key key * @ param time time (seconds) * @ return * / public boolean expire (String key Long time) {try {if (time > 0) {redisTemplate.expire (key, time, TimeUnit.SECONDS) } return true;} catch (Exception e) {e.printStackTrace (); return false }} / * get expiration time based on key * @ param key key cannot return 0 for null * @ return time (seconds) represents permanent validity * / public long getExpire (String key) {return redisTemplate.getExpire (key, TimeUnit.SECONDS) } / * determine whether key exists * @ param key key * @ return true does not exist false does not exist * / public boolean hasKey (String key) {try {return redisTemplate.hasKey (key) } catch (Exception e) {e.printStackTrace (); return false;}} / * * delete cache * @ param key can pass a value or multiple * / @ SuppressWarnings ("unchecked") public void del (String...) Key) {if (key! = null & & key.length > 0) {if (key.length = = 1) {redisTemplate.delete (key [0]);} else {redisTemplate.delete (CollectionUtils.arrayToList (key)) } / / = = String== / * ordinary cache acquires * @ param key key * @ return value * / public Object get (String key) {return key = = null? Null: redisTemplate.opsForValue () .get (key) } / * * ordinary cache put in * @ param key key * @ param value value * @ return true false failed * / public boolean set (String key, Object value) {try {redisTemplate.opsForValue () .set (key, value) Return true;} catch (Exception e) {e.printStackTrace (); return false }} / * ordinary cache put and set time * @ param key key * @ param value value * @ param time time (seconds) time is greater than 0 if time is less than or equal to 0, indefinitely * @ return true success false failure * / public boolean set (String key, Object value) Long time) {try {if (time > 0) {redisTemplate.opsForValue () .set (key, value, time, TimeUnit.SECONDS) } else {set (key, value);} return true;} catch (Exception e) {e.printStackTrace (); return false }} / * incremental * @ param key key * @ param delta to add several (greater than 0) * @ return * / public long incr (String key, long delta) {if (delta)

< 0) { throw new RuntimeException("递增因子必须大于0"); } return redisTemplate.opsForValue().increment(key, delta); } /** * 递减 * @param key 键 * @param delta 要减少几(小于0) * @return */ public long decr(String key, long delta) { if (delta < 0) { throw new RuntimeException("递减因子必须大于0"); } return redisTemplate.opsForValue().increment(key, -delta); } // ================================Map================================= /** * HashGet * @param key 键 不能为null * @param item 项 不能为null * @return 值 */ public Object hget(String key, String item) { return redisTemplate.opsForHash().get(key, item); } /** * 获取hashKey对应的所有键值 * @param key 键 * @return 对应的多个键值 */ public Map hmget(String key) { return redisTemplate.opsForHash().entries(key); } /** * HashSet * @param key 键 * @param map 对应多个键值 * @return true 成功 false 失败 */ public boolean hmset(String key, Map map) { try { redisTemplate.opsForHash().putAll(key, map); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * HashSet 并设置时间 * @param key 键 * @param map 对应多个键值 * @param time 时间(秒) * @return true成功 false失败 */ public boolean hmset(String key, Map map, long time) { try { redisTemplate.opsForHash().putAll(key, map); if (time >

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report