First, the background
I mentioned in my previous essay that the one-click login function was written in the project. After the launch, except for the failure of login caused by network fluctuations, other situations remained stable as the old dog
A certain amount of people have nothing to do these days and can only think of something I can do with a certain amount of time
Second, the solution
Since the one-click login of the project is achieved by invoking its own server, the one-click login is divided into two steps. Since each mobile phone number has a unique OpenID, openID is used as the key value of Redis
(1) Before calling the cloud function
Before calling the cloud function, the front end will send a request to the background, and check the login times within 2 hours in Redis. If the number of login times exceeds the set threshold, the limit of one-key login times will be returned; otherwise, the system will be allowed to pass
(2) Call the cloud function
Called using Redis’s setNX() command, which sets the specified value for the key if the specified key does not exist, in this case equivalent to the SET command. When key exists, do nothing. Set an initial value and expiration time because the key was not present the first time. Next, use Redis’ incrBy() to increment value, +1 each time value is called.
3. Overhand coding
(1) Code before calling the cloud function
public static void checkOneLogin(String openid) {
if (StringUtils.isBlank(openid)) {
"Check parameters. Throw custom exceptions.";
}
// Get the login times of the user in the last half hour from Redis
String s = RedisHelper.get(RedisHelper.get(openid));
// Return if null
if (StringUtils.isBlank(s)){
return;
}
// If redis stores OpenId and value is greater than 10, an exception is thrown
if (Integer.parseInt(s) >= 10) {
log.info([Log] User {} is temporarily banned from one-click login in {} due to excessive one-click login times.,openid,new Date());
"Log, throw an exception."; }}Copy the code
(2) Call cloud function encoding
public static void oneLoginOK(String openid) {
// Enter the default value for the first time
boolean nx = RedisHelper.setNx(RedisHelper.get(openid), "1".60 * 30);
// First entry returns
if (nx) {
return;
}
// Successful login increases by 1
Long incr = RedisHelper.incrBy(RedisHelper.get(openid));
if (incr >= 10) {
// Set the expiration time
RedisHelper.expire(RedisHelper.get(openid), 60 * 60 * 2); }}Copy the code
Write is not very standard, the actual development to add Redis and other problems generally encountered are not young and old, there is not enough memory cloud function, network problems will also have problems ~~~