整合阿里云短信服务

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;
        }
    }
}
相关推荐
听风者就是我28 分钟前
混合检索:关键词 + 向量的最佳组合
后端·ai编程
supersolon29 分钟前
WSL2(Linux)升级docker
linux·运维·docker·wsl·升级
Memory_荒年43 分钟前
当餐厅后厨也懂分布式:SpringBoot中的重试、限流、熔断与幂等的“四重奏”
java·后端·spring
一殊酒1 小时前
【Docker】常用命令大全及解析
docker·容器·eureka
刘晓飞1 小时前
nestjs 中的 rxjs
后端
Uncertainty!!2 小时前
将docker镜像上传到github镜像存储仓库(GitHub 容器仓库(GHCR)使用流程)
docker·容器·github
编码忘我2 小时前
java策略模式实战之优惠券
java·后端
anzhxu2 小时前
SpringBoot 3.x 整合swagger
java·spring boot·后端
青椒啊2 小时前
DPDK入门到精通(一)
后端
我是谁??2 小时前
Rocky9+ Docker + 容器内Linux桌面环境 + Web远程
运维·docker·容器