Counting, Generating Unique IDs
All Redis commands are atomic, you can easily use INCR, DECR commands to build a counter system. Similarly, you can use the INCR command to generate unique IDs for game players.
Example:
import java.util.Scanner;
import redis.clients.jedis.Jedis;
public class Incr {
// Count once for each web access
public static void accessWeb(Jedis jedis, String url) {
jedis.incr(url);
}
public static void main(String[] args) {
String host = "127.0.0.1";
int port = 10011;
Jedis jedis = new Jedis(host, port);
String url = "console.surfercloud.com";
//Get the original value
long origin_cnt = Long.parseLong(jedis.get(url));
//Receive terminal input
Scanner sc = new Scanner(System.in);
while(true) {
System.out.println("Access " + url +" ? [y/n]");
String ac = sc.nextLine();
if (ac.equals("y")) {
accessWeb(jedis,url);
}else {
break;
}
}
sc.close();
//Get the current value
long now_cnt = Long.parseLong(jedis.get(url));
//Calculate the number of visits to console.surfercloud.com.
System.out.println("You have visited "+ url+ " " + Long.toString(now_cnt - ori
gin_cnt)+" times.");
jedis.close();
}
}
Output
Access console.surfercloud.com ? [y/n]
y
Access console.surfercloud.com ? [y/n]
y
Access console.surfercloud.com ? [y/n]
y
Access console.surfercloud.com ? [y/n]
y
Access console.surfercloud.com ? [y/n]
n
You have visited console.surfercloud.com 4 times.