JDK21 Springboot3整合redis7 (为什么要配置RedisTemplate配置类)
SpringBoot3整合Redis7,所用JDK版本为21
将Redis starter场景导入到Springboot3
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
配置redistemplate配置类
import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator; 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; /** * <p> * Redis 配置类 * </p> * * @author MingHai * @since 2024/9/14 */ @Configuration public class redisConfig { @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(redisConnectionFactory); // 设置objectMapper:转换java对象的时候使用 ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_ARRAY); Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(objectMapper, Object.class); StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); // 设置key/value值的序列化方式 template.setKeySerializer(stringRedisSerializer); template.setValueSerializer(jackson2JsonRedisSerializer); template.setHashKeySerializer(stringRedisSerializer); template.setHashValueSerializer(jackson2JsonRedisSerializer); template.afterPropertiesSet(); return template; } }
配置文件properties(转yml同理):
#Redis服务器地址 spring.redis.host=192.168.47.33 #Redis服务器连接端口 spring.redis.port=6379 #Redis数据库索引(默认位0) spring.redis.database=0 #连接超时时间(毫秒) spring.redis.timeout=1800000 #连接池最大连接数(使用负值表示没有限制) spring.redis.lettuce.pool.max-active=20 #最大阻塞等待时间(复数表示没有限制) spring.redis.lettuce.pool.max-wait=-1 #连接池中的最大空闲连接 spring.redis.lettuce.pool.max-idle=5 #连接池中的最小空闲连接 spring.redis.lettuce.pool.min-idle=0
为什么要配置template类?这些又有什么用?starter不是自带了jackson了吗?以下是和CHATGPT-4o的问答:
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; @Configuration public class RedisConfig { @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(redisConnectionFactory); // 使用Jackson2JsonRedisSerializer来序列化和反序列化Redis的value值(默认使用Jackson) Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class); // 使用StringRedisSerializer来序列化和反序列化Redis的key值 StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); // key采用String的序列化方式 template.setKeySerializer(stringRedisSerializer); // hash的key也采用String的序列化方式 template.setHashKeySerializer(stringRedisSerializer); // value序列化方式采用jackson template.setValueSerializer(jackson2JsonRedisSerializer); // hash的value序列化方式采用jackson template.setHashValueSerializer(jackson2JsonRedisSerializer); template.afterPropertiesSet(); return template; } }
总结:
Redis的序列化默认使用的是JDK自带的序列化,序列化会将JAVA对象序列成字节码存储
例子:
配置过后:
那么我该如何使用RedisTemplate呢?
RedisTemplate 是 Spring Data Redis 提供的一个核心类,用于操作 Redis 数据库。它提供了对 Redis 的所有基本数据结构的全面支持,包括字符串、哈希、列表、集合、有序集合等。RedisTemplate 提供了多种 opsForXxx 方法来操作不同的数据类型。
RedisTemplate 的基本结构
RedisTemplate 通过以下几个重要的 opsForXxx 方法,提供对不同 Redis 数据结构的操作:
opsForValue() - 操作字符串(String)
- opsForHash() - 操作哈希(Hash)
- opsForList() - 操作列表(List)
- opsForSet() - 操作集合(Set)
- opsForZSet() - 操作有序集合(Sorted Set)
1. opsForValue() - 操作字符串(String)
opsForValue() 返回一个 ValueOperations 对象,用于操作 Redis 的字符串类型数据。
常用方法:
- set(String key, V value):设置指定键的值。
- get(String key):获取指定键的值。
- set(String key, V value, long timeout, TimeUnit unit):设置值并指定过期时间。
- increment(String key, long delta):将键对应的数值增加指定的增量。
- decrement(String key, long delta):将键对应的数值减少指定的减量。
- setIfAbsent(String key, V value):如果键不存在则设置值。
- getAndSet(String key, V value):设置键的值,并返回旧值。
- setBit(String key, long offset, boolean value):设置指定偏移量的二进制位。
- getBit(String key, long offset):获取指定偏移量的二进制位。
2. opsForHash() - 操作哈希(Hash)
opsForHash() 返回一个 HashOperations 对象,用于操作 Redis 的哈希类型数据。
常用方法:
- put(H key, HK hashKey, HV value):向哈希表中添加键值对。
- putAll(H key, Map<? extends HK, ? extends HV> m):向哈希表中添加多个键值对。
- get(H key, HK hashKey):获取哈希表中指定字段的值。
- delete(H key, Object... hashKeys):删除一个或多个哈希字段。
- hasKey(H key, Object hashKey):检查哈希表中是否存在指定的字段。
- increment(H key, HK hashKey, double delta):将哈希表中的指定字段值加上给定增量。
- keys(H key):获取哈希表中的所有字段名。
- values(H key):获取哈希表中的所有值。
- entries(H key):获取哈希表中的所有键值对。
3. opsForList() - 操作列表(List)
opsForList() 返回一个 ListOperations 对象,用于操作 Redis 的列表类型数据。
常用方法:
- leftPush(K key, V value):将值推入列表左端。
- rightPush(K key, V value):将值推入列表右端。
- leftPop(K key):从左端弹出并返回列表中的第一个元素。
- rightPop(K key):从右端弹出并返回列表中的最后一个元素。
- range(K key, long start, long end):获取列表中指定范围的元素。
- size(K key):获取列表长度。
- remove(K key, long count, Object value):从列表中删除值为 value 的元素,删除 count 次。
4. opsForSet() - 操作集合(Set)
opsForSet() 返回一个 SetOperations 对象,用于操作 Redis 的集合类型数据。
常用方法:
- add(K key, V... values):向集合中添加一个或多个元素。
- remove(K key, Object... values):从集合中移除一个或多个元素。
- isMember(K key, Object o):检查集合中是否包含指定元素。
- members(K key):获取集合中的所有元素。
- size(K key):获取集合的大小。
- pop(K key):随机移除并返回集合中的一个元素。
- intersect(K key, Collection
otherKeys):获取当前集合与其他集合的交集。 - union(K key, Collection
otherKeys):获取当前集合与其他集合的并集。
5. opsForZSet() - 操作有序集合(Sorted Set)
opsForZSet() 返回一个 ZSetOperations 对象,用于操作 Redis 的有序集合类型数据。
- add(K key, V value, double score):向有序集合中添加元素,并设置分数。
- remove(K key, Object... values):从有序集合中移除一个或多个元素。
- incrementScore(K key, V value, double delta):增加指定元素的分数。
- range(K key, long start, long end):获取指定范围内的元素(按分数排序)。
- rangeByScore(K key, double min, double max):获取分数在指定范围内的元素。
- score(K key, Object o):获取指定元素的分数。
- rank(K key, Object o):获取指定元素的排名(从低到高)。
- reverseRank(K key, Object o):获取指定元素的排名(从高到低)。
其他有用的 API
除了 opsForXxx 系列操作外,RedisTemplate 还提供了一些其他的有用方法:
- execute(RedisCallback
action):执行 Redis 操作的回调。 - boundValueOps(K key):返回一个绑定到指定键的 ValueOperations 操作。
- boundHashOps(K key):返回一个绑定到指定键的 HashOperations 操作。
- boundListOps(K key):返回一个绑定到指定键的 ListOperations 操作。
- boundSetOps(K key):返回一个绑定到指定键的 SetOperations 操作。
- boundZSetOps(K key):返回一个绑定到指定键的 ZSetOperations 操作。
- expire(K key, long timeout, TimeUnit unit):设置键的过期时间。
- persist(K key):移除键的过期时间,使其持久化。
- delete(K key):删除指定的键。
本文作者:MingHaiZ
本文链接:https://www.cnblogs.com/MingHaiZ/p/18414494
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步