This paper mainly explains the process of mall integration with Redis, taking the storage verification of SMS verification code as an example.

Redis installation and startup

Redis is a high performance key-value pair database developed in C language. It can be used for data caching. It is mainly used to handle high access loads of large amounts of data.

  • Download Redis at github.com/MicrosoftAr…

  • After downloading the file, decompress it to the specified directory

  • Enter CMD in the current address box and run the redis startup command redis.server. exe redis.windows.conf

Integrate Redis

Adding project dependencies

Add Redis dependencies to pom.xml

<! -- Redis dependency configuration -->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
Copy the code

Example Modify the SpringBoot configuration file

Add Redis configuration and Redis custom key configuration in application.yml.

Add the Redis configuration under the Spring node

  redis:
    host: localhost # Redis server address
    database: 0 # Redis database index (default 0)
    port: 6379 # Redis server connection port
    password: # Redis server connection password (default null)
    jedis:
      pool:
        max-active: 8 # maximum number of connections in the pool (use negative values to indicate no limit)
        max-wait: - 1ms Maximum connection pool blocking wait time (negative value indicates no limit)
        max-idle: 8 The maximum number of free connections in the connection pool
        min-idle: 0 Minimum free connection in connection pool
    timeout: 3000ms Connection timeout (ms)
Copy the code

Add the Redis custom key configuration under the root node

# Custom redis key
redis:
  key:
    prefix:
      authCode: "portal:authCode:"
    expire:
      authCode: 120 # Verification code expiration time
Copy the code

Add the RedisService interface to define some common Redis operations

package com.macro.mall.tiny.service;

/** * Created by macro on 2018/8/7. */
public interface RedisService {
    /** * Store data */
    void set(String key, String value);

    /** * get data */
    String get(String key);

    /** * set expiration time */
    boolean expire(String key, long expire);

    /** * delete data */
    void remove(String key);

    /** * autoincrement operation *@paramDelta self-increasing step */
    Long increment(String key, long delta);

}

Copy the code

Inject StringRedisTemplate to implement the RedisService interface

package com.macro.mall.tiny.service.impl;

import com.macro.mall.tiny.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/** * Created by macro on 2018/8/7. */
@Service
public class RedisServiceImpl implements RedisService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void set(String key, String value) {
        stringRedisTemplate.opsForValue().set(key, value);
    }

    @Override
    public String get(String key) {
        return stringRedisTemplate.opsForValue().get(key);
    }

    @Override
    public boolean expire(String key, long expire) {
        return stringRedisTemplate.expire(key, expire, TimeUnit.SECONDS);
    }

    @Override
    public void remove(String key) {
        stringRedisTemplate.delete(key);
    }

    @Override
    public Long increment(String key, long delta) {
        returnstringRedisTemplate.opsForValue().increment(key,delta); }}Copy the code

Add UmsMemberController

Add the interface for obtaining and verifying verification codes based on phone numbers

package com.macro.mall.tiny.controller;

import com.macro.mall.tiny.common.api.CommonResult;
import com.macro.mall.tiny.service.UmsMemberService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/** * Created by macro on 2018/8/3. */
@Controller
@Api(tags = "UmsMemberController", description = "Member Login and Registration Management")
@RequestMapping("/sso")
public class UmsMemberController {
    @Autowired
    private UmsMemberService memberService;

    @ApiOperation("Obtain captcha code")
    @RequestMapping(value = "/getAuthCode", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult getAuthCode(@RequestParam String telephone) {
        return memberService.generateAuthCode(telephone);
    }

    @ApiOperation("Determine whether the verification code is correct.")
    @RequestMapping(value = "/verifyAuthCode", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult updatePassword(@RequestParam String telephone, @RequestParam String authCode) {
        returnmemberService.verifyAuthCode(telephone,authCode); }}Copy the code

The UmsMemberService interface is added

package com.macro.mall.tiny.service;

import com.macro.mall.tiny.common.api.CommonResult;

/** * Service * Created by macro on 2018/8/3. */
public interface UmsMemberService {

    /** * Generates a verification code */
    CommonResult generateAuthCode(String telephone);

    /** * Check whether the verification code matches the mobile phone number */
    CommonResult verifyAuthCode(String telephone, String authCode);

}

Copy the code

Add the UmsMemberService interface implementation class UmsMemberServiceImpl

When generating a verification code, add the self-defined Redis key value to the mobile phone number to generate a Redis key, save the verification code value to Redis, and set the expiration time to the self-configured time (120s in this case). The verification code stored in Redis is obtained according to the mobile phone number and compared with the incoming verification code.

package com.macro.mall.tiny.service.impl;

import com.macro.mall.tiny.common.api.CommonResult;
import com.macro.mall.tiny.service.RedisService;
import com.macro.mall.tiny.service.UmsMemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Random;

/** * Created by macro on 2018/8/3. */
@Service
public class UmsMemberServiceImpl implements UmsMemberService {
    @Autowired
    private RedisService redisService;
    @Value("${redis.key.prefix.authCode}")
    private String REDIS_KEY_PREFIX_AUTH_CODE;
    @Value("${redis.key.expire.authCode}")
    private Long AUTH_CODE_EXPIRE_SECONDS;

    @Override
    public CommonResult generateAuthCode(String telephone) {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            sb.append(random.nextInt(10));
        }
        // The verification code is bound to the mobile phone number and stored in Redis
        redisService.set(REDIS_KEY_PREFIX_AUTH_CODE + telephone, sb.toString());
        redisService.expire(REDIS_KEY_PREFIX_AUTH_CODE + telephone, AUTH_CODE_EXPIRE_SECONDS);
        return CommonResult.success(sb.toString(), "Verification code obtained successfully");
    }


    // Verify the entered verification code
    @Override
    public CommonResult verifyAuthCode(String telephone, String authCode) {
        if (StringUtils.isEmpty(authCode)) {
            return CommonResult.failed("Please enter the verification code.");
        }
        String realAuthCode = redisService.get(REDIS_KEY_PREFIX_AUTH_CODE + telephone);
        boolean result = authCode.equals(realAuthCode);
        if (result) {
            return CommonResult.success(null."Verification code verified successfully");
        } else {
            return CommonResult.failed("Verification code is not correct"); }}}Copy the code

Run the project

Access to Swagger API documentation address, http://localhost:8080/swagger-ui.html, the interface for testing.

Project source code address

Github.com/macrozheng/…

The public,

Mall project full set of learning tutorials serialized, attention to the public number the first time access.