整合阿里云短信服务

1、开通短信服务、申请签名、模板

2、具体整合

(1)创建新模块service_msm

(2)创建配置文件

java 复制代码
# 服务端口
server.port=8005
# 服务名
spring.application.name=service-msm
# mysql数据库连接
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/guli?serverTimezone=GMT%2B8
spring.datasource.username=guli
spring.datasource.password=123123
spring.redis.host=192.168.140.132
spring.redis.port=6379
spring.redis.database= 0
spring.redis.timeout=1800000
spring.redis.lettuce.pool.max-active=20
spring.redis.lettuce.pool.max-wait=-1
#最大阻塞等待时间(负数表示没限制)
spring.redis.lettuce.pool.max-idle=5
spring.redis.lettuce.pool.min-idle=0
#最小空闲
#返回json的全局时间格式
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8
#配置mapper xml文件的路径
mybatis-plus.mapper-locations=classpath:com/atguigu/msmservice/mapper/xml/*.xml
#mybatis日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

(3)创建启动类

java 复制代码
package com.atguigu.msmservice;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;

@ComponentScan({"com.atguigu"})
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)//取消数据源自动配置
public class ServiceMsmApplication {
    public static void main(String[] args) {
        SpringApplication.run(ServiceMsmApplication.class, args);
    }
}

(4)引入依赖

java 复制代码
<dependencies>
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
    </dependency>
    <dependency>
        <groupId>com.aliyun</groupId>
        <artifactId>aliyun-java-sdk-core</artifactId>
    </dependency>
</dependencies>

(5)编写MsmApiController

java 复制代码
@Api(description="短信发送管理")
@RestController
@RequestMapping("/edumsm/msm")
@CrossOrigin
public class MsmApiController {
    @Autowired
    private MsmService msmService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @ApiOperation(value = "根据手机号发送验证码")
    @GetMapping("send/{phone}")
    public R sendMsmPhone(@PathVariable String phone){
        //1 从redis里根据手机号获取数据
        String rphone = redisTemplate.opsForValue().get(phone);
        //2 如果能取出数据直接返回
        if(!StringUtils.isEmpty(rphone)){
            return R.ok();
        }
        //3 如果取不出数据,调接口发送短信
        //3.1生成验证码,随机四位数
        String code = RandomUtil.getFourBitRandom();
        //3.2把生成的验证码封装到map
        Map<String,String> map = new HashMap<>();
        map.put("code",code);
        //3.3调用service方法
        boolean isSuccess = msmService.sendMsm(phone,map);
        //4 如果发送成功,把校验码往redis里存一份
        if(isSuccess){
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return R.ok();
        }else {
            return R.error().message("发送短信失败");
        }
    }
}

(6)编写MsmService接口

java 复制代码
package com.atguigu.msmservice.service;

import java.util.Map;

public interface MsmService {
    public boolean send(String PhoneNumbers, String templateCode, Map<String, Object> param);
}

(7)实现MsmService接口

java 复制代码
@Service
public class MsmServiceImpl implements MsmService {
    //根据手机号发送验证码
    @Override
    public boolean sendMsm(String phone, Map<String, String> map) {
        //0 判断手机号
        if(StringUtils.isEmpty(phone)) return false;
        //1 创建初始化对象
        DefaultProfile profile =
                DefaultProfile.getProfile("default", "LTAI3buexRAagkdy", "A6hpWJbF3Zz6wj3jxuBe40Mwryt1Zz");
        IAcsClient client = new DefaultAcsClient(profile);
        //2 创建request对象
        CommonRequest request = new CommonRequest();
        //3 向request里设置参数
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");

        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", "我的谷粒在线教育网站");
        request.putQueryParameter("TemplateCode", "SMS_183195440");
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(map));

        
        try {
            //4 调用初始化兑现方法实现发送
            CommonResponse response = client.getCommonResponse(request);
            //5 通过response获取发送是否成功
            boolean success = response.getHttpResponse().isSuccess();
            return success;
        } catch (ClientException e) {
            e.printStackTrace();
            return false;
        }
    }
}
相关推荐
long3161 分钟前
Aho-Corasick 模式搜索算法
java·数据结构·spring boot·后端·算法·排序算法
rannn_11128 分钟前
【苍穹外卖|Day4】套餐页面开发(新增套餐、分页查询、删除套餐、修改套餐、起售停售)
java·spring boot·后端·学习
短剑重铸之日38 分钟前
《设计模式》第十一篇:总结
java·后端·设计模式·总结
说实话起个名字真难啊1 小时前
用docker来安装openclaw
docker·ai·容器
恬静的小魔龙1 小时前
【群晖Nas】群晖Nas中实现SVN Server功能、Docker/ContainerManager等
docker·svn·容器
坚果派·白晓明1 小时前
在鸿蒙设备上快速验证由lycium工具快速交叉编译的C/C++三方库
c语言·c++·harmonyos·鸿蒙·编程语言·openharmony·三方库
Dragon Wu2 小时前
Spring Security Oauth2.1 授权码模式实现前后端分离的方案
java·spring boot·后端·spring cloud·springboot·springcloud
Zfox_2 小时前
CANN Catlass 算子模板库深度解析:高性能 GEMM 融合计算、Cube Unit Tiling 机制与编程范式实践
docker·云原生·容器·eureka
一个有梦有戏的人2 小时前
Python3基础:进阶基础,筑牢编程底层能力
后端·python
爬山算法2 小时前
Hibernate(88)如何在负载测试中使用Hibernate?
java·后端·hibernate