您现在的位置是:首页 >技术教程 >通过springboot内置功能动态刷新配置,mysubmail 发短信网站首页技术教程

通过springboot内置功能动态刷新配置,mysubmail 发短信

是阿漂啊 2025-12-15 12:01:03
简介通过springboot内置功能动态刷新配置,mysubmail 发短信

nacos 2.2.1

spring boot动态刷新配置

nacos 配置

mysubmail:

        appid: xxx

        appkey: xxx

        url: xxx

@ConfigurationProperties(prefix = "mysubmail")
@Configuration
@Data
public class SmsConfig {
    private String appid;

    private String appkey;

    private String url;
}

@Data
@Slf4j
@Component
@EnableConfigurationProperties({SmsConfig.class})
public class MessageSend {

    @Autowired
    public SmsConfig smsConfig;

    public static final String TIMESTAMP = "https://api-v4.mysubmail.com/service/timestamp";
    public static final String TYPE_MD5 = "md5";
    public static final String TYPE_SHA1 = "sha1";

    /**
     * Single send message      StringBuilder
     *
     * @param to      recipient phoneNumber(接收者手机号码)
     * @param content Text message(短信正文)
     * @param params  subMail request other request params(其余参数)
     * @return result
     */
    public String sendCode(@NotNull String to, @NotNull String content, Object params) {
        TreeMap<String, Object> requestData = new TreeMap<>();
        String sign_type = "md5";
        String sign_version = "2";
        Validate.notBlank(to, "`to` must not null");
        Validate.notBlank(content, "`content` must not null");

        //组合请求数据
        requestData.put("appid", smsConfig.getAppid());
        requestData.put("to", to);
        if (sign_type.equals(TYPE_MD5) || sign_type.equals(TYPE_SHA1)) {
            String timestamp = getTimestamp();
            requestData.put("timestamp", timestamp);
            requestData.put("sign_type", sign_type);
            requestData.put("sign_version", sign_version);
            String signStr = smsConfig.getAppid() + smsConfig.getAppkey() + RequestEncoder.formatRequest(requestData) + smsConfig.getAppid() + smsConfig.getAppkey();
            System.out.println(signStr);
            requestData.put("signature", RequestEncoder.encode(sign_type, signStr));
        } else {
            requestData.put("signature", smsConfig.getAppkey());
        }
        requestData.put("content", content);
        if (ObjectUtil.isNotEmpty(params)){
            requestData.put("params", JSONObject.toJSONString(params));
        }
        String data= StringUtils.EMPTY;
        //post请求
        HttpPost httpPost = new HttpPost(smsConfig.getUrl());
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-Type", "application/json");
        StringEntity entity = new StringEntity(JSONObject.toJSONString(requestData), "UTF-8");
        httpPost.setEntity(entity);
        try {
            CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().build();
            log.info("短信发送参数: {}", JSON.toJSONString(requestData));
            HttpResponse response = closeableHttpClient.execute(httpPost);
            HttpEntity httpEntity = response.getEntity();
            if (httpEntity != null) {
                String jsonStr = EntityUtils.toString(httpEntity, "UTF-8");
                log.info("短信返回结果: {}", jsonStr);
                JSONObject jsonObject = JSONObject.parseObject(jsonStr);
                if (ObjectUtil.isEmpty(jsonObject)) {
                    log.error("mysubmail 发送短信失败, 请求参数 = {}", requestData);
                }
                data = jsonObject.getString("status");
                return data;
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        log.debug("content: {}", content);
        return data;
    }

    //获取时间戳
    private static String getTimestamp() {
        CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().build();
        HttpGet httpget = new HttpGet(TIMESTAMP);
        try {
            HttpResponse response = closeableHttpClient.execute(httpget);
            HttpEntity httpEntity = response.getEntity();
            String jsonStr = EntityUtils.toString(httpEntity, "UTF-8");
            if (jsonStr != null) {
                JSONObject json = JSONObject.parseObject(jsonStr);
                return json.getString("timestamp");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static StringBuilder getCode() {
        String str="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        StringBuilder sb=new StringBuilder(4);
        for(int i=0;i<4;i++)
        {
            char ch=str.charAt(new Random().nextInt(str.length()));
            sb.append(ch);
        }
        return sb;

    }
}
风语者!平时喜欢研究各种技术,目前在从事后端开发工作,热爱生活、热爱工作。