In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly introduces how to use the hash data type in redis. It is very detailed and has a certain reference value. Friends who are interested must read it!
1. Overview of hash type data
Let's look at this example first.
We learned about string storage types together in the previous section. However, if the storage of object data has the need to update frequently, the operation will be cumbersome. For example: user:id:100-> {"id": 100,100, "name": "Spring Festival Gala", "fans": 12355, "blogs": 99, "focus:83}, if you need to update the local data in an object, you need to replace all the data, so you have the following requirements.
New requirements: group a series of stored data for easy management, such as the storage structure required to store information about an object: one storage space holds multiple key-value pairs of data
As shown below:
To solve this problem, we introduce a new data type: hash. At the same time, the hash storage structure has also been optimized as follows
If the number of field is small, the storage structure is optimized to be a class array structure.
If the number of field is large, the storage structure uses the HashMap structure
2. Basic operation of hash type data
Modify / add data
Hset key field value
Query single field / query all fields
# query single field data hget key field# query all data hgetall key
Delete operation
Hdel key field1 [field2]
Modify / add multiple data
Hmset key field1 value1 field2 value2
Returns the value of one or more given fields in the hash table
Hmget key field1 field2
Get the number of fields in the hash table
Hlen key
Gets whether the specified field exists in the hash table
Hexists key field3. Extension operation of hash type data
Get all field names or field values in the hash table
Hkey keyhvals key
Sets the numeric data of the specified character segment to increase the value of the specified range
Hincrby key field incrementhincrbyfloat key field increment
Considerations for data manipulation of hash type
Value under the hash type can only store strings, no other data types are allowed, and there are no nested objects. If the data is not obtained, the corresponding result is (nil)
Each hash can store 2 to the 32 power minus 1 key-value pair.
Hash type is very close to the data storage form of objects, and can flexibly add and delete object properties, but hash is not designed to store a large number of objects, so don't abuse it, let alone use hash as an object list.
The hgetall operation can get all the attributes. If there are too many internal field, the efficiency of traversing the entire data will be very low, and it may become the bottleneck of data access.
4. The application case of hash 4.1. Using hash to realize Shopping cart
Overview
Here we do not discuss persistent synchronization between shopping carts and databases, nor do we discuss the relationship between shopping carts and orders, while ignoring the storage of shopping cart information for unlogged-in users. We only use redis's storage model to add, browse, change the quantity, delete and empty the items in the shopping cart.
Realization scheme
Using customer id as key, each user creates a hash storage structure corresponding to shopping cart information
Store the item number as field and the purchased quantity as value
Add goods: add brand-new field and value
Browsing goods: traversing hash
Change quantity: self-increase / self-decrease, set value value
Delete items: delete field
Emptying: deleting key
The sample code is as follows:
# 001 users purchased 101items of ID and 200items of ID 102.One item of hmset 001 101 100 1022000002 of users purchased 1 item of ID 102and 7 items of hmset 002102 1104 7 of ID 104s
Commodity information acceleration
Currently, just storing the quantity in redis does not speed up, because the commodity information still needs to be queried in the database. You can use the following solutions:
The item information record in each shopping cart is saved as two field
Field1 is dedicated to saving quantities
Naming format: commodity id:nums saves data: numerical value
Field2 is specially used to save the product information displayed in the shopping cart, including text description, picture address, merchant information, etc.
Naming format: commodity id:info saves data: json
The sample code is as follows:
# 001user buys 2 items with ID 101and the product information is as follows: {"name": "good name"} hmset 001 101:num 2 101:info "{\" name\ ":\" goods name\ "}" # 002 user buys one item with ID 101and the product information is: {"name": "good name"} hmset 002 101:num 1 101:info "{\" name\ ":\" goods name\ "}
In the value corresponding to 101:info above, the string contains spaces, so it is quoted in double quotes to achieve the purpose of escape.
Independent preservation of commodity information
Because the field2 may exist in multiple product records, the data in the field2 can be saved to a separate hash. At this point, if you save the hash data every time you add a shopping cart record, it is obviously unreasonable, you can save the data through the hsetnx operation, and if the data exists, the save operation is not performed.
The command format is as follows
Hsetnx key field value
The code example is as follows
# storing goods with id 101separately hsetnx info 101s "{\" name\ ":\" goods name\ "}" 4.1. Using hash to realize panic purchase
Case study: on Singles' Day, merchants selling top-up cards for mobile phones launched panic buying activities for 30 yuan, 50 yuan and 100 yuan of goods from China Mobile, China Unicom and Telecom, with an upper limit of 100 for each item.
Solution
Use the merchant id as the key
Take the goods that were snapped up as field.
Take the quantity of goods that participate in the rush purchase as the corresponding value
Use the way of reducing the value to control the quantity of products when snapping up.
There are also practical problems such as overselling in the actual business, which will not be discussed here.
Realization process
Initial information of goods
# p01 merchants, 1000 recharge coupons for c30, 1000 recharge coupons for c50, 1000 recharge coupons for c100 hmset p01 c30 1000 c50 1000 c100 1000
When C30 sells 1 piece, the value minus 1; when C100 sells 20 pieces, the value minus 20, as shown in the following code
# p01 merchant, commodity c30 sold 1 hincrby p01 c30-commodity p01 merchant, commodity c100 sold 20 hincrby p01 c100-205. String storage object vs. hash storage object
String stores json strings: easy to read and update as a whole when updated
Specific fields of hash storage object: update flexibility
With the introduction of the hash data type, we have solved the problem that string stores objects and requires overall updates when updating objects.
The above is all the content of the article "how to use hash data types in redis". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.