Typical applications for Redis

Source: Internet
Author: User
Tags event listener hash http authentication redis time interval rsync
1. Redis implementation voting: use hash to store information about an article (storing entity object information) using INCR to generate the self-increment ID using Zset to save the sorted list, paging by index using the article ID as member, and using set to group according to business rule calculation score

2, Redis management Cluster Application Server session: Cookie session: All HTTP authentication mechanisms, will use a cookie as the authentication information for each request store, that is, the session with a cookie. Two types of cookies: Signature Cookie (Signed): Contains user information and signature (signature). signature, using the mechanism of the MD5 information digest to verify whether it has been tampered with. Token cookie uses a string of random bytes to walk tokens, and the server finds relevant user information in the database based on token. Pros and Cons: Token cookies are small in size and bandwidth-saving. But consumes server storage. and the database access performance requirements are high. Signature cookie, large size, verification signature mechanism laborious, there are security loopholes
3. Redis implements Shopping Cart: no longer holds information in cookies. Instead, it is stored in Redis: the hash "abstract as a shopping cart" as value in the current user's shopping cart, with the user token as key, is implemented as a Redis key value pair.
4, Web cache:. How to combine SPRINGMVC to implement a Web cache caches the request and the returned content as a Redis string key-value. You need to filter for cacheable requests. Set Expiration time expire

5. Data row cache: The data row is serialized as JSON, the row ID is key, as the string key-value cache data row update mechanism: Two ordered collection: Dispatch (Schedule): Member for the row Id,score is the timestamp, the next time the cache execution is recorded Because it is sorted by timestamp, the row ID to be cached is obtained each time from the team header. Delay: Member is the time interval for line Id,score, records the delay value, controls the cache frequency (whether the cache, the next time cache) can be set delay<=0, delete the cache, no longer dispatched. In fact, the delay set can be achieved with hash. A daemon is responsible for running "similar engines" for related work
6. Web analytics: Decide which products should be optimized for Redis cache: For example, set a zset to record the number of items viewed, and browse once for the product score-1. In this way, get a list of product heat

Redis build Twitter backend

1, Redis Modeling: User information (Users hash): "User:${userid} hash" User information hash "user:id:string" User information ID self-increment counter sensitive information is not saved here. (password, mailbox, etc.) "Users:hash" User name Login.lower () as Key-value registered user information hash can be used to check whether the user name has been registered status information (status hash) (that is, dynamic) "status:${ STATUSID} hash "state information hash ... Similar entity object Information hash, there are corresponding ID self-increment counter

Timeline (timeline): Home timeline (home timeline) "Home:${userid}=statusid~timestamp zset" user's home timeline by themselves and following users, And the status that can only be recommended by the user. Personal time Line (Profile timeline)

Watchlist followers list (followers list) "Followers:${userid}=userid~timestamp Zset" the list of people who follow the current user ... Timestamp is the time of concern
List of people you are following (following list) "Following:${userid}=userid~timestamp Zset" Current user
2, concern, take off change concern list: Followers Zset, following zset modify user hash Followerscount, followingcount These statistics will be the profile of the followers (the person taking the off) Some of the latest state information in timeline is added to the followers ' home timeline. Note that the user's home timeline should be kept up to date with the home_timeline_size number of status. And should not be infinitely appended.
3, the status released after the status of the update followers home timeline in two ways: followers less (less than 1000): Directly update all followers home timeline more: Use "delay task "28 Principles for all followers concerns: followers more than 1000 is a small percentage.
4. Twitter-like social networking sites, other common features: private users. Attention to this type of user, need approval mechanism to collect the user's private chat comments, likes, forwards @ users ... #话题 Complaint Mechanism User Group


5, Flow api--unintelligible general Flow API refers to the chain programming, that is, chain. And here is the stream. Some of the actions of social networking sites, such as publication status, deletion status, and so on, to understand the status of the site, you need to "broadcast events" for these actions, and then by the "event listener" listener to handle these events. This section implements broadcast and listener streaming data via the Redis Publish subscription (Publish/subscribe) mode using an HTTP chunked (chunked) transport, returning the message to the subscribed client as a stream
6, when registering a new user, lock the user name: Lock the current user name, the registration process to ensure that the user name is no longer being unregistered by others. If the acquisition lock fails, it indicates that the user name has been locked by someone else and is registering.
7, foreign Key Association in addition to have fk_id, should add Fk_name: usually need to show the associated information (at least name). If you add name, the downside is changing the name to a large-scale association modification. The advantage is that you don't have to correlate queries every time. However, because the query probability is much larger than the modification probability, you should bring the name




1, auto-completion (AutoComplete): Common Application Scenario: according to the input prefix, auto-complete search hot words using zset and Zrangebylex command implementation: add elements to Zset to create a look-up range, get the elements in the range, and remove the added elementsBased on the input prefix, gets the precursor (predecessor) and successor (successor) if Utf-8 in the current encoding (usually using utf-8), the precursor is calculated by prefix---to UTF8 encoding, and then the last byte minus 1. The successor is directly to the PREFIX+\XEF\XBF\XBF "\uffff Unicode character utf-8 byte form" will predecessor, successor insert Zset, then use Zrangebylex to get the element between the two "pay attention to use (open interval, thereby removing both ends"--Detailed Usage Reference redis Command reference documentationFinally, use Zrem to remove predecessor, successor settings Zset all score to 0 to sort the member directly
To add bytes (the smallest unit of Redis string) on the REDIS-CLI command line, you must use \x in quotation marks plus two-bit 16 binary. Competitive conditions race Condition: is the sharing of data consistency and the concept of locking mechanism in a reasonable range, the partial computation to the client, the "distributed computing" thinking, to reduce the load of the server.


2, file distribution: Common three ways to distribute Files: NFS or Samba: For server continuous distribution files Rsync software: (see Linux remote replication) uses synchronous increments to reduce the amount of traffic. Used for gradual changes in content (such as log files) BitTorrent protocol: Distribute file shards (partial) to multiple machines, and then let them share their own data, thereby reducing the load on the server. Used to distribute copies of files to multiple machine limitations: There are significant installation costs and relative value are independent services, need to maintain account and permissions Nfs/samba in the network is not stable rsync although not sensitive to network connection, but before synchronizing, you must first download the entire file BitTorrent, need the client to have BitTorrent client software to do support. Log analysis: map/reduce, File replication is not suitable for local data aggregation calculations, reduce the resource consumption of Redis remote communication. Send/Receive/process log files:

3. Use Redis logging: Two common logging methods in Unix-like systems:
Append log lines to the log file, adding new log files over time (rolling)
Syslog Service:
Forwarding function: Receive log messages from other programs and forward to corresponding log files

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.