阿里云短信配置类 从文件配置中读取 信息

该博客介绍了如何在Java项目中配置阿里云短信服务,通过添加依赖并创建`AliyunSmsUtils`类从配置文件读取`accessKeyId`、`accessKeySecret`、`signName`和`templateCode`等信息,实现发送短信的功能。在发送短信的方法中,使用了阿里云SDK进行请求,并解析响应结果来判断发送是否成功。
摘要由CSDN通过智能技术生成

阿里云短信配置类 从文件配置中读取 信息

添加依赖

<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>aliyun-java-sdk-core</artifactId>
</dependency>

可以将以下文件配置到common 模块中

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.nineclock.common.utils.JsonUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@ConfigurationProperties(prefix = "aliyun.sms") //从配置文件中 读入类属性
@Slf4j
@Data
public class AliyunSmsUtils {

    private String accessKeyId;

    private String accessKeySecret;

    private String signName;

    private String templateCode;

    public Boolean sendSMS(String phone, String code) {

        log.info("调用阿里云服务,发送短信: " + phone + ", " + code);
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");

        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", signName);
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}");


        try {
            CommonResponse response = client.getCommonResponse(request);
            log.info("调用阿里云服务发送短信完成, 返回结果 " + response.getData());
            Map map = JsonUtils.toBean(response.getData(), Map.class);
            return map.get("Code").equals("OK");

        } catch (Exception e) {
            log.error("发送短信出错:", e);
            return false;
        }
    }
}

在配置文件中 添加以下信息 供配置类读取

aliyun:
 sms:
  accessKeyId: # AccessKey ID
  accessKeySecret: # AccessKey Secret
  signName: # 签名名称
  TemplateCode: # 模板CODE
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值