整合阿里云短信服务

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;
        }
    }
}
相关推荐
程序新视界14 分钟前
MySQL的整体架构及功能详解
数据库·后端·mysql
绝无仅有16 分钟前
猿辅导Java面试真实经历与深度总结(二)
后端·面试·github
绝无仅有22 分钟前
猿辅导Java面试真实经历与深度总结(一)
后端·面试·github
Victor3561 小时前
Redis(76)Redis作为缓存的常见使用场景有哪些?
后端
Victor3561 小时前
Redis(77)Redis缓存的优点和缺点是什么?
后端
摇滚侠4 小时前
Spring Boot 3零基础教程,WEB 开发 静态资源默认配置 笔记27
spring boot·笔记·后端
天若有情6737 小时前
Java Swing 实战:从零打造经典黄金矿工游戏
java·后端·游戏·黄金矿工·swin
一只叫煤球的猫7 小时前
建了索引还是慢?索引失效原因有哪些?这10个坑你踩了几个
后端·mysql·性能优化
jianghx10249 小时前
Docker部署ES,开启安全认证并且设置账号密码(已运行中)
安全·elasticsearch·docker·es账号密码设置
magic334165639 小时前
Springboot整合MinIO文件服务(windows版本)
windows·spring boot·后端·minio·文件对象存储