RedisTemplate操作命令-Hash

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

RedisTemplate操作命令-Hash
Hash操作
* 看别⼈的总没有⾃⼰实操来的印象深刻
redis的五⼤数据类型字符串、列表、集合、有序集合、哈希
redis的哈希类型指的是键值本⾝⼜是⼀个键值对结构:
如:vaule = {{key1,value1},{key2,value2}...{keyn,valuen}}
相对于java可以理解为map:Key=>(Map<HK,HV>)
哈希类型的内部编码有两种:
ziplist(压缩列表):当哈希类型元素个数⼩于hash-max-ziplist-entries配置(默认512个)、同时所有值都⼩于hash-max-ziplist-value配置(默认64字节)时,Redis会使⽤ziplist作为哈希的内部实现,ziplist使⽤更加紧凑的结构实现多个元素的连续存储,所以在节省内存⽅⾯⽐hashtable更加优秀。

hashtable(哈希表):当哈希类型⽆法满⾜ziplist的条件时,Redis会使⽤hashtable作为哈希的内部实现,因为此时ziplist的读写效率会下降,⽽hashtable的读写时间复杂度为O(1)。

在redis开发与运维中的图解:
redis对哈希的命令在redisTemplate中都有映射,见下⽅表:
redisTemplate
//以下表格使⽤hash代替redisTemplate.opsForHash() :
HashOperations hash = redisTemplate.opsForHash();
命令操作返回值
hash.delete(H key, Object... hashKeys)删除,可以传⼊多个map 的key 【hdel 】Long hash.hasKey(key, hashKey)
查看hash 中的某个hashKey 是否存在
【hexists 】Boolean
hash.get(key, hashKey)
获取值【hget 】
Object (HV 泛型约束对象)hash.multiGet(H key, Collection<HK>hashKeys)
批量获取集合中的key 对应的值【hmget 】List<HV>hash.increment(H key, HK hashKey,long delta)
对值进⾏+(delta 值)操作【】Long hash.increment(H key, HK hashKey,double delta)~
double hash.keys(key)
返回map 内hashKey 的集合【hkeys 】Set<HK>hash.lengthOfValue(H key, HK hashKey)返回查询键关联的值的长度,为null 则返回0【hstrlen 】
Long hash.size(H key)
获取hashKey 的个数【hlen 】
Long hash.putAll(H key, Map<? extends HK,
extends HV> m)
相当于map 的putAll 【hmset 】
void
hash.put(H key, HK hashKey, HV value)
设置值,添加hashKey-value ,hashKay 相当
于map 的key 【hset 】void
hash.putIfAbsent(H key, HK hashKey,HV value)仅当hashKey 不存在时设置值Boolean hash.values(key)返回value 的集合【hvals 】List<HV>hase.entries(H key)
获取map 【hgetall 】
Map<HK, HV>
hash.scan(H key, ScanOptions options)基于游标的迭代查询【hscan 】Cursor<Map.Entry<HK, HV>>(返回的Cursor 要⼿动关闭,见下⾯⽰例2)hash.getOperations()返回RedisOperation ,它就是redis 操作的接⼝
RedisOperations<H, ?>
命令
操作返回值
对于命令的时间复杂度见下表:
⽰例测试操作1:
//key
String k = "phoneMap"; //map 的key
String hashKey = "138********";
Map<String, String> phoneMap = new HashMap<>(); phoneMap.put("138********","1"); phoneMap.put(hashKey,"2");
//添加map
//redisTemplate.opsForHash().putAll(k, phoneMap);
//在key的value中添加单个hash值
redisTemplate.opsForHash().put(k, "19199999999","2");
//获取map
Map m1 = redisTemplate.opsForHash().entries(k);
Object o = redisTemplate.opsForHash().get(k, hashKey);
("get key:{}", o);
("map:{}", m1);
log打印的结果:
2019-12-13 15:45:36.836 INFO 4156 --- [ main] : get key:null
2019-12-13 15:45:36.836 INFO 4156 --- [ main] : map:{138********=1, 138********=2, 19199999999=2}
如果这⾥使⽤了redisTemplate.opsForHash().putAll(k, phoneMap); ,则get key打印的结果就是2。

这⾥打印的map是包含之前测试的值。

⽰例测试操作2:
@Test
public void hashTest(){
String k = "phoneMap";
String hashKey = "19199999999";
HashOperations<String, String, String> hash = redisTemplate.opsForHash();
hash.increment(k,hashKey,1);
("19199999999:{}", hash.get(k,hashKey));
Set set = hash.keys(k);
("phoneMap:{}", set);
Long sizeLong = hash.size(k);
("sizeLong:{}",sizeLong);
Cursor<Map.Entry<String, String>> cursor = hash.scan(k,ScanOptions.scanOptions().count(1000).build());
while (cursor.hasNext()){
Map.Entry<String, String> entry = cursor.next();
("entry:{}:{}", entry.getKey(), entry.getValue());
}
try {
if (!cursor.isClosed()){
cursor.close();
}
} catch (IOException e) {
log.error("关闭cursor异常");
e.printStackTrace();
}
}
打印结果:
2019-12-13 16:59:35.573 INFO 1540 --- [ main] : 19199999999:6
2019-12-13 16:59:35.577 INFO 1540 --- [ main] : phoneMap:[138********, 138********, 19199999999, 138********, 138********]
2019-12-13 16:59:35.578 INFO 1540 --- [ main] : sizeLong:5
2019-12-13 16:59:35.587 INFO 1540 --- [ main] : entry:138********:1
2019-12-13 16:59:35.587 INFO 1540 --- [ main] : entry:138********:2
2019-12-13 16:59:35.587 INFO 1540 --- [ main] : entry:19199999999:6
2019-12-13 16:59:35.587 INFO 1540 --- [ main] : entry:138********:1
2019-12-13 16:59:35.587 INFO 1540 --- [ main] : entry:138********:2
# 使⽤⽂件形式展⽰:
private final String REDIS_PHONE_CONUM_PREFIX_KEY = "phoneSms:Check";
/**
* 添加⼿机号发送次数
* @param phone
* @return
*/
public void setPhoneSmsCountInc(String phone){
HashOperations hash = redisTemplate.opsForHash();
if (!redisTemplate.hasKey(REDIS_PHONE_CONUM_PREFIX_KEY)){
//设置过期key时间
redisTemplate.expire(REDIS_PHONE_CONUM_PREFIX_KEY, 24 * 60 * 60, TimeUnit.SECONDS); }
hash.increment(REDIS_PHONE_CONUM_PREFIX_KEY, phone,1);
}
这是HashOperations的源码:
/*
* Copyright 2011-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https:///licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.redis.core;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import ng.Nullable;
/**
* Redis map specific operations working on a hash.
*
* @author Costin Leau
* @author Christoph Strobl
* @author Ninad Divadkar
*/
public interface HashOperations<H, HK, HV> {
/**
* Delete given hash {@code hashKeys}.
*
* @param key must not be {@literal null}.
* @param hashKeys must not be {@literal null}.
* @return {@literal null} when used in pipeline / transaction.
*/
Long delete(H key, Object... hashKeys);
/**
* Determine if given hash {@code hashKey} exists.
*
* @param key must not be {@literal null}.
* @param hashKey must not be {@literal null}.
* @return {@literal null} when used in pipeline / transaction.
*/
Boolean hasKey(H key, Object hashKey);
/**
* Get value for given {@code hashKey} from hash at {@code key}.
*
* @param key must not be {@literal null}.
* @param hashKey must not be {@literal null}.
* @return {@literal null} when key or hashKey does not exist or used in pipeline / transaction.
*/
@Nullable
HV get(H key, Object hashKey);
/**
* Get values for given {@code hashKeys} from hash at {@code key}.
*
* @param key must not be {@literal null}.
* @param hashKeys must not be {@literal null}.
* @return {@literal null} when used in pipeline / transaction.
*/
List<HV> multiGet(H key, Collection<HK> hashKeys);
/**
* Increment {@code value} of a hash {@code hashKey} by the given {@code delta}.
*
* @param key must not be {@literal null}.
* @param hashKey must not be {@literal null}.
* @param delta
* @return {@literal null} when used in pipeline / transaction.
*/
Long increment(H key, HK hashKey, long delta);
/**
* Increment {@code value} of a hash {@code hashKey} by the given {@code delta}.
*
* @param key must not be {@literal null}.
* @param hashKey must not be {@literal null}.
* @param delta
* @return {@literal null} when used in pipeline / transaction.
*/
Double increment(H key, HK hashKey, double delta);
/**
* Get key set (fields) of hash at {@code key}.
*
* @param key must not be {@literal null}.
* @return {@literal null} when used in pipeline / transaction.
*/
Set<HK> keys(H key);
/**
* Returns the length of the value associated with {@code hashKey}. If either the {@code key} or the {@code hashKey} * do not exist, {@code 0} is returned.
*
* @param key must not be {@literal null}.
* @param hashKey must not be {@literal null}.
* @return {@literal null} when used in pipeline / transaction.
* @since 2.1
*/
@Nullable
Long lengthOfValue(H key, HK hashKey);
/**
* Get size of hash at {@code key}.
*
* @param key must not be {@literal null}.
* @return {@literal null} when used in pipeline / transaction.
*/
Long size(H key);
/**
* Set multiple hash fields to multiple values using data provided in {@code m}.
*
* @param key must not be {@literal null}.
* @param m must not be {@literal null}.
*/
void putAll(H key, Map<? extends HK, ? extends HV> m);
/**
* Set the {@code value} of a hash {@code hashKey}.
*
* @param key must not be {@literal null}.
* @param hashKey must not be {@literal null}.
* @param value
*/
void put(H key, HK hashKey, HV value);
/**
* Set the {@code value} of a hash {@code hashKey} only if {@code hashKey} does not exist.
*
* @param key must not be {@literal null}.
* @param hashKey must not be {@literal null}.
* @param value
* @return {@literal null} when used in pipeline / transaction.
*/
Boolean putIfAbsent(H key, HK hashKey, HV value);
/**
* Get entry set (values) of hash at {@code key}.
*
* @param key must not be {@literal null}.
* @return {@literal null} when used in pipeline / transaction.
*/
List<HV> values(H key);
/**
* Get entire hash stored at {@code key}.
*
* @param key must not be {@literal null}.
* @return {@literal null} when used in pipeline / transaction.
*/
Map<HK, HV> entries(H key);
/**
* Use a {@link Cursor} to iterate over entries in hash at {@code key}. <br />
* <strong>Important:</strong> Call {@link Cursor#close()} when done to avoid resource leak. *
* @param key must not be {@literal null}.
* @param options
* @return {@literal null} when used in pipeline / transaction.
* @since 1.4
*/
Cursor<Map.Entry<HK, HV>> scan(H key, ScanOptions options);
/**
* @return never {@literal null}.
*/
RedisOperations<H, ?> getOperations();
}
View Code。

相关文档
最新文档