> 文章列表 > 在Spring Boot微服务使用SetOperations操作Redis Set集合(无序集合)

在Spring Boot微服务使用SetOperations操作Redis Set集合(无序集合)

在Spring Boot微服务使用SetOperations操作Redis Set集合(无序集合)

记录:404

场景:在Spring Boot微服务使用RedisTemplate的SetOperations操作Redis Set集合(无序集合)。

版本: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 SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) {return redisTemplate.opsForSet();}
}

2.2解析

在配置RedisTemplate后,在Spring环境中,可以@Autowired自动注入方式注入操作Redis对象。比如:RedisTemplate、SetOperations。

3.使用SetOperations操作Redis Set集合(无序集合)

3.1简要说明

使用SetOperations操作Redis Set集合(无序集合),常用操作:增、查、删、设置超时等。

3.2操作示例

@RestController
@RequestMapping("/hub/example/load")
@Slf4j
public class LoadController {@Autowiredprivate RedisTemplate redisTemplate;@Autowiredprivate SetOperations setOperations;/*** 操作ZSet,使用ZSetOperations,有序排列且无重复数据* 对应写命令: ZADD* 对应读命令: SPOP*/@GetMapping("/zSetOperations")public Object loadData06() {log.info("ZSetOperations操作开始...");// 1.增zSetOperations.add("CityInfo:Hangzhou06", "杭州", 20);zSetOperations.add("CityInfo:Hangzhou06", "苏州", 10);zSetOperations.add("CityInfo:Hangzhou06", "上海", 30);zSetOperations.add("CityInfo:Hangzhou06", "北京", 101);zSetOperations.add("CityInfo:Hangzhou06", "宁波", 999);// 2.1查(通过下标查值,从0开始取第一个值)Set set = zSetOperations.range("CityInfo:Hangzhou06", 1, 4);set.forEach((value) -> {System.out.println("value=" + value);});// 2.2查(通过Score查值)set = zSetOperations.rangeByScore("CityInfo:Hangzhou06", 29, 60);set.forEach((value) -> {System.out.println("value=" + value);});// 3.改zSetOperations.add("CityInfo:Hangzhou06", "杭州", 99);// 4.1取(取出Score最大的值,取出后队列中值会删除)ZSetOperations.TypedTuple obj1 = zSetOperations.popMax("CityInfo:Hangzhou06");System.out.println("取出最大值,value=" + obj1.getValue() + ",Score=" + obj1.getScore());// 4.2取(取出Score最小的值,取出后队列中值会删除)ZSetOperations.TypedTuple obj2 = zSetOperations.popMin("CityInfo:Hangzhou06");System.out.println("取出最小值,value=" + obj2.getValue() + ",Score=" + obj2.getScore());// 5.1删除指定值zSetOperations.remove("CityInfo:Hangzhou06", "上海");// 5.2按照Score分数大小删除zSetOperations.removeRangeByScore("CityInfo:Hangzhou06", 1, 100);// 5.3删(删除全部)redisTemplate.delete("CityInfo:Hangzhou06");// 6.设置超时zSetOperations.add("CityInfo:Hangzhou06", "杭州", 21);zSetOperations.add("CityInfo:Hangzhou06", "苏州", 11);redisTemplate.boundValueOps("CityInfo:Hangzhou06").expire(5, TimeUnit.MINUTES);redisTemplate.expire("CityInfo:Hangzhou06", 10, TimeUnit.MINUTES);// 7.查询ZSet的元素个数Long size =zSetOperations.size("CityInfo:Hangzhou06");System.out.println("查询ZSet的元素个数,size="+size);log.info("ZSetOperations操作结束...");return "执行成功";}
}

3.3测试验证

使用Postman测试。

请求RUL:http://127.0.0.1:18205/hub-205-redis/hub/example/load/setOperations

4.SetOperations接口

4.1接口

SetOperations是一个接口,默认实现类是DefaultSetOperations。

接口:org.springframework.data.redis.core.SetOperations。

实现类:org.springframework.data.redis.core.DefaultSetOperations。

4.2接口源码

在源码中,查看接口具体方法,可以快速了解该接口具备功能,以便在生产中能根据实际场景对号入座找到合适方法解决实际问题。

public interface SetOperations<K, V> {@NullableLong add(K key, V... values);@NullableLong remove(K key, Object... values);@NullableV pop(K key);@NullableList<V> pop(K key, long count);@NullableBoolean move(K key, V value, K destKey);@NullableLong size(K key);@NullableBoolean isMember(K key, Object o);@NullableMap<Object, Boolean> isMember(K key, Object... objects);@NullableSet<V> intersect(K key, K otherKey);@NullableSet<V> intersect(K key, Collection<K> otherKeys);@NullableSet<V> intersect(Collection<K> keys);@NullableLong intersectAndStore(K key, K otherKey, K destKey);@NullableLong intersectAndStore(K key, Collection<K> otherKeys, K destKey);@NullableLong intersectAndStore(Collection<K> keys, K destKey);@NullableSet<V> union(K key, K otherKey);@NullableSet<V> union(K key, Collection<K> otherKeys);@NullableSet<V> union(Collection<K> keys);@NullableLong unionAndStore(K key, K otherKey, K destKey);@NullableLong unionAndStore(K key, Collection<K> otherKeys, K destKey);@NullableLong unionAndStore(Collection<K> keys, K destKey);@NullableSet<V> difference(K key, K otherKey);@NullableSet<V> difference(K key, Collection<K> otherKeys);@NullableSet<V> difference(Collection<K> keys);@NullableLong differenceAndStore(K key, K otherKey, K destKey);@NullableLong differenceAndStore(K key, Collection<K> otherKeys, K destKey);@NullableLong differenceAndStore(Collection<K> keys, K destKey);@NullableSet<V> members(K key);V randomMember(K key);@NullableSet<V> distinctRandomMembers(K key, long count);@NullableList<V> randomMembers(K key, long count);Cursor<V> scan(K key, ScanOptions options);RedisOperations<K, V> getOperations();
}

以上,感谢。

2023年4月12日