Redis learning notes

Xiaoweidumpb 2022-05-22 12:16:15 阅读数:995

key The operation of the value
keys * View all of the current key
set key value Set up key Value and value
set username wei
exists key Judge key Whether there is
1 There is 0 non-existent
type key see key What type is it
del key Delete specified key data
return 1
unlink key according to value Select non blocking delete
------ Only will keys from keyspace Delete from metadata , The real deletion will be done asynchronously later .
expire key 10 10 Second : For a given key Set expiration time
ttl key See how many seconds are left to expire ,-1 Never expire ,-2 Indicates that it has expired
Library selection
select Command switch database share 16 Databases
select 1
dbsize Check the... Of the current database key Number
flushdb Empty the current library
flushall Kill all the warehouses
string character string
  • One key Corresponding to one value
  • Binary safe , Can contain any data
  • value At most 512m
set key value Set up key value
get key Inquire about key value
append key value Will be given value Append to the end of the original value , Return length
strlen key Get the length of the value
setnx key value Only in key When it doesn't exist , Set up key value
incr key take key The number of values stored is incremented 1, Operate on numeric values only , If it is empty , The new value added is 1
decr key take key Value stores the number minus 1, Operate on numeric values only , If it is empty , The new value added is 1
incrby/decrby key < step > take key Increase or decrease the number of values stored, such as step size
Add additional string parameters :
mset key value key value.. Set one or more at the same time key-value
mget key key... Get one or more at the same time value
msetnx key value key value.. Set one or more at the same time key-value. If and only if all given key It doesn't exist
// String interception
getrange key < The starting position > < End position > obtain key The values of the start and end positions of
setrange key < The starting position > value take value The value of overwrites the starting position
setex key <> value While setting the key value , Set expiration time
getset key value Replace the old value with the new value
list list

Bottom array plus linked list

 Common commands :
lpush/rpush key value value... Insert one or more values from left or right ( Head and tail )
lpop/rpop key Spit out one or more values from left or right ( Value at key at , It's not worth it , No keys )
rpoplpush key1 key2 from key1 Spit a value on the right side of the list , Insert into key2 Left side
lrange key start stop Get elements by index subscript ( From left to right )
lrange key 0 -1 Get all values
lindex key index Get elements according to index subscript
llen key Get list length
linsert key before/after value newvalue stay value Insert a new value before
lrem key n value Delete from the left n individual value value
lset key index value In the list key Subscript in index Change the value value
set aggregate

Dictionaries , The underlying hash table
Automatic weight removal and disordered

sadd key value value... Put one or more member Add elements to the collection key in , What already exists member Element ignored
smembers key Take all the values of the set
sismember key value Judge the set key Whether the modified value is included
scard key Returns the number of elements in the collection
srem key value value Delete an element in the collection
spop key Randomly take an element from the set
srandmember key n From this collection n It's worth , Will not be removed from the collection
smove < A collection a>< A collection b>value Put a collection a One of the value Move to another collection b
sinter key1 key2 Returns the intersection element of two sets
sunion key1 key2 Returns the union element of two sets
sdiff key1 key2 Returns the difference set element of two sets (key1 yes , we have ,key2 No, )
hash Hash

similar Java Medium Map<String,Object> Store the object , The value of an attribute of an object is often modified

hset key field value to key In the collection filed Key assignment value
hget key1 field aggregate field Take out value
hmset key1 field1 value1 field2 value2 Batch settings hash Value
hexists key1 field Look at the hash table key in , Given domain field Whether there is
hkeys key List the hash All of the collection field
hvals key List the hash All of the collection value
hincrby key field increment Hash table key In the domain field Plus the increment 1 -1
hsetnx key field value Hash table key In the domain field Is set to value, If and only if domain field non-existent

Zset An ordered set without repetition

Bottom hash+ Skip list

zadd key score1 value1 score2 value2 Put one or more member Elements and score Values are added to the order key in
zrange key start stop (withscores) Return to ordered set key, The subscript is start And stop Between the elements , belt withscores, You can return scores and values together to the result set .
zrangebyscore key min max(withscores) Return to ordered set key, all score The value is between min and max Between ( Including equal to min or max) Members of . Members of the ordered set press score The values of are arranged in ascending order
zrevrangebyscore key max min (withscores) ditto , Change to big to small
zincrby key increment value For the elements score Plus the increment
zrem key value Delete... Under this collection , The element that specifies the value
zcount key min max Count the set , The number of elements in the fraction range
zrank key value Returns the rank of the value in the collection , from 0 Start

Redis6 New data types


Bit storage 0/1 Achieve daily active user visits


duplicate removal


Geographic Information A two-dimensional

Provide latitude and longitude settings , Query range , Distance query, etc

 Command parameter :
1. Add location ( Longitude and latitude name )
When the coordinates are outside the specified range , The command will return an error
Added data , Can't add
geoadd key longitude latitude member
for example geoadd china:city 121.47 31.23 shanghai
2. Get the coordinate value of the specified area
geopos key member
for example geopos china:city shanghai
3. Get the linear distance between two positions
geodist key member1 member2 (m km ft mi)
4. Centered on a given latitude and longitude , Find the inner element of a radius
georadius key longitude latitude radius (m km ft mi)
<!-- -->


 // establish Jedis object
Jedis jedis = new Jedis("", 9098);
jedis.auth("123456"); // Set the password
// test
String ping =;

View all key

Jedis jedis = new Jedis("", 6379);
Set<String> keys = jedis.keys("*");
for(String key:keys){

key The test code is as follows

jedis.set("k1", "v1");
jedis.set("k2", "v2");
jedis.set("k3", "v3");
Set<String> keys = jedis.keys("*");
for (String key : keys) {

String Test code

// operation key string
public void demo1() {
// establish Jedis object
Jedis jedis = new Jedis("",6379);
// add to
// obtain
String name = jedis.get("name");
// Set up multiple key-value
List<String> mget = jedis.mget("k1", "k2");
Set<String> keys = jedis.keys("*");
for(String key : keys) {

List Test code

List<String> list = jedis.lrange("mylist",0,-1);
List<String> values = jedis.lrange("key1", 0, -1);
for (String element : list) {

Set Test code

jedis.sadd("orders", "order01");
jedis.sadd("orders", "order02");
jedis.sadd("orders", "order03");
jedis.sadd("orders", "order04");
Set<String> smembers = jedis.smembers("orders");
for (String order : smembers) {
jedis.srem("orders", "order02");
Mobile phone verification code
public class PhoneCode {

public static void main(String[] args) {

// Analog captcha sending 
// Analog verification code verification 
//3 Verification code verification 
public static void getRedisCode(String phone,String code) {

// from redis Get verification code 
Jedis jedis = new Jedis("",6379);
// Verification Code key
String codeKey = "VerifyCode"+phone+":code";
String redisCode = jedis.get(codeKey);
// Judge 
if(redisCode.equals(code)) {

System.out.println(" success ");
}else {

System.out.println(" Failure ");
//2 Each phone can only send three times a day , Verification code in redis in , Set expiration time 120
public static void verifyCode(String phone) {

// Connect redis
Jedis jedis = new Jedis("",6379);
// Splicing key
// The number of times a cell phone sends key
String countKey = "VerifyCode"+phone+":count";
// Verification Code key
String codeKey = "VerifyCode"+phone+":code";
// Each phone can only send three times a day 
String count = jedis.get(countKey);
if(count == null) {

// No number of times to send , First send 
// Set the number of times to send 1
} else if(Integer.parseInt(count)<=2) {

// Number of times sent +1
} else if(Integer.parseInt(count)>2) {

// Send three times , Can no longer send 
System.out.println(" It has been sent more than three times today ");
return;// After more than three times, it will automatically exit and will not be sent again , Don't add this line , Even if the number of times sent is displayed , But there will be verification codes that receive 
// Send verification code to redis Inside 
String vcode = getCode();// Call the generated verification code 
jedis.setex(codeKey,120,vcode);// Set the generated verification code to only 120 The second time 
//1 Generate 6 Digit verification code ,code It's a verification code 
public static String getCode() {

Random random = new Random();
String code = "";
for(int i=0;i<6;i++) {

int rand = random.nextInt(10);
code += rand;
return code;
multi Team formation stage , Not yet implemented set key value
exec Execution phase , take multi Put in line exec in
discard give up multi The value in the queue

Wrong situation :

1. When forming a team, a command fails ,exec All commands failed

2. There is a hidden error in a command when forming a team ,exec Error command failed

Optimism lock

In execution multi Before , Carry out orders watch

Rush to buy goods
public class SecKill_redis {

public static void main(String[] args) {

Jedis jedis =new Jedis("",6379);
// Second kill process 
public static boolean doSecKill(String uid,String prodid) throws IOException {

//1 uid and prodid Judge not empty 
if(uid == null || prodid == null) {

return false;
//2 Connect redis
Jedis jedis = new Jedis("",6379);
//3 Splicing key
// 3.1 stock key
String kcKey = "sk:"+prodid+":qt";
// 3.2 Second kill successful users key
String userKey = "sk:"+prodid+":user";
//4 Get inventory , If inventory null, The second kill hasn't started yet 
String kc = jedis.get(kcKey);
if(kc == null) {

System.out.println(" The second kill hasn't started yet , Please wait ");
return false;
// 5 Judge whether the user repeats the second kill operation 
if(jedis.sismember(userKey, uid)) {

System.out.println(" It's a second kill , You can't repeat the second kill ");
return false;
// because kc For the string , So first change the city integer Type of 
//6 Judge if the quantity of goods , Inventory quantity is less than 1, End of seckill 
if(Integer.parseInt(kc)<=0) {

System.out.println(" The second kill is over ");
return false;
//7.1 stock -1
//7.2 Add successful users to the list 
System.out.println(" The second kill succeeded ..");
return true;

1. Connection timeout , One hundred thousand people asked Redis,Redis Limited connection pool

​ Lock the connection pool

2. The inventory of goods is negative

Add watch Monitor inventory

3. Inventory remaining problems , Because optimistic locking leads to different version numbers

LUA Script solution

// Join a monitoring watch;
//7 Second kill process 
// With a transaction 
Transaction multi = jedis.multi();
// Team operation 
// perform 
List<Object> results = multi.exec();
if(results == null || results.size()==0) {

System.out.println(" The second kill failed ....");
return false;
//7.1 stock -1
//7.2 Add successful users to the list 
System.out.println(" The second kill succeeded ..");
return true;
copyright:author[Xiaoweidumpb],Please bring the original link to reprint, thank you.