In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly introduces redis how to achieve the World Cup ranking function, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand.
Digression:
The editor first recommends a good official account of Wechat to you:
Interested friends can follow the editor's official Wechat account [programmer's thing], more web page production of special effects source code and learn practical information!
Demand
Some time ago, I made a ranking of points in the World Cup. To guess the outcome of 64 World Cup matches, guess right + 1 points, error + 0 points, each person can only guess once.
1. Show a list of the top 100.
two。 Show personal rankings (e. G. Zhang San, your current ranking 106579).
Analysis.
At the beginning, I intend to use the mysql database directly to do it. When I encounter a problem, everyone's score will change. How can I get a personal ranking? The database can be sorted by row_num by score, but this method requires a full table scan, and the query is very slow when the number of participants reaches 10000.
Redis's ranking function perfectly meets this need. Let's see how I did it.
Realize
I. introduction to redis sorts sets
The Sorted Sets data type is like a mix of set and hash. Like sets, Sorted Sets is a unique, non-repeating string composition. It can be said that Sorted Sets is a kind of Sets.
Sorted Sets is implemented through the dual-port data structures of Skip List (hop table) and hash Table (hash table), so every time an element is added, Redis performs an O (log (N)) operation. So when we asked for sorting, Redis didn't need to do any work at all, it was all sorted. The score of the element can be updated at any time.
II. Using RedisTemplate in springboot
This article mainly through redisTemplate to operate redis, of course, you can also use redis-client, depending on personal preferences.
I have opened a single point of redis on this machine, and the configuration file is as follows
Server: port: 9001spring: redis: database: 0 url: redis://user:123@127.0.0.1:6379 host: 127.0.0.1 password: 123 port: 6379 ssl: false timeout: 5000
Maven dependencies are introduced as follows
Org.springframework.boot spring-boot-starter-parent 2.0.4.RELEASE org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-data-redis org.springframework.boot spring-boot-starter-test
three。 Code implementation
1. Inject redis to declare key as a constant SCORE_RANK
@ Autowired private StringRedisTemplate redisTemplate; public static final String SCORE_RANK = "score_rank"
two。 New default ranking data
Here, use the for loop to create a collection, and then use the batch to add 100000 pieces of data
/ * batch added * / @ Test public void batchAdd () {Set tuples = new HashSet (); long start = System.currentTimeMillis (); for (int I = 0; I < 1000000; iTunes +) {DefaultTypedTuple tuple = new DefaultTypedTuple ("Zhang San" + I, 1D + I); tuples.add (tuple);} System.out.println ("cycle time:" (System.currentTimeMillis ()-start)); Long num = redisTemplate.opsForZSet (). Add (SCORE_RANK, tuples) System.out.println ("batch added time:" + (System.currentTimeMillis ()-start)); System.out.println ("number of affected rows:" + num);}
/ / output
Cycle time: 56
Batch added time: 1015
Number of rows affected: 100000
3. Get the top 10 (in reverse order according to scores)
Two get methods are provided, one with score and the other without
/ * get ranking list * / @ Test public void list () {Set range = redisTemplate.opsForZSet (). ReverseRange (SCORE_RANK, 0,10); System.out.println ("obtained ranking list:" + JSON.toJSONString (range)); Set rangeWithScores = redisTemplate.opsForZSet (). ReverseRangeWithScores (SCORE_RANK, 0,10); System.out.println ("obtained ranking and score list:" + JSON.toJSONString (rangeWithScores)) } / / output the ranking list: ["Zhang San 99999", "Zhang San 99998", "Zhang San 99997", "Zhang San 99996", "Zhang San 99995", "Zhang San 99994", "Zhang San 99993", "Zhang San 99992", "Zhang San 99991", "Zhang San 99990", "Zhang San 99989") obtained ranking and score list: [{"score": 100000.0, "value": "Zhang San 99999"}, {"score": 99999.0 "value": "Zhang San 99998"}, {"score": 99998.0, "value": "Zhang San 99997"}, {"score": 99997.0, "value": "Zhang San 99996"}, {"score": 99996.0, "value": "Zhang San 99995"}, {"score": 99995.0, "value": "Zhang San 99994"}, {"score": 99994.0, "value": "Zhang San 99993"}, {"score": 99993.0, "value": "Zhang San 99992"} {"score": 99992.0, "value": "Zhang San 99991"}, {"score": 99991.0, "value": "Zhang San 99990"}, {"score": 99990.0, "value": "Zhang San 99989"}]
4. Add Li Si's score
Add "Li Si" to the ranking, and redis will be carried out when you insert it, and you can take it out directly when you take it out, and you don't need to do any sorting operation.
/ * single addition * / @ Test public void add () {redisTemplate.opsForZSet () .add (SCORE_RANK, "Li Si", 8899);}
5. Get the ranking of Li Si
/ * get a single ranking * / @ Test public void find () {Long rankNum = redisTemplate.opsForZSet (). ReverseRank (SCORE_RANK, "Li Si"); System.out.println ("Li Si's personal ranking:" + rankNum "); Double score = redisTemplate.opsForZSet (). Score (SCORE_RANK," Li Si "); System.out.println (" Li Si's score: "+ score);}
/ / output
Li Si's personal ranking: 91101
Li Si's score: 8899.0
6. The number of people in the statistical score range
Redis also provides a method for counting score ranges, as follows
/ * count the number between the two scores * / @ Test public void count () {Long count = redisTemplate.opsForZSet (). Count (SCORE_RANK, 8001, 9000); System.out.println ("Statistics between 8001 and 9000:" + count);}
/ / output
Statistics between 8001 and 9000: 1001
7. Gets the cardinality (quantity size) of the collection
/ * get the cardinality (quantity size) of the entire collection * / @ Test public void zCard () {Long aLong = redisTemplate.opsForZSet () .zCard (SCORE_RANK); System.out.println ("cardinality of the collection is:" + aLong);}
/ / output
The cardinality of the collection is: 100001
8. Use addition to manipulate fractions
This method uses addition directly on the original score; without this element, it is created, and the score starts with 0. 0. Then use addition
/ * * use addition operation score * / @ Test public void incrementScore () {Double score = redisTemplate.opsForZSet (). IncrementScore (SCORE_RANK, "Li Si", 1000); System.out.println ("Li four scores + 1000:" + score);}
/ / output
Li four points + 1000: 9899.0
four。 Induction
Which features of redis did we use in the above test classes? In the above example, we use single add, batch add, get the top ten, and get single ranking, but redisTemplate also provides more methods.
New or updates
There are three ways, one is individual, the other is batch, using addition for fractions (if it does not exist, add from 0).
/ single added or update Boolean add (K key, V value, double score); / batch added or update Long add (K key, Set tuples); / / use addition operation score Double incrementScore (K key, V value, double delta)
Delete
Deletion provides three ways: delete through key/values, delete through ranking range, and delete through score range.
/ / Delete Long remove (K key, Object...) via key/value Values); / / delete Long removeRange (K key, long start, long end) through the ranking range; / / delete Long removeRangeByScore (K key, double min, double max) through the score range
Check
1. List query:
It can be divided into two categories, positive order and reverse order. The following lists only the positive order, and the reverse order only needs to add reverse before the method.
/ obtain the list value set Set range (K key, long start, long end) through the ranking interval; / / obtain the list value and score set Set rangeWithScores (K key, long start, long end) through the ranking interval; / / obtain the list value set Set rangeByScore (K key, double min, double max) through the score interval; / / obtain the list value and score set Set rangeByScoreWithScores (K key, double min, double max) through the score interval / / obtain the collection ranking Set rangeByLex (K key, Range range) by deleting the Range object; / / obtain the collection ranking Set rangeByLex of the number of limit by deleting the Range object (K key, Range range, Limit limit)
two。 Single inquiry
You can get individual rankings and score through key/value. The following lists only the positive order, and the reverse order only needs to add reverse before the method.
/ / obtain personal ranking Long rank (K key, Object o); / / obtain personal score Double score (K key, Object o)
Statistics
Count the number of people in the score range and count the cardinality of the set.
/ / the number of people in the statistical score range Long count (K key, double min, double max); / / Statistical set cardinality Long zCard (K key)
Conclusion
Here I use redis to achieve the World Cup points ranking display, whether in batch updates or access to personal ranking and other convenience, has a high efficiency, but also reduces the pressure on database operation, and achieves good results.
Thank you for reading this article carefully. I hope the article "how to achieve the World Cup ranking function of redis" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!
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.