02 Introduction and application of the five classic data types of Redis

  • command encyclopedia
  • 9 types
    • String (character type)
    • Hash (hash type)
    • List (list type)
    • Set (collection type)
    • SortedSet (ordered collection type, referred to as zset)
    • Bitmap (bitmap)
    • HyperLogLog (statistics)
    • GEO (geography)
    • Stream (understand)

string

Common commands

  • Most used
    • set key value
    • get key
  • Set/get multiple key values ​​at the same time
    • MSET key value [key value …]
    • MGET key [key …]
  • Numerical increase or decrease
    • Increment number: INCR key
    • Increase the specified integer: INCRBY key increment
    • Decrement value: DECR key
    • Decrement the specified integer: DECRBY key decrement
  • Get the string length: STRLEN key
  • distributed lock
    • setnx key value
    • set key value [EX seconds] [PX milliseconds] [NX|XX]
    • insert image description here

Application Scenario

  • For example, Douyin can like a certain video or product infinitely, and click to add it once
  • Do you like the article
  • Number of readings: As long as you click on the rest address, you can directly use the incr key command to add a number 1 to complete the record number.
    insert image description here

hash

Common commands

  • Map<String,Map<Object,Object>>
  • Set a field value at a time: HSET key field value
  • Get field values ​​one at a time: HGET key field
  • Set multiple field values ​​at once: HMSET key field value [field value …]
  • Get multiple field values ​​at once: HMGET key field [field …]
  • Get all field values: hgetall key
  • Get all the quantities in a key: hlen
  • Delete a key: hdel

Application Scenario

The early design of the JD shopping cart is no longer used, and the current small and medium factories are available

  • Add new product → hset shopcar:uid1024 334488 1
  • Add new product → hset shopcar:uid1024 334477 1
  • Increase the quantity of goods→ hincrby shopcar:uid1024 334477 1
  • Total number of products → hlen shopcar:uid1024
  • select all → hgetall shopcar:uid1024
    insert image description here

list

Common commands

  • The structure of a double-ended linked list , the capacity is 2 to the 32nd power minus 1 element, about 4 billion, the main functions are push/pop, etc., generally used in stacks, queues, message queues and other scenarios.
  • Add elements to the left of the list: LPUSH key value [value …]
  • Add elements to the right of the list: RPUSH key value [value ...]
  • View list: LRANGE key start stop
  • Get the number of elements in the list: LLEN key

Application Scenario

WeChat official account subscription news

  • Mr. Li Yongle, the author of the big V, and CSDN published articles 11 and 22 respectively
  • Brother Yang has followed both of them, as long as they publish new articles, they will be installed in my List
    lpush likearticle: Brother Yang id 11 22
  • View all the articles subscribed by Yang Ge's own account, similar to pagination, the following 0~10 is to display 10 articles at a time
    lrange likearticle: Yang Ge id 0 9
    insert image description here

Product review list

  • Requirement 1: A user posts a comment on a product, and a product will be commented by different users. When saving product reviews, sort them in chronological order
  • Requirement 2: The user queries the comments of the product on the front-end page, which needs to be sorted in descending order of time
  • Use the list to store product comment information, the key is the id of the product, and the value is the product review key of the product review information product number 1001 [items:comment:1001]
  • lpush items:comment:1001 {“id”:1001,“name”:“huawei”,“date”:1600484283054,“content”:“lasjfdljsa;fdlkajsd;lfjsa;ljf;lasjf;lasjfdlsad”}

set

Common commands

  • Add element: SADD key member [member ...]
  • Delete element: SREM key member [member ...]
  • Traverse all elements in the collection: SMEMBERS key
  • Determine whether the element is in the set: SISMEMBER key member
  • Get the total number of elements in the collection: SCARD key
  • Randomly pop an element from the collection, the element is not deleted: SRANDMEMBER key [number]
  • Randomly pop an element from the collection, remove one and delete one: SPOP key [number]
  • set operation
    • Set difference operation AB
      • The set of elements that belong to A but not to B
      • SDIFF key [key …]
    • Set intersection operation A∩B
      • A collection of commonly owned elements that belong to A and also belong to B
      • SINTER key [key …]
    • The union operation of sets A ∪ B
      • The combined set of elements belonging to A or B
      • SUNION key [key …]

Application Scenario

WeChat lucky draw applet

  • User ID, Participate Now button
    • sadd key user ID
  • Show how many people have participated, 23208 people have participated in the picture above
    • SCARD key
  • Lottery draw (randomly select N winners from the set)
    • SRANDMEMBER key 2 randomly draws 2 people, elements are not deleted
    • SPOP key 3 randomly draw 3 people, the element will be deleted

WeChat circle of friends like

  • add likes
    • sadd pub:msgID like user ID1 like user ID2
  • cancel like
    • srem pub:msgID Like user ID
  • Show all users who have liked
    • SMEMBERS pub:msgID
  • The statistics of the number of like users is the common red number of like
    • scard pub:msgID
  • Determine whether a friend has liked the host
    • SISMEMBER pub:msgID User ID

Weibo friends follow social relations

common concern

insert image description here

The people I follow also follow him (everyone has the same hobbies)

insert image description here

people you may know

insert image description here

Set

  • Add an element and the element's score to the sorted set
  • Add element: ZADD key score member [score member ...]
  • According to the order of element scores from small to large, return all elements with index from start to stop
    • ZRANGE key start stop [WITHSCORES]
  • Get the score of an element
    • ZSCORE key member
  • delete element
    • ZREM key member [member …]
  • Get the elements of the specified score range
    • ZRANGEBYSCORE key min max [WITHSCORES] [LIMIT offset count]
  • increase the score of an element
    • ZINCRBY key increment member
  • Get the number of elements in the collection
    • ZCARD key
  • Get the number of elements within the specified score range
    • ZCOUNT key min max
  • Remove elements by rank range
    • ZREMRANGEBYRANK key start stop
  • Get the rank of an element
    • From small to large: ZRANK key member
    • From largest to smallest: ZREVRANK key member

Application Scenario

Sort the display of products based on product sales

  • Define the commodity sales leaderboard (sorted set collection), the key is goods:sellsort, and the score is the quantity of commodity sales.
  • insert image description here

Douyin hot search

insert image description here

Case study: WeChat article reading statistics

package com.learn.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author YSK
 * @since 2023/5/30 14:06
 */
@Service
@Slf4j
public class ArticleService {
    
    
    public static final String ARTICLE = "article:";
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public void likeArticle(String articleId) {
    
    
        String key = ARTICLE + articleId;
        Long likeNumber = stringRedisTemplate.opsForValue().increment(key);
        log.info("文章编号:{},喜欢数:{}", key, likeNumber);
    }
}
package com.learn.controller;

import com.learn.service.ArticleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author YSK
 * @since 2023/5/30 14:07
 */
@RestController
@Slf4j
@Api(description = "喜欢的文章接口")
public class ArticleController {
    
    
    @Resource
    private ArticleService articleService;

    @ApiOperation("喜欢的文章,点一次加一个喜欢")
    @RequestMapping(value = "/view/{articleId}", method = RequestMethod.POST)
    public void likeArticle(@PathVariable(name = "articleId") String articleId) {
    
    
        articleService.likeArticle(articleId);
    }

}
  • Small and medium-sized factories can use it, but large factories with particularly high QPS cannot use it

Guess you like

Origin blog.csdn.net/m0_56709616/article/details/130944864