spring boot对接阿里短信

一:依赖包安装

复制代码
<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>dysmsapi20170525</artifactId>
    <version>4.2.0</version>
</dependency>

二:阿里短信配置

在application.yaml配置阿里短信,路径地址为:src/main/resources/application.yaml

复制代码
aliyun:
  sms:
    access-key-id: xxx
    access-key-secret: xxx
    endpoint: dysmsapi.aliyuncs.com
    sign-name: xxx
    template-code: xxx # 短信模板CODE

三:短信配置属性类

复制代码
package com.example.demo.properties;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Data
@Component
@ConfigurationProperties(prefix = "aliyun.sms")
public class AliSmsProperties {
    private String accessKeyId;
    private String accessKeySecret;
    private String endpoint;
    private String signName;
    private String templateCode;
}

四:短信服务

复制代码
package com.example.demo.service;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import com.aliyun.teaopenapi.models.Config;
import com.example.demo.properties.AliSmsProperties;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tools.jackson.databind.ObjectMapper;

import static com.aliyun.teautil.Common.toJSONString;

import java.util.Map;

@Service
public class AliSmsService {

    @Resource
    private AliSmsProperties aliSmsProperties;
    @Autowired
    private ObjectMapper objectMapper;

    public Client createClient() throws Exception {
        Config config = new Config()
                .setAccessKeyId(aliSmsProperties.getAccessKeyId())
                .setAccessKeySecret(aliSmsProperties.getAccessKeySecret())
                .setEndpoint(aliSmsProperties.getEndpoint());
        return new Client(config);
    }


    public boolean send(String phone, Map params) throws Exception {
        //初始化请求客户端
        Client client = createClient();
        try {
            SendSmsRequest sendSmsRequest = new SendSmsRequest();

            //手机号
            sendSmsRequest.setPhoneNumbers(phone);
            // 短信签名
            sendSmsRequest.setSignName(aliSmsProperties.getSignName());
            // 模板CODE
            sendSmsRequest.setTemplateCode(aliSmsProperties.getTemplateCode());
            // 模板参数JSON
            sendSmsRequest.setTemplateParam(objectMapper.writeValueAsString(params));

            SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);

            SendSmsResponseBody body = sendSmsResponse.getBody();

            System.out.println(toJSONString(sendSmsResponse));
            System.out.println("ok".equals(body.getCode()));
            if ("OK".equals(body.getCode())) {
                //发送成功
                return true;
            } else {
                //发送失败
                return false;
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return false;
        }
    }
}

五:短信服务调用示例

复制代码
package com.example.demo.controller;

import com.example.demo.service.AliSmsService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/sms")
public class SmsController {

    @Resource
    private AliSmsService aliSmsService;

    @GetMapping("/send")
    public Boolean send() throws Exception {

        String phone = "xxxxxxxx";
        Map<String, Object> params = new HashMap<>();
        params.put("code", "1234");

        boolean ok = aliSmsService.send(phone, params);
        return ok;
    }
}
相关推荐
code2cat3 分钟前
【随笔】Java客户端选了HTTP/3,怎样知道请求实际走了哪个版本
java·开发语言·http
码云社区2 小时前
Java在线租房系统源码:VR看房素材、房源图片与内容维护方案
java·vue.js·vr·租房小程序·在线租房·看房租房
码云社区2 小时前
Spring Boot智慧物业系统源码:合同到期提醒、续签资料与资产协作
java·spring boot·后端·物业管理·物业系统·智慧物业
AI开源软件2 小时前
Vue3+SpringBoot3 业务配置统一管理:接管、保存与回退怎样保留有效值
java·前端·vue.js·spring boot·vue·ruoyi office
陈如水3 小时前
Spring AI Alibaba 在多 Agent 场景下的实践
java·人工智能·spring
杨运交3 小时前
091-功能模块-API Key 管理功能模块解析:feature-sa-token 架构设计与数据库持久化
spring boot
行百里er3 小时前
【Spring Insight 技术分享】如何给 AI 接口调用做滑动窗口限流
spring boot·后端·spring cloud
有个傻瓜3 小时前
一次「查到别家门店订单」的线上事故:Spring Boot 3 + MyBatis-Plus 多租户隔离踩坑复盘
spring boot·mybatis-plus·多租户·ruoyi-vue-plus·线上故障复盘
吃我一窝jio3 小时前
Docker+Jenkins+K8s全流程部署
java·开发语言·笔记·python
Resean02236 小时前
Spring 源码分析(六)循环依赖与三级缓存
java·spring·缓存