Online game score ranking based on redis

Time:2020-11-21

introduce

This scenario will introduce how to implement the player points ranking function in online games based on redis database.

background knowledge

Redis
Redis is an open source, using ANSI C language to write, comply with BSD protocol, support network, can be based on memory and persistent log type key value database, and provides a variety of language API. It is often referred to as a data structure server, because values can be of types such as string, hash, list, sets, and sorted sets. ZSet(sorted Sets (sets) is an ordered set. The internal use of HashMap and skip table (skiplist) to ensure the orderly storage of data. In HashMap, the mapping of members to score is placed, and all members are stored in the jump table. Sorting is based on the score stored in HashMap. Using the structure of jump table can obtain high efficiency of searching, and is relatively simple in implementation. Leaderboard is a classic usage scenario of ordered collection. For example, websites such as novel video need to make a ranking list of novels uploaded by users. The list can be graded according to the number of users’ attention, update time, word number, etc.

Apache Maven
Maven is an open source project management tool of Apache. It includes a project object model, a set of standard sets, a project lifecycle, and a dependency management system System) and the logic used to run the plug-in goal defined in the phase. But because the foreign warehouse often can’t connect, even if it is connected, the download speed is also very slow. Alibaba cloud provides an official image warehouse based on Maven. The image warehouse uses OSS (object storage) as the back-end storage, which has fast download speed and supports high concurrency. Moreover, the whole site is encrypted with HTTPS, which is more secure.

Scene experience

An ECS instance (cloud server) with CentOS 7.7 and a redis 5.0 database instance are provided. Through the operation of this tutorial, you can use java language to realize the game player points ranking function based on redis database.
Alicloud scene resources: (provide real resource simulation)
https://developer.aliyun.com/adc/scenario/44d54481170f4914996d3ae53b818f32

Step 1: build Java environment

This step will build a java development environment on the ECS server, including openjdk 1.8 and maven 3.6.3, and configure alicloud image warehouse.

Operation steps:

1. Install openjdk 1.8.

yum -y install java-1.8.0-openjdk-devel.x86_64

2. Download Maven installation package.

wget https://mirror.bit.edu.cn/apache/maven/maven-3/3.6.3/binaries/apache-maven-3.6.3-bin.tar.gz

3. Unzip the downloaded installation package to the / usr / local / directory and rename the installation directory.

tar -zxvf apache-maven-3.6.3-bin.tar.gz -C /usr/local/ &&
mv /usr/local/apache-maven-3.6.3/ /usr/local/maven

4. Add Maven’s executable file directory to the system environment variable, and use the source command to make the contents of the / etc / profile file take effect immediately.

echo "export PATH=$PATH:/usr/local/maven/bin" >> /etc/profile
source /etc/profile

5. Execute the following command to open the image warehouse configuration file and add alicloud image warehouse configuration.

a. Open the mirror warehouse configuration file using vim.

vim /usr/local/maven/conf/settings.xml

b. Enter the VIM editor page and enter / mirrors to search for and jump to the < mirrors > tab.

c. Press n to jump to the second uncommented label.

d. Press the o key to start another line for editing and paste the following.

<mirror>
       <id>nexus-aliyun</id>
       <mirrorOf>central</mirrorOf>
       <name>Nexus aliyun</name>
       <url>http://maven.aliyun.com/nexus/content/groups/public</url>
</mirror>

e. Press ECs to exit the edit mode, enter: WQ to save and exit the VIM editor.

Add alicloud image warehouse configuration as shown in the following figure:
Online game score ranking based on redis

Step 2: develop the game player points ranking function

Operation steps:

1. Execute the following command to create and enter the workspace.

mkdir -p demo/src/main/java/test/ && cd demo

2. Refer to the following steps to edit the code file.

a. Open with VIM GameRankSample.java Documents.

vim src/main/java/test/GameRankSample.java

b. Input: set paste enter and press the I key to enter the VIM paste insertion mode, and add the following contents.

package test;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Tuple;
public class GameRankSample {
    static int TOTAL_SIZE = 20;
    public static void main(String[] args) 
    {
        //Redis database connection address
        String host = "xxxxxxxxxx.m.cnhz1.kvstore.aliyuncs.com";
        //Connection password
        String password = "password";
        int port = 6379;
        Jedis jedis = new Jedis(host, port);
        try {
            String authString = jedis.auth(password);
            if (!authString.equals("OK"))
            {
                System.err.println("AUTH Failed: " + authString);
                return;
            }
            //Key
            String key = "game name: run, Ali! ";
            //Clear possible existing data
            jedis.del(key);
            //Simulate and generate several gamers
            List<String> playerList = new ArrayList<String>();
            for (int i = 0; i < TOTAL_SIZE; ++i)
            {
                //Randomly generate each player's ID
                playerList.add(UUID.randomUUID().toString());
            }
            System.out.println ("enter all players");
            //Record each player's score
            for (int i = 0; i < playerList.size(); i++)
            {
                //Randomly generate numbers to simulate player's game score
                int score = (int)(Math.random()*5000);
                String member = playerList.get(i);
                System.out.println ("player ID" + member + ", player score" + score) ";
                //Add the player's ID and score to the sortedset of the corresponding key
                jedis.zadd(key, score, member);
            }
            //Output and print all player rankings
            System.out.println();
            System.out.println("       "+key);
            System.out.println (the "all players leaderboard");
            //Get the ordered player list from the sortedset of the corresponding key
            Set<Tuple> scoreList = jedis.zrevrangeWithScores(key, 0, -1);
            for (Tuple item : scoreList) {  
                System.out.println (player ID:+ item.getElement "+, player score:+ Double.valueOf ( item.getScore ()).intValue());
            }  
            //Output and print top 5 player rankings
            System.out.println();
            System.out.println("       "+key);
            System.out.println ("top player");
            scoreList = jedis.zrevrangeWithScores(key, 0, 4);
            for (Tuple item : scoreList) {  
                System.out.println (player ID:+ item.getElement "+, player score:+ Double.valueOf ( item.getScore ()).intValue());
            }
            //Output print specific player list
            System.out.println();
            System.out.println("         "+key);
            System.out.println (players with 1000 to 2000 points);
            //Get the list of players who have accumulated 1000 to 2000 points from the sortedset of the corresponding key
            scoreList = jedis.zrangeByScoreWithScores(key, 1000, 2000);
            for (Tuple item : scoreList) {  
                System.out.println (player ID:+ item.getElement "+, player score:+ Double.valueOf ( item.getScore ()).intValue());
            } 
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            jedis.quit();
            jedis.close();
        }
    }
}

c. Press the ESC key to exit the paste insert mode, and then enter: set nopaste. Press enter and press the I key to enter the normal VIM insertion mode. Replace the values of host and password variables in the code with the redis intranet address and redis password provided by the experience platform on the left Resource bar.

d. Press the ESC key to exit the edit mode, enter the command mode, enter the command: WQ, save and exit vim.

3. Refer to the following steps to create pom.xml Configuration file.

a. Open with VIM pom.xml Documents.

vim pom.xml

b. Press the I key to enter the VIM editing mode and add the following contents:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>test</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.9.0</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <configuration>
                    <appendAssemblyId>false</appendAssemblyId>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                    <archive>
                        <manifest>
                            <! -- jar entry class, format Package.ClassName  >
                            <mainClass>test.GameRankSample</mainClass>
                        </manifest>
                    </archive>
                </configuration>
                <executions>
                    <execution>
                        <id>make-assembly</id>
                        <phase>package</phase>
                        <goals>
                            <goal>assembly</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

c. Press the ESC key to exit the edit mode, enter the command mode, enter the command: WQ, save and exit vim.

4. Use Maven to package the project.

mvn assembly:assembly

If the following log appears, the package is successful:
Online game score ranking based on redis

  1. Run the jar file.
java -jar target/demo-0.0.1-SNAPSHOT.jar

The operation results are as follows:
Online game score ranking based on redis
The above is all the content of the online game points ranking based on redis

To experience the real scene, you can go to alicloud experience lab
https://developer.aliyun.com/adc/labs/