天天看點

Spring boot 內建 阿裡雲短信發送功能

建立一個Spring boot 項目 過程此處省略

1在pom.xml檔案中加入依賴

  • 以下依賴包含項目測試用的到工具類
<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- 阿裡雲短信包依賴 -->
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-core</artifactId>
            <version>4.4.1</version>
        </dependency>
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-dysmsapi</artifactId>
            <version>2.1.0</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.20</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.45</version>
        </dependency>

        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.0.6</version>
        </dependency>

        <dependency>
            <groupId> org.springframework.boot </groupId>
            <artifactId> spring-boot-configuration-processor </artifactId>
            <optional> true </optional>
        </dependency>

    </dependencies>
           

2在application.yml 配置需要用到的賬号資訊

2.1accessKeyId和accessKeysecret在阿裡雲的—>使用者資訊管理—>安全資訊管理 中建立

Spring boot 內建 阿裡雲短信發送功能

2.2singName和templateCode 需要在阿裡雲 短信服務中進行建立 并稽核,具體規則官網有詳解

Spring boot 內建 阿裡雲短信發送功能
sms:
  product: Dysmsapi #固定
  url: dysmsapi.aliyuncs.com #請求路徑,固定
  accessKeyId: LTA**********JeKqFdL2 #阿裡雲賬号驗證id
  accessKeySecret: UUBkb***********NesozT6Ln # 阿裡雲驗證密碼
  signName: 黃淮學院軟體工程 #短信簽名
  templateCode: SMS_181850928 #短信模闆
           

3 建立配置類AlySmsConfig

@Component
@PropertySource(value = {"classpath:application.yml"})
@ConfigurationProperties(prefix = "sms")
@Data
public class AlySmsConfig implements Serializable {

    private String product;

    private String url;

    private String accessKeyId;

    private String accessKeySecret;

    private String signName;

    private String templateCode;

}
           

4 建立發送資訊的接口 AlySmsServcie

  • 兩種實作方法,原理相同
public interface AlySmsServcie {

    /**
     * 方法1
     */
    void sendSms();

    /**
     * 方法2
     */
    void sendSmsTwo();

}
           

實作類

@Service
public class AlySmsServiceImpl implements  AlySmsServcie {

    @Autowired
    private AlySmsConfig config;

    private Logger logger = LoggerFactory.getLogger(getClass());

    public IAcsClient alySmsConfigInit() throws ClientException
    {
        //初始化acsClient
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou",config.getAccessKeyId(),config.getAccessKeySecret());
        DefaultProfile.addEndpoint("cn-hangzhou","cn-hangzhou",config.getProduct(),config.getUrl());
        IAcsClient acsClient = new DefaultAcsClient(profile);
        return acsClient;
    }

    @Override
    public void sendSms() {
        try {
        IAcsClient acsClient = alySmsConfigInit();
        //組裝請求對象
        SendSmsRequest request = new SendSmsRequest();
        //手機号,必填
        request.setPhoneNumbers("15239491151");
        //簽名,必填
        request.setSignName(config.getSignName());
        //模闆,必填
        request.setTemplateCode(config.getTemplateCode());
        //模闆中參數,選填
        String params = "123456";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code",params);
        request.setTemplateParam(jsonObject.toJSONString());

        //可選:outId為提供給業務方擴充字段,最終在短信回執消息中将此值帶回給調用者
        request.setOutId("thisOneId");

        //hint 此處可能會抛出異常,注意catch

            SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
            System.out.println(BeanUtil.beanToMap(sendSmsResponse));
            System.out.println(JSON.toJSON(sendSmsResponse));
        }catch (ClientException e)
        {
            System.out.println(e.getMessage());
        }
    }

    @Override
    public void sendSmsTwo() {

        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou",config.getAccessKeyId(),config.getAccessKeySecret());
        IAcsClient acsClient = new DefaultAcsClient(profile);

        //請求對象
        CommonRequest request =new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setDomain(config.getUrl());
        request.setSysVersion("2017-05-25");

        //發送對象
        String phone ="15239491151";
        request.putQueryParameter("PhoneNumbers", phone);
        //  阿裡雲控制台簽名

        request.putQueryParameter("SignName", config.getSignName());

        // 阿裡雲控制台模闆編号

        request.putQueryParameter("TemplateCode", config.getTemplateCode());
        //系統規定參數
        request.setAction("SendSms");

        // 模闆内需要填充參數資訊
        //模闆中參數,選填
        String params = "123456";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code",params);
        request.putQueryParameter("TemplateParam", jsonObject.toJSONString());
        try {
            CommonResponse response = acsClient.getCommonResponse(request);
            System.out.println(BeanUtil.beanToMap(response));
            System.out.println(JSON.toJSON(response));
        }catch (ServerException e) {
            logger.error("阿裡雲短信服務異常:{}", e);
        }catch (ClientException e) {
            logger.error("連接配接阿裡雲短信異常:{}", e);

        }catch (Exception e) {
            logger.error("json轉換異常:{}", e);

        }
    }

}

           

5 測試類

@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = {AlysmsApplication.class})
public class smsTest {

    @Autowired
    private AlySmsServcie alySmsServcie;
    
    @Test
    public void alySmsTest()
    {
        alySmsServcie.sendSms();
    }

    @Test
    public void alySmsTestTwo()
    {
        alySmsServcie.sendSmsTwo();
    }
}