ApsaraDB for Redis is compatible with open source Redis. This topic provides an example on how to use ApsaraDB for Redis to create rankings of online game players sorted by score.

Environment settings

Cloud service Description
Elastic Compute Service (ECS) instance
  • The ECS instance runs the Ubuntu 16.04.6 operating system.
  • The ECS instance and the ApsaraDB for Redis instance are deployed in the same virtual private cloud (VPC).
ApsaraDB for Redis instance The ApsaraDB for Redis instance and the ECS instance are deployed in the same VPC.
Note If the ApsaraDB for Redis instance and the ECS instance are deployed in different VPCs, you can migrate the ApsaraDB for Redis instance to the VPC of the ECS instance. For more information about how to change the VPC of an ApsaraDB for Redis instance, see Change the VPC or vSwitch of an ApsaraDB for Redis instance. If the ApsaraDB for Redis instance and the ECS instance are deployed in different types of networks, see Connect an ECS instance to an ApsaraDB for Redis instance in different types of networks.

Procedure

  1. Configure the IP address whitelist of the ApsaraDB for Redis instance to make sure that the ECS instance and the ApsaraDB for Redis instance can communicate with each other.
    1. Obtain the private IP address of the ECS instance. For more information, see How do I query IP addresses of ECS instances?
    2. Add the private IP address of the ECS instance to the whitelist of the ApsaraDB for Redis instance. For more information, see Configure an IP whitelist.
  2. Log on to the ECS instance. For more information, see Overview.
  3. On the ECS instance, run the following commands to install the dependencies for the environment:
    sudo apt-get update
    sudo apt-get install openjdk-8-jdk
    apt install maven
  4. Run the following commands to download and decompress the sample code file:
    wget https://docs-aliyun.cn-hangzhou.oss.aliyun-inc.com/assets/attach/120287/cn_zh/1615470698355/source.tar.gz
    tar xvf source.tar.gz && cd source
  5. Run the vim src/main/java/test/GameRankSample.java command to change the value of each parameter in the sample code based on your requirements.
    Note After you run the preceding command, the system opens the editor. Enter a to enter the editing mode.
    Figure 1. Examples
    Examples
    Parameter Description
    String host Enter the internal endpoint and port number of the ApsaraDB for Redis instance. For more information about how to obtain the internal endpoint and port number, see View endpoints.
    port
    String authString The password of the account that has the read and write permissions. The password format varies based on the account that you select. For more information about how to create an account, see Create and manage database accounts.
    Note
    • If you are using the default account, which is named after the instance ID, enter only the password.
    • If you are using a custom account, enter a password in the format of <user>:<password>. For example, if the username of a custom account is testaccount and the password is Rp829dlwa, you must enter testaccount:Rp829dlwa.
  6. To save the configuration file and exit the editor, press the Esc key to exit the edit mode, enter :wq, and press the Enter key.
  7. To run the sample code, run the following commands.
    mvn clean package assembly:single -DskipTests
    java -classpath target/demo-0.0.1-SNAPSHOT.jar test.GameRankSample

Output

Comments on the sample code

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) {
    //The endpoint of the instance. You can view the endpoint in the ApsaraDB for Redis console.
    String host = "r-gs50a75e1968****.redis.hangzhou.rds.aliyuncs.com";

    int port = 6379;
    Jedis jedis = new Jedis(host, port);
    try {
      //The password of the instance.
      String authString = jedis.auth("Pass!123"); //password
      if (!authString.equals("OK")) {
        System.err.println("AUTH Failed: " + authString);
        return;
      }
      //The key.
      String key = "Game name: Keep Running, Alibaba Cloud!";
      //Clears all data.
      jedis.del(key);
      //Creates multiple player accounts.
      List<String> playerList = new ArrayList<String>();
      for (int i = 0; i < TOTAL_SIZE; ++i) {
        //Generates a random ID for each player.
        playerList.add(UUID.randomUUID().toString());
      }
      System.out.println("Inputs all players ");
      //Records the score of each player.
      for (int i = 0; i < playerList.size(); i++) {
        //Generates random numbers as the scores of players.
        int score = (int) (Math.random() * 5000);
        String member = playerList.get(i);
        System.out.println("Player ID:" + member + ", Player Score: " + score);
        //Adds the player IDs and scores to a specified sorted set.
        jedis.zadd(key, score, member);
      }
      //Prints the rankings of all players.
      System.out.println();
      System.out.println("       " + key);
      System.out.println(" Ranking list of all players");
      //Obtains the sorted list of players from the specified sorted set.
      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()
        );
      }
      //Prints information about the top five players.
      System.out.println();
      System.out.println("       " + key);
      System.out.println("       Top players");
      scoreList = jedis.zrevrangeWithScores(key, 0, 4);
      for (Tuple item : scoreList) {
        System.out.println(
          "Player ID:" +
          item.getElement() +
          ", Player Score:" +
          Double.valueOf(item.getScore()).intValue()
        );
      }
      //Prints a list of specific players.
      System.out.println();
      System.out.println("         " + key);
      System.out.println(" Players with scores from 1,000 to 2,000");
      //Obtains the list of players whose scores range from 1,000 to 2,000 from the specified sorted set.
      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();
    }
  }
}