In practical application, the implementation of pure digital six-digit invitation code (java implementation)

​ In practical application, the implementation of pure digital six-digit invitation code (java implementation)

First of all, the rigid characteristics of the invitation code: uniqueness and non-repeatability. This is the most important thing, so no matter what the algorithm is, we must ensure the uniqueness of the check, even if there is a one-billion possibility of duplication, it will not work.

Secondly, there are several soft requirements in our business:

1. It needs pure numbers, not combined with letters.

2. Do not order, as random as possible.

Based on the above hard and soft requirements, our solution is to use the database or redis as a unique check. As we all know, the database is based on hard disk storage. Except for the data that is strongly related to the business, we try to reduce the connection and query to the database to avoid resource performance and interface performance problems. However, redis is stored in memory, and its performance and convenience are definitely better than databases. Therefore, the uniqueness check in our production code is done by using the collection of redis.

The following is the code implementation of the java invitation code tool class

package com.example.demo.utils;

import org.springframework.beans.factory.annotation.Autowired;
import java.util.concurrent.TimeUnit;

public class ShareCodeUtils {
    
    

    @Autowired
    private RedisTemplate redisTemplate;
    // 邀请码的长度
    private static final int CODE_LENGTH = 6;
    // redis集合的key值
    private static final String REDIS_KEY = "INVITE_CODE";


    public String generate() {
    
    
        String code;
        do {
    
    
            code = generateCode();
        } while (redisTemplate.opsForSet().isMember(REDIS_KEY,code));
        redisTemplate.opsForSet().add(REDIS_KEY, code);
        return code;
    }

    private String generateCode() {
    
    
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < CODE_LENGTH; i++) {
    
    
            sb.append((int) (Math.random() * 10));
        }
        return sb.toString();
    }

}

Guess you like

Origin blog.csdn.net/qq798867485/article/details/131185478