在Spring Boot微服务使用HashOperations操作Redis Hash哈希散列
记录:403
场景:在Spring Boot微服务使用RedisTemplate的HashOperations操作Redis Hash哈希散列。
版本:JDK 1.8,Spring Boot 2.6.3,redis-6.2.5
1.微服务中Redis配置信息
1.1在application.yml中Redis配置信息
spring:redis:host: 192.168.19.203port: 28001password: 12345678timeout: 50000
1.2加载简要逻辑
Spring Boot微服务在启动时,自动注解机制会读取application.yml的注入到RedisProperties对象。在Spring环境中就能取到Redis相关配置信息了。
类全称:org.springframework.boot.autoconfigure.data.redis.RedisProperties
1.3在pom.xml添加依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2.配置RedisTemplate
2.1配置RedisTemplate
@Configuration
public class RedisConfig {@Bean("redisTemplate")public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {// 1.创建RedisTemplate对象RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();// 2.加载Redis配置redisTemplate.setConnectionFactory(lettuceConnectionFactory);// 3.配置key序列化RedisSerializer<?> stringRedisSerializer = new StringRedisSerializer();redisTemplate.setKeySerializer(stringRedisSerializer);redisTemplate.setHashKeySerializer(stringRedisSerializer);// 4.配置Value序列化Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);ObjectMapper objMapper = new ObjectMapper();objMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);objMapper.activateDefaultTyping(objMapper.getPolymorphicTypeValidator(), ObjectMapper.DefaultTyping.NON_FINAL);jackson2JsonRedisSerializer.setObjectMapper(objMapper);redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);// 5.初始化RedisTemplateredisTemplate.afterPropertiesSet();return redisTemplate;}@Beanpublic HashOperations<String, Object, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) {return redisTemplate.opsForHash();}
}
2.2解析
在配置RedisTemplate后,在Spring环境中,可以@Autowired自动注入方式注入操作Redis对象。比如:RedisTemplate、HashOperations。
3.使用HashOperations操作Redis Hash哈希散列
3.1简要说明
使用HashOperations操作Redis Hash哈希散列,常用操作:增、查、改、删、设置超时等。
3.2操作示例
@RestController
@RequestMapping("/hub/example/load")
@Slf4j
public class LoadController {@Autowiredprivate RedisTemplate redisTemplate;@Autowiredprivate HashOperations hashOperations;/*** 操作Hash,使用HashOperations* 对应写命令: HMSET* 对应读命令: HGETALL* 本质就是在一个key对应存储了一个Map*/@GetMapping("/hashOperations")public Object loadData04() {log.info("HashOperations操作开始...");// 1.增hashOperations.put("CityInfo:Hangzhou04", "hangzhou", "杭州");hashOperations.put("CityInfo:Hangzhou04", "suzhou", "苏州");// 2.1查-获取map键值对数据Map resultMap = hashOperations.entries("CityInfo:Hangzhou04");resultMap.forEach((key, value) -> {System.out.println("key=" + key + ",value=" + value);});// 2.2查-获取Map的全部keySet set = hashOperations.keys("CityInfo:Hangzhou04");set.forEach((key) -> {System.out.println("key=" + key);});// 2.3查-获取Map的全部valueList list = hashOperations.values("CityInfo:Hangzhou04");list.forEach((value) -> {System.out.println("value=" + value);});// 3.改hashOperations.put("CityInfo:Hangzhou04", "hangzhou", "杭州-西湖");// 4.1删,(删除指定值)hashOperations.delete("CityInfo:Hangzhou04", "hangzhou", "suzhou");// 4.2删,(删除全部)redisTemplate.delete("CityInfo:Hangzhou04");// 5.设置超时hashOperations.put("CityInfo:Hangzhou04", "hangzhou", "杭州");redisTemplate.boundValueOps("CityInfo:Hangzhou04").expire(5, TimeUnit.MINUTES);redisTemplate.expire("CityInfo:Hangzhou04", 10, TimeUnit.MINUTES);// 6.查询Hash的元素个数Long size =hashOperations.size("CityInfo:Hangzhou04");System.out.println("查询Hash的元素个数,size="+size);log.info("HashOperations操作结束...");return "执行成功";}
}
3.3测试验证
使用Postman测试。
请求RUL:http://127.0.0.1:18205/hub-205-redis/hub/example/load/hashOperations
4.HashOperations接口
4.1接口
HashOperations 是一个接口,默认实现类是DefaultHashOperations。
接口:org.springframework.data.redis.core.HashOperations。
实现类:org.springframework.data.redis.core.DefaultHashOperations。
4.2接口源码
在源码中,查看接口具体方法,可以快速了解该接口具备功能,以便在生产中能根据实际场景对号入座找到合适方法解决实际问题。
public interface HashOperations<H, HK, HV> {Long delete(H key, Object... hashKeys);Boolean hasKey(H key, Object hashKey);@NullableHV get(H key, Object hashKey);List<HV> multiGet(H key, Collection<HK> hashKeys);Long increment(H key, HK hashKey, long delta);Double increment(H key, HK hashKey, double delta);@NullableHK randomKey(H key);@NullableEntry<HK, HV> randomEntry(H key);@NullableList<HK> randomKeys(H key, long count);@NullableMap<HK, HV> randomEntries(H key, long count);Set<HK> keys(H key);@NullableLong lengthOfValue(H key, HK hashKey);Long size(H key);void putAll(H key, Map<? extends HK, ? extends HV> m);void put(H key, HK hashKey, HV value);Boolean putIfAbsent(H key, HK hashKey, HV value);List<HV> values(H key);Map<HK, HV> entries(H key);Cursor<Entry<HK, HV>> scan(H key, ScanOptions options);RedisOperations<H, ?> getOperations();
}
以上,感谢。
2023年4月12日