当前位置:网站首页>Redistemplate operates redis. This article is enough (I) [easy to understand]
Redistemplate operates redis. This article is enough (I) [easy to understand]
2022-06-25 01:55:00 【Full stack programmer webmaster】
Hello everyone , I meet you again , I'm your friend, Quan Jun .
RedisTemplate operation Redis, This article is enough ( One )StringRedisTemplate and RedisTemplate The difference between ( Two )StringRedisTemplate A small case of ( 3、 ... and )
List of articles - One 、SpringDataRedis brief introduction
- Two 、RedisTemplate in API Use
- 5、Hash Type dependent operations
- 1)、 Add cache (2/3 yes 1 The progressive value of )
- 2)、 Set expiration time ( Set separately )
- 3)、 Add one Map aggregate
- 4)、 Set expiration time ( Set separately )
- 5)、 Extract all the small key
- 6)、 Extract all of value value
- 7)、 according to key extract value value
- 8)、 Get a collection of all key value pairs
- 9)、 Delete
- 10)、 Judge Hash Whether the value is contained in the
- 1)、 Add cache (2/3 yes 1 The progressive value of )
- 2)、 Set expiration time ( Set separately )
- 3)、 Add one Map aggregate
- 4)、 Set expiration time ( Set separately )
- 5)、 Extract all the small key
- 6)、 Extract all of value value
- 7)、 according to key extract value value
- 8)、 Get a collection of all key value pairs
- 9)、 Delete
- 10)、 Judge Hash Whether the value is contained in the
- 6、Set Type dependent operations
- 1)、 add to Set cache ( Value can be a , It's also multiple )(2/3 yes 1 The progressive value of )
- 2)、 Set expiration time ( Set separately )
- 3)、 according to key obtain Set All the values in
- 4)、 according to value From a set Query in , Whether there is
- 5)、 obtain Set The length of the cache
- 6)、 Remove the specified element
- 7)、 Remove specified key
- 7、 LIST Type dependent operations
- 1)、 Add cache (2/3 yes 1 The progressive value of )
- 2)、 take List Put into cache
- 3)、 Set expiration time ( Set separately )
- 4)、 obtain List Cache everything ( Starting index , End index )
- 5)、 Pop up an element from left or right
- 6)、 Query elements by index
- 7)、 obtain List The length of the cache
- 8)、 Modify according to the index List A piece of data in (key, Indexes , value )
- 9)、 remove N The values are value(key, Number of removed , value )
- 8、Zset Type related operations
- 1)、 Insert element into collection , And set the score
- 2)、 Insert multiple elements into the collection , And set the score
- 3)、 In order of rank ( From small to large ) Print the elements in the specified interval , -1 To print all
- 4)、 Get the score of the specified element
- 5)、 Returns the number of members in the collection
- 6)、 Returns the number of members in the specified score range in the collection (Double type )
- 7)、 Returns the ranking of the elements in the collection within the specified score range ( From small to large )
- 8)、 With offset and number ,(key, Starting score , Maximum score , Offset , Number )
- 9)、 Returns the ranking of the elements in the collection , And scores ( From small to large )
- 10)、 Returns the ranking of a specified member
- 11)、 Deletes the specified element from the collection
- 12)、 Delete the element of the specified index range (Long type )
- 13)、 Delete elements in the specified score range (Double type )
- 14)、 Add points to the specified elements (Double type )
One 、SpringDataRedis brief introduction
1、Redis
redis It's an open source Key-Value database , Running in memory , from C Language writing . Enterprise development usually uses Redis To implement caching . There are also similar products memcache 、memcached etc. .
2、Jedis
Jedis yes Redis An official product for Java The client of , Many interfaces are provided for Java Language call . Can be in Redis Download from the official website , Of course, there are some clients provided by open source enthusiasts , Such as Jredis、SRP wait , Recommended Jedis.
3、Spring Data Redis
Spring-data-redis yes spring Part of a large family , Provided in srping Access through simple configuration in the application redis service , Yes reids Underlying development package (Jedis, JRedis, and RJC) It's highly encapsulated ,RedisTemplate Provides redis Various operations 、 Exception handling and serialization , Support publish subscription , Also on spring 3.1 cache Implemented . spring-data-redis in the light of jedis The following functions are provided :
- Connection pool automatic management , Provides a highly encapsulated “RedisTemplate” class
- in the light of jedis There are a lot of api It is classified and packaged , Encapsulate the same type of operation as operation Interface
- ValueOperations: Simple K-V operation
- SetOperations:set Type data operation
- ZSetOperations:zset Type data operation
- HashOperations: in the light of map Type of data operation
- ListOperations: in the light of list Type of data operation
- Provide for the right to key Of “bound”( binding ) Convenient operation API, Can pass bound Encapsulate the specified key, And then do a series of operations without “ Explicit ” Re designation of Key, namely BoundKeyOperations:
- BoundValueOperations
- BoundSetOperations
- BoundListOperations
- BoundSetOperations
- BoundHashOperations
- Encapsulate transaction operations , There's container control .
- For data “ serialize / Deserialization ”, Provides a variety of alternative strategies (RedisSerializer)
JdkSerializationRedisSerializer:POJO Object access scenarios , Use JDK The serialization mechanism itself , take pojo Class passing ObjectInputStream/ObjectOutputStream Do serialization , Final redis-server A sequence of bytes will be stored . Is currently the most commonly used serialization strategy .
StringRedisSerializer:Key perhaps value For string scenarios , According to the designation charset Encode the byte sequence of data into string, yes “new String(bytes, charset)” and “string.getBytes(charset)” The direct packaging of . It's the lightest and most efficient strategy .
JacksonJsonRedisSerializer:jackson-json The tool provides javabean And json The ability to transform between , Can be pojo Examples are sequenced into json The format is stored in redis in , Can also be json Format data into pojo example . because jackson When the tool serializes and deserializes , You need to specify Class type , So this strategy is a little more complex to encapsulate .【 need jackson-mapper-asl Tool support 】
Two 、RedisTemplate in API Use
1、pom.xml rely on
<!--Redis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>2、 The configuration file
# Redis Server connection port
spring.redis.port=6379
# Redis Server address
spring.redis.host=127.0.0.1
# Redis Database index ( The default is 0)
spring.redis.database=0
# Redis Server connection password ( The default is empty. )
spring.redis.password=
# Maximum number of connections in connection pool ( Use a negative value to indicate that there is no limit )
spring.redis.jedis.pool.max-active=8
# Connection pool maximum blocking wait time ( Use a negative value to indicate that there is no limit )
spring.redis.jedis.pool.max-wait=-1ms
# The maximum free connection in the connection pool
spring.redis.jedis.pool.max-idle=8
# The smallest free connection in the connection pool
spring.redis.jedis.pool.min-idle=0
# Connection timeout ( millisecond )
spring.redis.timeout=5000ms3、RedisTemplate The direct method of
use first @Autowired Inject RedisTemplate( Use directly behind , No special instructions )
@Autowired
private RedisTemplate redisTemplate;1、 Removing a single key
// Delete key
public void delete(String key){
redisTemplate.delete(key);
}2、 To delete multiple key
// To delete multiple key
public void deleteKey (String ...keys){
redisTemplate.delete(keys);
}3、 Appoint key The expiration time of
// Appoint key The expiration time of
public void expire(String key,long time){
redisTemplate.expire(key,time,TimeUnit.MINUTES);
}4、 according to key Get expiration time
// according to key Get expiration time
public long getExpire(String key){
Long expire = redisTemplate.getExpire(key);
return expire;
}5、 Judge key Whether there is
// Judge key Whether there is
public boolean hasKey(String key){
return redisTemplate.hasKey(key);
}4、String Type dependent operations
1)、 Add cache (2/3 yes 1 The progressive value of )
//1、 adopt redisTemplate Set the value
redisTemplate.boundValueOps("StringKey").set("StringValue");
redisTemplate.boundValueOps("StringKey").set("StringValue",1, TimeUnit.MINUTES);
//2、 adopt BoundValueOperations Set the value
BoundValueOperations stringKey = redisTemplate.boundValueOps("StringKey");
stringKey.set("StringVaule");
stringKey.set("StringValue",1, TimeUnit.MINUTES);
//3、 adopt ValueOperations Set the value
ValueOperations ops = redisTemplate.opsForValue();
ops.set("StringKey", "StringVaule");
ops.set("StringValue","StringVaule",1, TimeUnit.MINUTES);2)、 Set expiration time ( Set separately )
redisTemplate.boundValueOps("StringKey").expire(1,TimeUnit.MINUTES);
redisTemplate.expire("StringKey",1,TimeUnit.MINUTES);3)、 Get cache value (2/3 yes 1 The progressive value of )
//1、 adopt redisTemplate Set the value
String str1 = (String) redisTemplate.boundValueOps("StringKey").get();
//2、 adopt BoundValueOperations Get value
BoundValueOperations stringKey = redisTemplate.boundValueOps("StringKey");
String str2 = (String) stringKey.get();
//3、 adopt ValueOperations Get value
ValueOperations ops = redisTemplate.opsForValue();
String str3 = (String) ops.get("StringKey");4)、 Delete key
Boolean result = redisTemplate.delete("StringKey");5)、 The order is increasing
redisTemplate.boundValueOps("StringKey").increment(3L);6)、 Decreasing in order
redisTemplate.boundValueOps("StringKey").increment(-3L);5、Hash Type dependent operations
1)、 Add cache (2/3 yes 1 The progressive value of )
//1、 adopt redisTemplate Set the value
redisTemplate.boundHashOps("HashKey").put("SmallKey", "HashVaue");
//2、 adopt BoundValueOperations Set the value
BoundHashOperations hashKey = redisTemplate.boundHashOps("HashKey");
hashKey.put("SmallKey", "HashVaue");
//3、 adopt ValueOperations Set the value
HashOperations hashOps = redisTemplate.opsForHash();
hashOps.put("HashKey", "SmallKey", "HashVaue");2)、 Set expiration time ( Set separately )
redisTemplate.boundValueOps("HashKey").expire(1,TimeUnit.MINUTES);
redisTemplate.expire("HashKey",1,TimeUnit.MINUTES);3)、 Add one Map aggregate
HashMap<String, String> hashMap = new HashMap<>();
redisTemplate.boundHashOps("HashKey").putAll(hashMap );4)、 Set expiration time ( Set separately )
redisTemplate.boundValueOps("HashKey").expire(1,TimeUnit.MINUTES);
redisTemplate.expire("HashKey",1,TimeUnit.MINUTES);5)、 Extract all the small key
//1、 adopt redisTemplate Get value
Set keys1 = redisTemplate.boundHashOps("HashKey").keys();
//2、 adopt BoundValueOperations Get value
BoundHashOperations hashKey = redisTemplate.boundHashOps("HashKey");
Set keys2 = hashKey.keys();
//3、 adopt ValueOperations Get value
HashOperations hashOps = redisTemplate.opsForHash();
Set keys3 = hashOps.keys("HashKey");6)、 Extract all of value value
//1、 adopt redisTemplate Get value
List values1 = redisTemplate.boundHashOps("HashKey").values();
//2、 adopt BoundValueOperations Get value
BoundHashOperations hashKey = redisTemplate.boundHashOps("HashKey");
List values2 = hashKey.values();
//3、 adopt ValueOperations Get value
HashOperations hashOps = redisTemplate.opsForHash();
List values3 = hashOps.values("HashKey");7)、 according to key extract value value
//1、 adopt redisTemplate obtain
String value1 = (String) redisTemplate.boundHashOps("HashKey").get("SmallKey");
//2、 adopt BoundValueOperations Get value
BoundHashOperations hashKey = redisTemplate.boundHashOps("HashKey");
String value2 = (String) hashKey.get("SmallKey");
//3、 adopt ValueOperations Get value
HashOperations hashOps = redisTemplate.opsForHash();
String value3 = (String) hashOps.get("HashKey", "SmallKey");8)、 Get a collection of all key value pairs
//1、 adopt redisTemplate obtain
Map entries = redisTemplate.boundHashOps("HashKey").entries();
//2、 adopt BoundValueOperations Get value
BoundHashOperations hashKey = redisTemplate.boundHashOps("HashKey");
Map entries1 = hashKey.entries();
//3、 adopt ValueOperations Get value
HashOperations hashOps = redisTemplate.opsForHash();
Map entries2 = hashOps.entries("HashKey");9)、 Delete
// Delete small key
redisTemplate.boundHashOps("HashKey").delete("SmallKey");
// Delete big key
redisTemplate.delete("HashKey");10)、 Judge Hash Whether the value is contained in the
Boolean isEmpty = redisTemplate.boundHashOps("HashKey").hasKey("SmallKey");6、Set Type dependent operations
1)、 add to Set cache ( Value can be a , It's also multiple )(2/3 yes 1 The progressive value of )
//1、 adopt redisTemplate Set the value
redisTemplate.boundSetOps("setKey").add("setValue1", "setValue2", "setValue3");
//2、 adopt BoundValueOperations Set the value
BoundSetOperations setKey = redisTemplate.boundSetOps("setKey");
setKey.add("setValue1", "setValue2", "setValue3");
//3、 adopt ValueOperations Set the value
SetOperations setOps = redisTemplate.opsForSet();
setOps.add("setKey", "SetValue1", "setValue2", "setValue3");2)、 Set expiration time ( Set separately )
redisTemplate.boundValueOps("setKey").expire(1,TimeUnit.MINUTES);
redisTemplate.expire("setKey",1,TimeUnit.MINUTES);3)、 according to key obtain Set All the values in
//1、 adopt redisTemplate Get value
Set set1 = redisTemplate.boundSetOps("setKey").members();
//2、 adopt BoundValueOperations Get value
BoundSetOperations setKey = redisTemplate.boundSetOps("setKey");
Set set2 = setKey.members();
//3、 adopt ValueOperations Get value
SetOperations setOps = redisTemplate.opsForSet();
Set set3 = setOps.members("setKey");4)、 according to value From a set Query in , Whether there is
Boolean isEmpty = redisTemplate.boundSetOps("setKey").isMember("setValue2");5)、 obtain Set The length of the cache
Long size = redisTemplate.boundSetOps("setKey").size();6)、 Remove the specified element
Long result1 = redisTemplate.boundSetOps("setKey").remove("setValue1");7)、 Remove specified key
Boolean result2 = redisTemplate.delete("setKey");7、 LIST Type dependent operations
1)、 Add cache (2/3 yes 1 The progressive value of )
//1、 adopt redisTemplate Set the value
redisTemplate.boundListOps("listKey").leftPush("listLeftValue1");
redisTemplate.boundListOps("listKey").rightPush("listRightValue2");
//2、 adopt BoundValueOperations Set the value
BoundListOperations listKey = redisTemplate.boundListOps("listKey");
listKey.leftPush("listLeftValue3");
listKey.rightPush("listRightValue4");
//3、 adopt ValueOperations Set the value
ListOperations opsList = redisTemplate.opsForList();
opsList.leftPush("listKey", "listLeftValue5");
opsList.rightPush("listKey", "listRightValue6");2)、 take List Put into cache
ArrayList<String> list = new ArrayList<>();
redisTemplate.boundListOps("listKey").rightPushAll(list);
redisTemplate.boundListOps("listKey").leftPushAll(list);3)、 Set expiration time ( Set separately )
redisTemplate.boundValueOps("listKey").expire(1,TimeUnit.MINUTES);
redisTemplate.expire("listKey",1,TimeUnit.MINUTES);4)、 obtain List Cache everything ( Starting index , End index )
List listKey1 = redisTemplate.boundListOps("listKey").range(0, 10); 5)、 Pop up an element from left or right
String listKey2 = (String) redisTemplate.boundListOps("listKey").leftPop(); // Pop up an element from the left
String listKey3 = (String) redisTemplate.boundListOps("listKey").rightPop(); // Pop up an element from the right 6)、 Query elements by index
String listKey4 = (String) redisTemplate.boundListOps("listKey").index(1);7)、 obtain List The length of the cache
Long size = redisTemplate.boundListOps("listKey").size();8)、 Modify according to the index List A piece of data in (key, Indexes , value )
redisTemplate.boundListOps("listKey").set(3L,"listLeftValue3");9)、 remove N The values are value(key, Number of removed , value )
redisTemplate.boundListOps("listKey").remove(3L,"value");8、Zset Type related operations
1)、 Insert element into collection , And set the score
//1、 adopt redisTemplate Set the value
redisTemplate.boundZSetOps("zSetKey").add("zSetVaule", 100D);
//2、 adopt BoundValueOperations Set the value
BoundZSetOperations zSetKey = redisTemplate.boundZSetOps("zSetKey");
zSetKey.add("zSetVaule", 100D);
//3、 adopt ValueOperations Set the value
ZSetOperations zSetOps = redisTemplate.opsForZSet();
zSetOps.add("zSetKey", "zSetVaule", 100D);2)、 Insert multiple elements into the collection , And set the score
DefaultTypedTuple<String> p1 = new DefaultTypedTuple<>("zSetVaule1", 2.1D);
DefaultTypedTuple<String> p2 = new DefaultTypedTuple<>("zSetVaule2", 3.3D);
redisTemplate.boundZSetOps("zSetKey").add(new HashSet<>(Arrays.asList(p1,p2)));3)、 In order of rank ( From small to large ) Print the elements in the specified interval , -1 To print all
Set<String> range = redisTemplate.boundZSetOps("zSetKey").range(0, -1);4)、 Get the score of the specified element
Double score = redisTemplate.boundZSetOps("zSetKey").score("zSetVaule");5)、 Returns the number of members in the collection
Long size = redisTemplate.boundZSetOps("zSetKey").size();6)、 Returns the number of members in the specified score range in the collection (Double type )
Long COUNT = redisTemplate.boundZSetOps("zSetKey").count(0D, 2.2D);7)、 Returns the ranking of the elements in the collection within the specified score range ( From small to large )
Set byScore = redisTemplate.boundZSetOps("zSetKey").rangeByScore(0D, 2.2D);8)、 With offset and number ,(key, Starting score , Maximum score , Offset , Number )
Set<String> ranking2 = redisTemplate.opsForZSet().rangeByScore("zSetKey", 0D, 2.2D 1, 3);9)、 Returns the ranking of the elements in the collection , And scores ( From small to large )
Set<TypedTuple<String>> tuples = redisTemplate.boundZSetOps("zSetKey").rangeWithScores(0L, 3L);
for (TypedTuple<String> tuple : tuples) {
System.out.println(tuple.getValue() + " : " + tuple.getScore());
}ss10)、 Returns the ranking of a specified member
// From small to large
Long startRank = redisTemplate.boundZSetOps("zSetKey").rank("zSetVaule");
// From big to small
Long endRank = redisTemplate.boundZSetOps("zSetKey").reverseRank("zSetVaule");11)、 Deletes the specified element from the collection
redisTemplate.boundZSetOps("zSetKey").remove("zSetVaule");12)、 Delete the element of the specified index range (Long type )
redisTemplate.boundZSetOps("zSetKey").removeRange(0L,3L);13)、 Delete elements in the specified score range (Double type )
redisTemplate.boundZSetOps("zSetKey").removeRangeByScorssse(0D,2.2D);14)、 Add points to the specified elements (Double type )
Double score = redisTemplate.boundZSetOps("zSetKey").incrementScore("zSetVaule",1.1D);Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/151883.html Link to the original text :https://javaforall.cn
边栏推荐
- 弹性蛋白酶中英文说明书
- (CVPR 2020) Learning Object Bounding Boxes for 3D Instance Segmentation on Point Clouds
- Ideas and examples of divide and conquer
- Application session coverage solutions with different ports on the same server
- 实验5 8254定时/计数器应用实验【微机原理】【实验】
- 菊花链(寒假每日一题 39)
- 困牛排序(寒假每日一题 40)
- 结合实操带你吃透Redis持久化
- Reverse ordinal number by merge sort
- Dataease template market officially released
猜你喜欢

Ideas and examples of divide and conquer

TC对象结构和简称

数组中关于sizeof()和strlen

Tianshu night reading notes -- memory paging mechanism

PS5连接OPPO K9电视不支持2160P/4K

明日考试 最后一天如何备考?二造考点攻略全整理

Ps5 connected to oppo K9 TV does not support 2160p/4k

Integration of metersphere open source continuous testing platform and Alibaba cloud cloud cloud efficient Devops

Baidu voice synthesizes voice files and displays them on the website

創新藥二級市場審餅疲勞:三期臨床成功、產品獲批也不管用了
随机推荐
通达信哪个开户更安全,更好点
Preg in PHP_ How to replace variable data
字符串常用方法
Day 04 - file IO
How to prepare for the last day of tomorrow's exam? Complete compilation of the introduction to the second building test site
Redis basic commands and types
Some Modest Advice for Graduate Students - by Stephen C. Stearns, Ph.D.
Matlab rounding
IPC机制
Unity C # e-learning (VI) -- FTP (II)
Basic use of transformers Library
监听 Markdown 文件并热更新 Next.js 页面
Chinese address and English address
After the college entrance examination, the following four situations will inevitably occur:
Combined with practice, you will understand redis persistence
sql 聚合函数对 null 的处理[通俗易懂]
PMP考试“临门一脚”如何踢得漂亮?
第04天-文件IO
"One good programmer is worth five ordinary programmers!"
Is CICC securities reliable? Is it safe to open a securities account?