Redis can not only store strings, but also List, Set, Hash, and Zset. What advantages can it bring to you if used correctly?

Article directory

  • Application scenarios of the five major data types of Redis
    • 1. String
    • 2. Hash
    • 3. List
    • 4. Set
    • 5. Zset

I am Liao Zhiwei, a Java development engineer, high-quality creator in the Java field, CSDN blog expert, 51CTO expert blogger, Alibaba Cloud expert blogger, Tsinghua University Press contracted author, product soft article creator, technical article review teacher, Questionnaire designer, personal community founder, open source project contributor. I have run fifteen kilometers, climbed Hengshan Mountain on foot, and have experienced losing 20 pounds in three months. I am a ruthless person who likes to lie flat.

Have many years of front-line R&D and team management experience, and have studied the underlying source code of mainstream frameworks (Spring, SpringBoot, Spring MVC, SpringCould, Mybatis, Dubbo, Zookeeper), the underlying architecture principles of message middleware (RabbitMQ, RockerMQ, Kafka), Redis Cache, MySQL relational database, ElasticSearch full-text search, MongoDB non-relational database, Apache ShardingSphere sub-database and table read-write separation, design pattern, domain-driven DDD, Kubernetes container orchestration, etc. Have experience in high-concurrency projects from 0 to 1, using elastic scaling, load balancing, alarm tasks, and self-starting scripts. The highest pressure has been tested on 200 machines. He has rich experience in project tuning.

After years of experience in creating thousands of articles in CSDN, I already have good writing skills. At the same time, I also signed a contract with Tsinghua University Press for four books, which will be published next year. These books include “Java Project Practice – In-depth understanding of common technologies of large Internet companies” for basic, advanced and architecture chapters, and “Decrypting the Programmer’s Thinking Code – Practice of Communication, Speech and Thinking” 》. The specific publishing plan will be adjusted according to the actual situation. I hope all readers can support me!

Take dreams as horses and live up to your time

I hope that all readers will support bloggers who write articles with care. Times have changed, information is exploding, and the alley is dark. Bloggers really need everyone’s help to continue to shine in this ocean, so hurry up. Move your little hands, click to follow, click to like, click to favorite, and even click to comment, these are the best support and encouragement for bloggers!

  • Blog homepage: I am Liao Zhiwei
  • Open source project: java_wxid
  • Bilibili: I am Liao Zhiwei
  • Personal Community: The boss behind the scenes
  • Personal WeChat ID: SeniorRD

At this beautiful moment, I no longer talk nonsense, and now enter the topic to be discussed in the article without delay. Next, I will present the main text content to you.

CSDN

Redis can not only store strings, but also List, Set, Hash, and Zset. Use it correctly. What advantages can it bring to you?

Application scenarios of Redis’s five major data types

Redis is a high-performance key-value database that supports multiple data types, including String, Hash, List, Set and Zset. Each data type has its own characteristics and application scenarios, and is widely used in actual development. The application scenarios and examples of each data type will be introduced below.

1. String

The String data type is the most basic data type in Redis. It can store any type of string, including numbers and JSON format strings. In actual development, the String data type has a wide range of application scenarios. For example, the distributed lock we often talk about is implemented through setnx. Below we will introduce the application scenarios and examples of the String data type in detail:

  1. Distributed lock

In a distributed system, in order to prevent multiple clients from modifying the same data at the same time, we need to use locks to ensure concurrent access to data. The most common one is distributed lock, which can achieve exclusive access to resources. Distributed locks can be implemented in Redis through the setnx command. If 1 is returned, it means the lock acquisition is successful, otherwise the lock acquisition fails. The following is an example of using setnx to implement distributed locks:

SET key value NX EX max_lock_time

2. Counter

When counting the number of website visits, we can use the incr command of Redis. It can perform an increment operation on the specified key and return the incremented value. The following is an example of using incr to implement a counter:

INCR page_view_count

2. Hash

The Hash data type is a special string type provided by Redis. It can store multiple key-value pairs, each key-value pair is a string. In actual development, the application scenarios of Hash data type are also very wide. For example, we often use Hash to store user information, product information, etc. Below we will introduce the application scenarios and examples of the Hash data type in detail:

1. Shopping cart

In e-commerce projects, the shopping cart is a very important business module. We can use the Hash data type of Redis to implement the shopping cart function. For example, we can use the hset command to add products, the hlen command to get the total number of products, the hdel command to delete products, and the hgetall command to get all the products in the shopping cart. The following is an example of using Hash to implement a shopping cart:

HSET cart:item1 id 1 name 'item1' price 10
HSET cart:item2 id 2 name 'item2' price 20
HLEN cart
HDEL cart:item1
HGETALL cart

2. Cache objects

When caching objects, sometimes we need to modify multiple fields instead of a single field. In this case, we can use Redis’s Hash data type to store the object. For example, we can use the hset command to add an object, the hmget command to obtain multiple fields of an object, and the hset command to set multiple fields of an object. The following is an example of using Hash to implement cache objects:

HSET user:1 name 'Tom' age 18 gender 'Male'
HMGET user:1 name age gender
HSET user:1 name 'Jerry' age 19 gender 'Female'

3. List

The List data type is actually a simple list of strings, sorted in insertion order. It can add an element to the head or tail of the list and pop elements of the list through the lpop and rpop commands. In actual development, the List data type has a wide range of application scenarios. For example, we often use List to implement message queues, article lists, etc. Below we will introduce the application scenarios and examples of the List data type in detail:

1. Article publishing

During the article publishing process, we need to display the article list in the order of publishing time. At this time we can use Redis’s List data type to store the article list. For example, we can use the lpush and rpop commands to implement a first-in-first-out queue. The following is an example of using List to publish articles:

LPUSH article_list article1
LPUSH article_list article2
RPUSH article_list article3
LRANGE article_list 0 -1

2. Weibo news

In the process of displaying Weibo messages, we need to display Weibo messages in the order of release time. At this time, we can use the List data type of Redis to store the Weibo message list. For example, we can use the lpush and lpop commands to implement a first-in, last-out stack. The following is an example of using List to implement Weibo messages:

LPUSH weibo_list weibo1
LPUSH weibo_list weibo2
LPOP weibo_list

4. Set

The Set data type is an unordered collection provided by Redis, which can store multiple string values and does not allow duplication. In actual development, the Set data type has a wide range of application scenarios. For example, we often use Set to implement global deduplication, WeChat lottery, Weibo likes, collections, tags and other functions. Below we will introduce the application scenarios and examples of the Set data type in detail:

1. Global deduplication

In actual development, it is often necessary to deduplicate data. In this case, we can use the Set data type of Redis to achieve global deduplication. For example, we can use the sadd and smembers commands to add elements to a Set and get all elements. The following is an example of using Set to achieve global deduplication:

SADD user_list user1
SADD user_list user2
SADD user_list user3
SMEMBERS user_list

2. WeChat lottery

During the WeChat lottery, we need to ensure that each user can only win one prize. At this time we can use the Set data type of Redis to implement the WeChat lottery. For example, we can use the sadd and spop commands to draw and remove elements. The following is an example of using Set to implement WeChat lottery:

SADD prize_list prize1
SADD prize_list prize2
SADD prize_list prize3
SPOP prize_list

5. Zset

The Zset data type is an ordered set provided by Redis, which can store multiple string values, and each string has a score. In actual development, the Zset data type has a wide range of application scenarios. For example, we often use Zset to implement functions such as leaderboards and gold coin rankings. Below we will introduce the application scenarios and examples of the Zset data type in detail:

1. Ranking list

When implementing the ranking function, we need to display the ranking list in order of scores. At this time we can use Redis’s Zset data type to store the rankings. For example, we can use the zadd command to add elements to Zset and specify the score, and use the zrange command to obtain the ranking list. The following is an example of using Zset to implement the ranking list:

ZADD rank_list 100 Tom
ZADD rank_list 200 Jerry
ZADD rank_list 300 Bob
ZADD rank_list 400 Amy
ZRANGE rank_list 0 -1 WITHSCORES

2. Gold coin ranking

During the gold coin ranking process, we need to display the ranking list in order of the user’s gold coin count. At this time we can use Redis’s Zset data type to store gold coin rankings. For example, we can use the zadd command to add users to Zset and specify the number of gold coins, and use the zrevrange command to obtain the ranking list. The following is an example of using Zset to achieve gold coin ranking:

ZADD coin_list 1000 Tom
ZADD coin_list 2000 Jerry
ZADD coin_list 3000 Bob
ZADD coin_list 4000 Amy
ZREVRANGE coin_list 0 -1 WITHSCORES

The above are the application scenarios and examples of the five major data types of Redis, including String, Hash, List, Set and Zset. Developers can choose appropriate data types according to different needs and combine Redis’ rich commands to implement their own business logic.

CSDN

If you need to reprint or move this article, you are very welcome to send me a private message~

I hope that all readers will support bloggers who write articles with care. Times have changed, information is exploding, and the alley is dark. Bloggers really need everyone’s help to continue to shine in this ocean, so hurry up. Move your little hands, click to follow, click to like, click to favorite, and even click to comment, these are the best support and encouragement for bloggers!

  • Blog homepage: I am Liao Zhiwei
  • Open source project: java_wxid
  • Bilibili: I am Liao Zhiwei
  • Personal Community: The boss behind the scenes
  • Personal WeChat ID: SeniorRD

Blogger’s life insights and goals

Exploring the inner world, bloggers share life insights and future goals

  • You cannot stop on the road of program development. If you stop, you will easily be eliminated. If you cannot endure the hardship of self-discipline, you will suffer from mediocrity. Only sustained ability can bring continuous self-confidence. I am a very ordinary programmer myself. Among the crowd, apart from my innate beauty, I am only 180cm tall. Even a person like me has been writing blog posts silently for many years.
  • There is an old saying that goes before being awesome, you have to be a fool to persevere. I hope that you can create your own technical influence through a large number of works, time accumulation, personal charm, luck, and timing.
  • My heart is ups and downs, sometimes I am excited, sometimes I am pensive. I hope that I can become a comprehensive talent with superb skills in technology, business and management. I want to be the chief designer of the product architecture route, the leader of the team, the mainstay of the technical team, and a practical expert in corporate strategy and capital planning.
  • The realization of this goal requires unremitting efforts and continuous growth, but I must work hard to pursue it. Because I know that only by becoming such a talent can I continue to advance in my career and bring real value to the development of the company. In this ever-changing era, I must always be ready to face challenges, keep learning and exploring new areas in order to keep moving forward. I firmly believe that as long as I keep working hard, I will definitely achieve my goals.