In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >
Share
Shulou(Shulou.com)06/01 Report--
Xiaobian to share with you java based on redis ordered collection how to achieve the rankings, I believe most people still do not know how to share this article for your reference, I hope you have a lot of harvest after reading this article, let's go to understand it together!
preface
Leaderboard as an essential element of Internet applications, can evoke the desire of human comparison, a treasure in the commodity sales ranking, store reputation ranking, etc., there are many ways to achieve the leaderboard, you can use the quick sorting algorithm + achieve the Comparator interface to achieve sorting by a certain weight, now many companies are using redis this nosql database to achieve the function of the leaderboard
Based on redis implementation leaderboard
What we need to do now is rank companies. The ranking standard is the number of times users search for companies. We need to make a ranking list of the top ten companies.
1. Related redis knowledge
The redis data structure relevant to the implementation of the leaderboard functionality is sort set
About Sort Set
We know that set is a collection, a collection has a characteristic is no repeated elements, sort set in addition to no repeated elements, there is also a characteristic is ordered.
Data structure consists of:
key: unique identifier of sort set Weight: also called score redis Sorts the elements of a set in ascending order by weight (default), weights can be repeated value: set elements, elements cannot be repeated String(set key),double(weight),String(value)
sort set is implemented by hash table, so adding, function, lookup time complexity is O(1), each set can store more than 4 billion elements
basic commands
Add one or more elements to a collection
ZADD "KEY" SCORE "VALUE" [ SCORE "VALUE"]
Effect:
MyRedis:0>ZADD test 1 "one""1"MyRedis:0>zadd test 4 "four" 5 "five""2"
Gets the number of elements in the collection
ZCARD "key"
effect
MyRedis:0>ZCARD test"5"
Gets the score (weight) of the specified element
ZSCORE "KEY" "VALUE"
effect
MyRedis:0>ZSCORE "test" "one""2"
Specifies that the specified element of the collection is incremented by the specified score
ZINCRBY "key" score "value"
Effect:
MyRedis:0>ZSCORE "test" "one""2"MyRedis:0>ZINCRBY "test" 1 "one""3"MyRedis:0>ZSCORE "test" "one" "3"
Gets a specified range of elements (default scores)| ascending order of weights)
ZRANGE "key" Start subscript End subscript
effect
MyRedis:0>ZRANGE "test" 0 1 1) "two" 2) "one"
This is about how many commands are needed to complete this requirement, and then we start implementing our requirement.
2. Springboot + redis implementation
Import redis dependency
org.springframework.boot spring-boot-starter-data-redis
Writing tools
//=============================== sort set ================================= /** * Adds the specified element to an ordered collection * @param key * @param score * @param value * @return */ public boolean sortSetAdd(String key,double score,String value){ try{ return redisTemplate.opsForZSet().add(key,value,score); }catch (Exception e){ e.printStackTrace(); return false; } } /** * The fraction of a specified member in an ordered set plus an increment * @param key * @param value * @param i * @return */ public double sortSetZincrby(String key,String value,double i){ try { //Return the score of the new element return redisTemplate.opsForZSet().incrementScore(key, value, i); }catch(Exception e){ e.printStackTrace(); return -1; } } /** * Gets an ordered collection of specified range elements (from largest to smallest) * @param key * @param start * @param end * @return */ public Set sortSetRange(String key,int start,int end){ try { return redisTemplate.opsForZSet().reverseRange(key, start, end); }catch (Exception e){ e.printStackTrace(); return null; } }
Business realization:
Because the leaderboard has high real-time requirements, I don't think it is necessary to persist it to the database.
/** * Find the specified company by company name * @param companyName * @return */ @Override public AjaxResult selectCompanyName(String companyName) { Set set = redisUtils.sGet("company"); for(Object i : set){ String json = JSONObject.toJSONString(i); JSONObject jsonObject = JSONObject.parseObject(json); if(jsonObject.getString("companyName").equals(companyName)){ //Number of searches + 1 redisUtils.sortSetZincrby("companyRank",companyName,1); log.info ("Return from direct cache"); return new AjaxResult().ok(jsonObject); } } log.error("Not in cache, check database"); TbCommpanyExample tbCommpanyExample = new TbCommpanyExample(); tbCommpanyExample.createCriteria().andCompanyNameEqualTo(companyName); List list = tbCommpanyMapper.selectByExample(tbCommpanyExample); if(list.size() != 0){ //put in cache redisUtils.sSet("company",list.get(0)); //database exists //Search times + 1 redisUtils.sortSetZincrby("companyRank",companyName,1); log.info("sql"); return new AjaxResult().ok(list.get(0)); }else{ return new AjaxResult().error("Company not found: "+companyName); } }
Get Rankings
/** * Get the company rankings (top ten) * @return */ @Override public AjaxResult getCompanyRank() { Set set = redisUtils.sortSetRange("companyRank",0,9); if(set.size() == 0){ return new AjaxResult().error("Company leaderboard is empty"); } return new AjaxResult().ok(set); }3. Testing and Summary
Postman test:
And then there's the question of ranking the same score.
What if I want A to be first in line at the same score but before B later in line?
To solve this problem, we can consider adding a timestamp to the score, which is calculated as:
Timestamped score = actual score * 10000000 + (99999999- timestamp)
This time-bound company can write its own, minimizing errors.
The above is java based on redis ordered collection how to achieve all the content of the leaderboard, thank you for reading! I believe that everyone has a certain understanding, hope to share the content to help everyone, if you still want to learn more knowledge, welcome to pay attention to 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.