springboot integrates redis
- Add dependencies
- yml configuration file
- RedisTemplate configuration
- Serialization
- redis tool class
Current environment springboot version 2.7.17
Add dependencies
<!-- redis --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <!-- redis depends on commons-pool. This dependency must be added --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> </dependency> <!-- Alibaba JSON parser --> <dependency> <groupId>com.alibaba.fastjson2</groupId> <artifactId>fastjson2</artifactId> <version>2.0.14</version> </dependency>
yml configuration file
spring: redis: host: 127.0.0.1 port: 6379 password: database: 0 lettuce: pool: max-idle: 8 min-idle: 0 max-active: 8 max-wait: -1 timeout: 30000
RedisTemplate configuration
import org.springframework.cache.annotation.CachingConfigurerSupport; import org.springframework.cache.annotation.EnableCaching; 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.StringRedisSerializer; /** * redis configuration * * @author */ @Configuration @EnableCaching public class RedisConfig extends CachingConfigurerSupport { @Bean @SuppressWarnings(value = { "unchecked", "rawtypes" }) public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(connectionFactory); FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer(Object.class); //Use StringRedisSerializer to serialize and deserialize redis key values template.setKeySerializer(new StringRedisSerializer()); template.setValueSerializer(serializer); // The Hash key also uses the StringRedisSerializer serialization method. template.setHashKeySerializer(new StringRedisSerializer()); template.setHashValueSerializer(serializer); template.afterPropertiesSet(); return template; } }
Serialization
import com.alibaba.fastjson2.JSON; import com.alibaba.fastjson2.JSONReader; import com.alibaba.fastjson2.JSONWriter; import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.data.redis.serializer.SerializationException; import java.nio.charset.Charset; /** * Redis uses FastJson serialization * * @author */ public class FastJson2JsonRedisSerializer<T> implements RedisSerializer<T> { public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); private Class<T>clazz; public FastJson2JsonRedisSerializer(Class<T> clazz) { super(); this.clazz = clazz; } @Override public byte[] serialize(T t) throws SerializationException { if (t == null) { return new byte[0]; } return JSON.toJSONString(t, JSONWriter.Feature.WriteClassName).getBytes(DEFAULT_CHARSET); } @Override public T deserialize(byte[] bytes) throws SerializationException { if (bytes == null || bytes.length <= 0) { return null; } String str = new String(bytes, DEFAULT_CHARSET); return JSON.parseObject(str, clazz, JSONReader.Feature.SupportAutoType); } }
redis tool class
import cn.hutool.core.collection.CollUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; /** * Redis tool class */ @Component public final class RedisUtil { @Autowired private RedisTemplate<String, Object> redisTemplate2; private static RedisTemplate<String, Object> redisTemplate; @PostConstruct public void init() { redisTemplate = redisTemplate2; } // =============================common==================== ========== /** * Specify cache expiration time * @param key key * @param time time (seconds) * @return */ public static 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 be null * @return time (seconds) Returning 0 means it is permanently valid */ public static long getExpire(String key) { return redisTemplate.getExpire(key, TimeUnit.SECONDS); } /** * Determine whether the key exists * @param key key * @return true exists false does not exist */ public static boolean hasKey(String key) { try { return redisTemplate.hasKey(key); } catch (Exception e) { e.printStackTrace(); return false; } } /** * Delete cache * @param key can pass one value or multiple */ @SuppressWarnings("unchecked") public static void del(String... key) { if (key != null & amp; & amp; key.length > 0) { if (key.length == 1) { redisTemplate.delete(key[0]); } else { redisTemplate.delete(CollUtil.toList(key)); } } } // ===========================String==================== ========== /** * Ordinary cache acquisition * @param key key * @return value */ public static Object get(String key) { return key == null ? null : redisTemplate.opsForValue().get(key); } /** * put in normal cache * @param key key * @param value value * @return true success false failure */ public static boolean set(String key, Object value) { try { redisTemplate.opsForValue().set(key, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * Put the normal cache into and set the time * @param key key * @param value value * @param time time (seconds) time must be greater than 0. If time is less than or equal to 0, it will be set indefinitely. * @return true success false failure */ public static 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; } } /** *increment * @param key key * @param delta How much to increase (greater than 0) * @return */ public static long incr(String key, long delta) { if (delta < 0) { throw new RuntimeException("The increment factor must be greater than 0"); } return redisTemplate.opsForValue().increment(key, delta); } /** * Decreasing * @param key key * @param delta How much to reduce (less than 0) * @return */ public static long decr(String key, long delta) { if (delta < 0) { throw new RuntimeException("Decreasing factor must be greater than 0"); } return redisTemplate.opsForValue().increment(key, -delta); } // ===============================Map================ ================== /** *HashGet * @param key key cannot be null * @param item item cannot be null * @return value */ public static Object hget(String key, String item) { return redisTemplate.opsForHash().get(key, item); } /** * Get all key values corresponding to hashKey * @param key key * @return corresponding multiple key values */ public static Map<Object, Object> hmget(String key) { return redisTemplate.opsForHash().entries(key); } /** *HashSet * @param key key * @param map corresponds to multiple key values * @return true success false failure */ public static boolean hmset(String key, Map<String, Object> map) { try { redisTemplate.opsForHash().putAll(key, map); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * HashSet and set the time * @param key key * @param map corresponds to multiple key values * @param time time (seconds) * @return true success false failure */ public static boolean hmset(String key, Map<String, Object> map, long time) { try { redisTemplate.opsForHash().putAll(key, map); if (time > 0) { expire(key, time); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * Put data into a hash table, if it does not exist, it will be created * @param key key * @param item item * @param value value * @return true success false failure */ public static boolean hset(String key, String item, Object value) { try { redisTemplate.opsForHash().put(key, item, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * Put data into a hash table, if it does not exist, it will be created * @param key key * @param item item * @param value value * @param time time (seconds) Note: If the existing hash table has time, the original time will be replaced here * @return true success false failure */ public static boolean hset(String key, String item, Object value, long time) { try { redisTemplate.opsForHash().put(key, item, value); if (time > 0) { expire(key, time); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * Delete the value in the hash table * @param key key cannot be null * @param item item can be multiple and cannot be null */ public static void hdel(String key, Object... item) { redisTemplate.opsForHash().delete(key, item); } /** * Determine whether there is a value for the item in the hash table * @param key key cannot be null * @param item item cannot be null * @return true exists false does not exist */ public static boolean hHasKey(String key, String item) { return redisTemplate.opsForHash().hasKey(key, item); } /** * Hash increment If it does not exist, it will create one and return the new value. * @param key key * @param item item * @param by How many to add (greater than 0) * @return */ public static double hincr(String key, String item, double by) { return redisTemplate.opsForHash().increment(key, item, by); } /** * hash decrementing * @param key key * @param item item * @param by To reduce the number (less than 0) * @return */ public static double hdecr(String key, String item, double by) { return redisTemplate.opsForHash().increment(key, item, -by); } // ===========================set==================== ========== /** * Get all values in Set based on key * @param key key * @return */ public static Set<Object> sGet(String key) { try { return redisTemplate.opsForSet().members(key); } catch (Exception e) { e.printStackTrace(); return null; } } /** * Query from a set based on value to see if it exists * @param key key * @param value value * @return true exists false does not exist */ public static boolean sHasKey(String key, Object value) { try { return redisTemplate.opsForSet().isMember(key, value); } catch (Exception e) { e.printStackTrace(); return false; } } /** * Put data into set cache * @param key key * @param values The value can be multiple * @return the number of successes */ public static long sSet(String key, Object... values) { try { return redisTemplate.opsForSet().add(key, values); } catch (Exception e) { e.printStackTrace(); return 0; } } /** * Put the set data into cache * @param key key * @param time time (seconds) * @param values The value can be multiple * @return the number of successes */ public static long sSetAndTime(String key, long time, Object... values) { try { Long count = redisTemplate.opsForSet().add(key, values); if (time > 0) expire(key, time); return count; } catch (Exception e) { e.printStackTrace(); return 0; } } /** * Get the length of the set cache * @param key key * @return */ public static long sGetSetSize(String key) { try { return redisTemplate.opsForSet().size(key); } catch (Exception e) { e.printStackTrace(); return 0; } } /** * Remove the value of value * @param key key * @param values The value can be multiple * @return the number of items removed */ public static long setRemove(String key, Object... values) { try { Long count = redisTemplate.opsForSet().remove(key, values); return count; } catch (Exception e) { e.printStackTrace(); return 0; } } // ===============================list================ ================= /** * Get the contents of the list cache * @param key key * @param start start * @param end End 0 to -1 represents all values * @return */ public static List<Object> lGet(String key, long start, long end) { try { return redisTemplate.opsForList().range(key, start, end); } catch (Exception e) { e.printStackTrace(); return null; } } /** * Get the length of the list cache * @param key key * @return */ public static long lGetListSize(String key) { try { return redisTemplate.opsForList().size(key); } catch (Exception e) { e.printStackTrace(); return 0; } } /** * Get the value in the list by index * @param key key * @param index index When index>=0, 0 is the header, 1 is the second element, and so on; when index<0, -1 is the tail, -2 is the penultimate element, and so on. * @return */ public static Object lGetIndex(String key, long index) { try { return redisTemplate.opsForList().index(key, index); } catch (Exception e) { e.printStackTrace(); return null; } } /** * Put the list into cache * @param key key * @param value value * @return */ public static boolean lSet(String key, Object value) { try { redisTemplate.opsForList().rightPush(key, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * Put the list into cache * @param key key * @param value value * @param time time (seconds) * @return */ public static boolean lSet(String key, Object value, long time) { try { redisTemplate.opsForList().rightPush(key, value); if (time > 0) expire(key, time); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * Put the list into cache * @param key key * @param value value * @return */ public static boolean lSet(String key, List<Object> value) { try { redisTemplate.opsForList().rightPushAll(key, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * Put the list into cache * * @param key key * @param value value * @param time time (seconds) * @return */ public static boolean lSet(String key, List<Object> value, long time) { try { redisTemplate.opsForList().rightPushAll(key, value); if (time > 0) expire(key, time); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * Modify a piece of data in the list based on the index * @param key key * @param index index * @param value value * @return */ public static boolean lUpdateIndex(String key, long index, Object value) { try { redisTemplate.opsForList().set(key, index, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * Remove N values as value * @param key key * @param count How many to remove * @param value value * @return the number of items removed */ public static long lRemove(String key, long count, Object value) { try { Long remove = redisTemplate.opsForList().remove(key, count, value); return remove; } catch (Exception e) { e.printStackTrace(); return 0; } } }