自学内容网 自学内容网

定时任务启动腾讯云自动发送短信(双数据源)

SmsController:

package com.todod.warning.controller;

import com.todod.warning.service.ISmsService;
import com.todod.warning.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping("/edusms/sms")
@CrossOrigin
public class SmsController {
    @Autowired
    private ISmsService smsService;

    @GetMapping("send/{phone}")
    public R sendSms(
            @PathVariable String phone, // 路径变量,用于接收URL中的电话号码
            @RequestParam(value = "templateParam", required = false) String[] templateParams // 查询参数,用于接收URL中的模板参数数组
    ){
        // 调用service发送短信的方法,传入电话号码和模板参数数组
        boolean isSend = smsService.send(phone, templateParams);

        // 根据发送结果返回相应的响应
        if (isSend) {
            return R.ok(); // 发送成功,返回成功响应
        } else {
            return R.error("短信发送失败!"); // 发送失败,返回错误响应
        }
    }
}

ISmsService:

package com.todod.warning.service;

import java.util.List;

public interface ISmsService {
    boolean send(String phone, String[] templateParam);
}

SmsServiceImpl:

package com.todod.warning.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sms.v20210111.SmsClient;
import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
import com.todod.warning.service.ISmsService;
import com.todod.warning.utils.ConstantSmsUtils;
import com.todod.warning.utils.RandomUtil;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SmsServiceImpl implements ISmsService {

    //发送短信的方法
    @Override
    public boolean send(String phone, String[] templateParam) {
        //判断手机号是否为空
        if (StringUtils.isEmpty(phone)){
            return false;
        }
        try{
            // 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey,此处还需注意密钥对的保密
            // 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
            Credential cred = new Credential("AKIDBAQhnfJlOs8OTJtEOBk5HJMFxZ0Cuc8S", "Jbv2uXzDF4gLtLbgZHm6YovvhFbjdXKt");
            // 实例化一个http选项,可选的,没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("sms.tencentcloudapi.com");
            // 实例化一个client选项,可选的,没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的  第二个参数是地域信息
            SmsClient client = new SmsClient(cred, "ap-beijing", clientProfile);
            // 实例化一个请求对象,每个接口都会对应一个request对象
            SendSmsRequest req = new SendSmsRequest();
            //设置固定的参数
            req.setSmsSdkAppId("1400953332");// 短信应用ID: 短信SdkAppId在 [短信控制台] 添加应用后生成的实际SdkAppId
            req.setSignName("天津浪淘科技");//短信签名内容: 使用 UTF-8 编码,必须填写已审核通过的签名
            req.setTemplateId("2321690");//模板 ID: 必须填写已审核通过的模板 ID
            /* 用户的 session 内容: 可以携带用户侧 ID 等上下文信息,server 会原样返回 */


            //设置发送相关的参数
            String[] phoneNumberSet1 = {"+86"+phone};
            req.setPhoneNumberSet(phoneNumberSet1);//发送的手机号
            req.setTemplateParamSet(templateParam);//发送验证码

            //发送短信
            // 返回的resp是一个SendSmsResponse的实例,与请求对象对应
            SendSmsResponse resp = client.SendSms(req);
            System.out.println("resp"+resp);
            // 输出json格式的字符串回包
            System.out.println(SendSmsResponse.toJsonString(resp));
            return true;
        } catch (TencentCloudSDKException e) {
            e.printStackTrace();
            return false;
        }
    }
}


定时任务:

package com.todod.warning.utils;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.todod.warning.controller.SmsController;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;

@Component
public class ScheduleTask {

    private static final Logger logger = LoggerFactory.getLogger(ScheduleTask.class);

    @Autowired
    @Qualifier("clickhouseJdbcTemplate")
    private JdbcTemplate clickhouseJdbcTemplate;

    @Autowired
    private SmsController smsController;

    @Value("${tencent.sms.phone}")
    private String phone;

    //    @Scheduled(cron = "0 0 3 * * ?")
    @Scheduled(fixedRate = 10000)
    @DS("slave")
    public void doTaskEveryDayAtNoon() {
        try {
            String clickhouseUrl = "jdbc:clickhouse://192.168.1.106:8123/qbdata_db";
            String user = "qbdata_db";
            String password = "qbdata_db";
            try (Connection connection = DriverManager.getConnection(clickhouseUrl, user, password);
                 PreparedStatement statement = connection.prepareStatement(
                         "SELECT count(*) FROM base_yw WHERE db_batch = formatDateTime(yesterday(), '%Y-%m-%d') AND api_type = ?")) {

                statement.setString(1, "1"); // Set the api_type value
                try (ResultSet resultSet = statement.executeQuery()) {
                    if (resultSet.next()) {
                        int count1 = resultSet.getInt(1);
                        if (count1 == 0) {
                            //获取昨天的数据
//                LocalDate yesterdayDate = LocalDate.now().minusDays(1);
                            LocalDate localDate = LocalDate.now();
                            int year = localDate.getYear(); // 获取年份
                            int month = localDate.getMonthValue(); // 获取月份(1-12)
                            int day = localDate.getDayOfMonth(); // 获取日(1-31)
                            String errorMsg = "蜜度接口数据获取失败";
                            String[] templateParam = new String[4];
                            templateParam[0] = String.valueOf(year);
                            templateParam[1] = String.valueOf(month);
                            templateParam[2] = String.valueOf(day);
                            templateParam[3] = errorMsg;
                            smsController.sendSms(phone, templateParam);
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            try (Connection connection = DriverManager.getConnection(clickhouseUrl, user, password);
                 PreparedStatement statement = connection.prepareStatement(
                         "SELECT count(*) FROM base_yw WHERE db_batch = formatDateTime(yesterday(), '%Y-%m-%d') AND api_type = ?")) {

                statement.setString(1, "2"); // Set the api_type value
                try (ResultSet resultSet = statement.executeQuery()) {
                    if (resultSet.next()) {
                        int count2 = resultSet.getInt(1);
                        if (count2 == 0) {
                            //获取昨天的数据
//                LocalDate yesterdayDate = LocalDate.now().minusDays(1);
                            LocalDate localDate = LocalDate.now();
                            int year = localDate.getYear(); // 获取年份
                            int month = localDate.getMonthValue(); // 获取月份(1-12)
                            int day = localDate.getDayOfMonth(); // 获取日(1-31)
                            String errorMsg = "蚁坊接口数据获取失败";
                            String[] templateParam = new String[4];
                            templateParam[0] = String.valueOf(year);
                            templateParam[1] = String.valueOf(month);
                            templateParam[2] = String.valueOf(day);
                            templateParam[3] = errorMsg;
                            smsController.sendSms(phone, templateParam);
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            try (Connection connection = DriverManager.getConnection(clickhouseUrl, user, password);
                 PreparedStatement statement = connection.prepareStatement(
                         "SELECT count(*) FROM base_yw WHERE db_batch = formatDateTime(yesterday(), '%Y-%m-%d') AND api_type = ?")) {

                statement.setString(1, "3"); // Set the api_type value
                try (ResultSet resultSet = statement.executeQuery()) {
                    if (resultSet.next()) {
                        int count3 = resultSet.getInt(1);
                        if (count3 == 0) {
                            //获取昨天的数据
//                LocalDate yesterdayDate = LocalDate.now().minusDays(1);
                            LocalDate localDate = LocalDate.now();
                            int year = localDate.getYear(); // 获取年份
                            int month = localDate.getMonthValue(); // 获取月份(1-12)
                            int day = localDate.getDayOfMonth(); // 获取日(1-31)
                            String errorMsg = "五节接口数据获取失败";
                            String[] templateParam = new String[4];
                            templateParam[0] = String.valueOf(year);
                            templateParam[1] = String.valueOf(month);
                            templateParam[2] = String.valueOf(day);
                            templateParam[3] = errorMsg;
                            smsController.sendSms(phone, templateParam);
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}

R:

package com.todod.warning.utils;

public class R<T> {
    private int code;
    private String message;
    private T data;

    private R(int code, String message) {
        this.code = code;
        this.message = message;
    }

    public static <T> R<T> ok() {
        return new R<>(200, "成功");
    }

    public static <T> R<T> error(String message) {
        return new R<>(500, message);
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
}

yaml:

server.port=9099

#设置é»è®¤çæ°æ®æºæèæ°æ®æºç»,é»è®¤å¼å³ä¸ºmaster
spring.datasource.dynamic.primary=master
#设置严格模å¼,é»è®¤falseä¸å¯å¨. å¯å¨åå¨æªå¹éå°æå®æ°æ®æºæ¶åä¼æåºå¼å¸¸,ä¸å¯å¨åå¨æªå¹éå°æå®æ°æ®æºæ¶å使ç¨é»è®¤æ°æ®æº
spring.datasource.dynamic.strict=false  
spring.datasource.dynamic.datasource.master.url=jdbc:mysql://localhost:3306/qcfx_db?useSSL=true&allowPublicKeyRetrieval=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
spring.datasource.dynamic.datasource.master.username=root
spring.datasource.dynamic.datasource.master.password=xiao1021
spring.datasource.dynamic.datasource.master.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.dynamic.datasource.slave.url=jdbc:clickhouse://192.168.1.106:8123/qbdata_db
spring.datasource.dynamic.datasource.slave.username=qbdata_db
spring.datasource.dynamic.datasource.slave.password=qbdata_db
spring.datasource.dynamic.datasource.slave.driver-class-name=ru.yandex.clickhouse.ClickHouseDriver


server.tomcat.protocolHeader=x-forwarded-proto
server.tomcat.remoteIpHeader=x-forwarded-for
server.tomcat.basedir=
server.tomcat.backgroundProcessorDelay=30

spring.thymeleaf.prefix=classpath:/static/
spring.thymeleaf.suffix=.html
spring.thymeleaf.cache=false  

mybatis-plus.mapper-locations: classpath:mapper/*Mapper.xml

spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8

#è¾è®¯äºç­ä¿¡æå¡åæ°
#è¾è®¯äºè´¦æ·secretIdï¼secretKey
tencent.sms.keyId=AKIDBAQhnfJlOs8OTJtEOBk5HJMFxZ0Cuc8S
tencent.sms.keysecret=Jbv2uXzDF4gLtLbgZHm6YovvhFbjdXKt
tencent.sms.phone=18833703503
#ç­ä¿¡åºç¨ID: ç­ä¿¡SdkAppIdå¨ [ç­ä¿¡æ§å¶å°] æ·»å åºç¨åçæçå®éSdkAppId
tencent.sms.smsSdkAppId=1400952592
#ç­ä¿¡ç­¾åå容: ä½¿ç¨ UTF-8 ç¼ç ï¼å¿é¡»å¡«å已审核éè¿çç­¾å
tencent.sms.signName="天津浪æ·ç§æ"
#æ¨¡æ¿ ID: å¿é¡»å¡«å已审核éè¿çæ¨¡æ¿ ID
tencent.sms.templateId=2321690
# è¾è®¯äºç­ä¿¡æå¡
tencent:
sms:
secret-id: "AKIDBAQhnfJlOs8OTJtEOBk5HJMFxZ0Cuc8S"
secret-key:"Jbv2uXzDF4gLtLbgZHm6YovvhFbjdXKt"
sdk-app-id: 1400952592
sign-name: "天津浪æ·ç§æ"
# 模æ¿IDæ å°ï¼keyä»»æ设置ï¼value为审核éè¿æ¨¡æ¿ID
template-id-map:
register: "2321690"
forget: "2321690"

TencentSmsProperties:

package com.todod.warning.model;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Map;

@Data // lombok 省略get/set方法
@Component
@ConfigurationProperties(prefix = "tencent.sms")  // 读取配置文件中tencent.sms 为前缀的配置信息
public class TencentSmsProperties {
    /** 腾讯云账户密钥对secretId */
    private String secretId;

    /** 腾讯云账户密钥对secretKey */
    private String secretKey;

    /** 短信应用ID: 短信SdkAppId在 [短信控制台] 添加应用后生成的实际SdkAppId(位于[应用管理]中的[应用列表]),示例: 1400006666 (1400开头)*/
    private String sdkAppId;

    /** 短信签名内容: 使用 UTF-8 编码,必须填写已审核通过的签名,签名信息可登录 [短信控制台] 查看 */
    private String signName;

    /** 模板 ID 哈希表: 必须填写已审核通过的模板 ID。模板ID可登录 [短信控制台] 查看
     *  key: 模板名称(自定义);value: 模板 ID(腾讯云已通过模板)
     * */
    private Map<String, String> templateIdMap;

    /** 国际/港澳台短信 SenderId: 国内短信填空,默认未开通(国内短信不需要填写此项),如需开通请联系 [sms helper] */
    String senderid = "";


    /**短信号码扩展号: 默认未开通,如需开通请联系 [sms helper]   个人不需要填写*/
    private String extendCode = "";

}


原文地址:https://blog.csdn.net/qq_50684356/article/details/144357012

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!