How to Integrate Redis for SMS Verification in a Spring Boot Mall Project
This guide walks you through installing Redis, adding Maven dependencies, configuring Spring Boot, creating a Redis service interface and implementation, and building controller endpoints to generate and verify SMS verification codes, complete with code examples and deployment instructions.
Redis Installation and Startup
Redis is a high‑performance key‑value store written in C, often used for caching large volumes of data.
Download Redis from GitHub .
Extract the archive to a chosen directory.
Open a command prompt in the directory and run redis-server.exe redis.windows.conf to start Redis.
Integrating Redis
Adding Project Dependency
<!-- Redis dependency configuration -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>Modifying Spring Boot Configuration
In application.yml add Redis connection settings and custom key configuration:
redis:
host: localhost # Redis server address
port: 6379 # Redis server port
database: 0 # Database index (default 0)
password: # Password (optional)
jedis:
pool:
max-active: 8 # Max active connections
max-wait: -1ms # Max wait time
max-idle: 8 # Max idle connections
min-idle: 0 # Min idle connections
timeout: 3000ms # Connection timeout
key:
authCode: "portal:authCode:" # Custom key prefix
expire: 120 # Expiration time in secondsCreating RedisService Interface
package com.macro.mall.tiny.service;
/**
* Redis operation service, storing objects and arrays as JSON.
*/
public interface RedisService {
/** Store data */
void set(String key, String value);
/** Retrieve data */
String get(String key);
/** Set expiration */
boolean expire(String key, long expire);
/** Delete data */
void remove(String key);
/** Increment */
Long increment(String key, long delta);
}Implementing RedisService with StringRedisTemplate
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;
@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) {
return stringRedisTemplate.opsForValue().increment(key, delta);
}
}Adding UmsMemberController
Provides endpoints for generating and verifying SMS verification codes.
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.*;
@Api(tags = "UmsMemberController", description = "Member login and registration management")
@Controller
@RequestMapping("/sso")
public class UmsMemberController {
@Autowired
private UmsMemberService memberService;
@ApiOperation("Get verification code")
@RequestMapping(value = "/getAuthCode", method = RequestMethod.GET)
@ResponseBody
public CommonResult getAuthCode(@RequestParam String telephone) {
return memberService.generateAuthCode(telephone);
}
@ApiOperation("Verify verification code")
@RequestMapping(value = "/verifyAuthCode", method = RequestMethod.POST)
@ResponseBody
public CommonResult verifyAuthCode(@RequestParam String telephone,
@RequestParam String authCode) {
return memberService.verifyAuthCode(telephone, authCode);
}
}Defining UmsMemberService Interface
package com.macro.mall.tiny.service;
import com.macro.mall.tiny.common.api.CommonResult;
public interface UmsMemberService {
/** Generate verification code */
CommonResult generateAuthCode(String telephone);
/** Verify code against phone number */
CommonResult verifyAuthCode(String telephone, String authCode);
}Implementing UmsMemberServiceImpl
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.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.Random;
@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));
}
// Store code in Redis with expiration
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 generated successfully");
}
@Override
public CommonResult verifyAuthCode(String telephone, String authCode) {
if (StringUtils.isEmpty(authCode)) {
return CommonResult.failed("Please enter verification code");
}
String realAuthCode = redisService.get(REDIS_KEY_PREFIX_AUTH_CODE + telephone);
boolean result = authCode.equals(realAuthCode);
if (result) {
return CommonResult.success(null, "Verification successful");
} else {
return CommonResult.failed("Incorrect verification code");
}
}
}Running the Project
Start the Spring Boot application and open the Swagger UI at http://localhost:8080/swagger-ui.html to test the APIs.
Project Source Code
https://github.com/macrozheng/mall-learning/tree/master/mall-tiny-03
Recommended Reading
mall Architecture Overview
Required Knowledge for mall Learning
Building the Basic Skeleton with SpringBoot + MyBatis
Integrating Swagger‑UI for Online API Docs
Follow us and give a like!
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
macrozheng
Dedicated to Java tech sharing and dissecting top open-source projects. Topics include Spring Boot, Spring Cloud, Docker, Kubernetes and more. Author’s GitHub project “mall” has 50K+ stars.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
