Master Spring Boot SMS Integration with SMS4J: Multi‑Provider Setup in Minutes
This guide walks you through integrating SMS4J into a Spring Boot application, covering dependency setup, multi‑vendor configuration, code examples for sending verification codes, Redis‑based rate limiting, fallback handling, common pitfalls, and a ready‑to‑use project structure.
Why Choose SMS4J?
Integrating SMS services in Java projects often suffers from disparate vendor APIs, hard‑coded credentials, and the need to rewrite rate‑limiting logic. SMS4J abstracts these differences, offering a unified API, multi‑vendor and multi‑account support, dynamic switching, Redis‑backed throttling, asynchronous sending, and built‑in utilities for verification codes.
Core Features Overview
Out‑of‑the‑box: Add the starter and start sending SMS immediately.
Multi‑vendor support: Alibaba Cloud, Tencent Cloud, Huawei Cloud, Qiniu Cloud, etc.
Flexible switching: Change providers via configuration without code changes.
Multiple configuration sources: YAML, Nacos, database, etc.
Sending limits: Daily and per‑minute caps with Redis persistence.
Verification code utilities: Random numeric or alphanumeric code generation ( SmsUtil).
Async & thread pool: Built‑in thread pool for non‑blocking SMS dispatch.
Step‑by‑Step Spring Boot Integration
1. Add Maven Dependency
<dependency>
<groupId>org.dromara.sms4j</groupId>
<artifactId>sms4j-spring-boot-starter</artifactId>
<version>LATEST_VERSION</version>
</dependency>Check Gitee or Maven Central for the latest version number.
2. Configure application.yml for Multiple Vendors
sms:
config-type: yaml
blends:
ali1:
supplier: alibaba
access-key-id: YOUR_ACCESS_KEY_ID
access-key-secret: YOUR_ACCESS_KEY_SECRET
signature: YOUR_SMS_SIGNATURE
template-id: SMS_215125134
tencent1:
supplier: tencent
access-key-id: YOUR_SECRET_ID
access-key-secret: YOUR_SECRET_KEY
sdk-app-id: YOUR_SDK_APP_ID
signature: YOUR_TENCENT_SIGNATURE
template-id: YOUR_TEMPLATE_ID3. Send an SMS (Core Controller Code)
@RestController
@RequestMapping("/sms")
public class SmsController {
@GetMapping("/send")
public String sendSms() {
SmsFactory.getSmsBlend("ali1").sendMessage("18888888888", "123456");
return "发送成功";
}
}4. Verification Code Generation
String code = SmsUtil.getRandomInt(6); // 6‑digit numeric code
String mix = SmsUtil.getRandomString(6); // 6‑character alphanumeric code5. Rate Limiting & Redis Configuration
sms:
restricted: true # Enable sending limits
redis-cache: true # Store counters in Redis
account-max: 20 # Max messages per day
minute-max: 2 # Max messages per minute
core-pool-size: 10
max-pool-size: 30
queue-capacity: 50Redis keys such as sms:count:18888888888 (daily count) and sms:minute:18888888888 (per‑minute check) are automatically maintained.
6. Service Wrapper with Automatic Fallback
@Service
public class SmsService {
@Resource
private StringRedisTemplate redisTemplate;
public boolean sendCode(String phone) {
String code = SmsUtil.getRandomInt(6);
try {
SmsFactory.getSmsBlend("ali1").sendMessage(phone, code);
} catch (Exception e) {
// Fallback to another provider
SmsFactory.getSmsBlend("tencent1").sendMessage(phone, code);
}
redisTemplate.opsForValue().set("sms:code:" + phone, code, 5, TimeUnit.MINUTES);
return true;
}
public boolean validateCode(String phone, String inputCode) {
String cache = redisTemplate.opsForValue().get("sms:code:" + phone);
return inputCode != null && inputCode.equals(cache);
}
}7. Common Errors and Fixes
InvalidSignature: Ensure the signature/template is approved in the cloud console.
isv.BUSINESS_LIMIT_CONTROL: Exceeded rate limits – enable Redis throttling.
404 from Alibaba Cloud: Verify AccessKey credentials.
SupplierTypeError: Correct the supplier value (e.g., alibaba, tencent).
Template variable fill failure: Confirm the template format is valid JSON.
8. Recommended Project Structure
src/main/java
└── com.example.sms
├── controller
│ └── SmsController.java
├── service
│ └── SmsService.java
├── config
│ └── RedisConfig.java
└── SmsApplication.javaConclusion
By following this guide, you can equip a Spring Boot application with multi‑vendor SMS capabilities, dynamic account switching, verification code delivery, Redis‑backed rate limiting, and automatic provider fallback—all within roughly ten minutes of setup.
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.
Ray's Galactic Tech
Practice together, never alone. We cover programming languages, development tools, learning methods, and pitfall notes. We simplify complex topics, guiding you from beginner to advanced. Weekly practical content—let's grow together!
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.
