整合阿里云短信服务

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;
        }
    }
}
相关推荐
有梦想的攻城狮35 分钟前
mac本地docker镜像上传指定虚拟机
macos·docker·eureka
程序员爱钓鱼5 小时前
匿名函数与闭包(Anonymous Functions and Closures)-《Go语言实战指南》原创
后端·golang
言之。6 小时前
Go 语言中接口类型转换为具体类型
开发语言·后端·golang
diving deep7 小时前
XML简要介绍
xml·java·后端
宋康7 小时前
Docker 常用命令
docker·容器·eureka
编程乐学(Arfan开发工程师)8 小时前
06、基础入门-SpringBoot-依赖管理特性
android·spring boot·后端
编程乐学(Arfan开发工程师)8 小时前
05、基础入门-SpringBoot-HelloWorld
java·spring boot·后端
橘子海全栈攻城狮9 小时前
【源码+文档+调试讲解】党员之家服务系统小程序1
java·开发语言·spring boot·后端·小程序·旅游
冼紫菜9 小时前
Java开发中使用 RabbitMQ 入门到进阶详解(含注解方式、JSON配置)
java·spring boot·后端·rabbitmq·springcloud
boring_1119 小时前
Apache Pulsar 消息、流、存储的融合
分布式·后端