阿里云短信(二)

一、创建项目

1、创建模块

service_sms

2、配置 pom.xml

<dependencies>
    <!--阿里云短信-->
    <dependency>
        <groupId>com.aliyun</groupId>
        <artifactId>aliyun-java-sdk-core</artifactId>
    </dependency>
</dependencies>

3、application.yml

resources目录下创建文件

server:
  port: 8150 # 服务端口

spring:
  profiles:
    active: dev # 环境设置
  application:
    name: service-sms # 服务名
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848 # nacos服务地址
#spring: 
  redis:
    host: 192.168.100.100
    port: 6379
    database: 0
    password: 123456 #默认为空
    lettuce:
      pool:
        max-active: 20  #最大连接数,负值表示没有限制,默认8
        max-wait: -1    #最大阻塞等待时间,负值表示没限制,默认-1
        max-idle: 8     #最大空闲连接,默认8
        min-idle: 0     #最小空闲连接,默认0        

#阿里云短信
aliyun:
  sms:
    regionId: cn-hangzhou
    keyId: 你的keyid
    keySecret: 你的keysecret
    templateCode: 你的短信模板code
    signName: 你的短信模板签名

4、为子账户添加授权

AliyunDysmsFullAccess

5、logback-spring.xml

6、创建SpringBoot启动类

package com.atguigu.guli.service.sms;

@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
@ComponentScan({"com.atguigu.guli"})
@EnableDiscoveryClient
public class ServiceSmsApplication {
    public static void main(String[] args) {
        SpringApplication.run(ServiceSmsApplication.class, args);
    }
}

二、配置和工具

1、从配置文件读取常量
创建常量读取工具类:SmsProperties.java

package com.atguigu.guli.service.sms.util;

@Data
@Component
//注意prefix要写到最后一个 "." 符号之前
@ConfigurationProperties(prefix="aliyun.sms")
public class SmsProperties {
    private String regionId;
    private String keyId;
    private String keySecret;
    private String templateCode;
    private String signName;
}

2、引入工具类
common-util中引入工具类:RandomUtils.java、FormUtils.java

三、发送短信

1、创建controller

ApiSmsController.java

package com.atguigu.guli.service.sms.controller;

@RestController
@RequestMapping("/api/sms")
@Api(description = "短信管理")
@CrossOrigin //跨域
@Slf4j
public class ApiSmsController {

    @Autowired
    private SmsService smsService;
    
    @Autowired
    private RedisTemplate redisTemplate;
    
    @GetMapping("send/{mobile}")
    public R getCode(@PathVariable String mobile) throws ClientException {
    
        //校验手机号是否合法
        if(StringUtils.isEmpty(mobile) || !FormUtils.isMobile(mobile)) {
            log.error("请输入正确的手机号码 ");
            throw new GuliException(ResultCodeEnum.LOGIN_PHONE_ERROR);
        }
    
        //生成验证码
        String checkCode = RandomUtils.getFourBitRandom();
        //发送验证码
        smsService.send(mobile, checkCode);
        //将验证码存入redis缓存
        redisTemplate.opsForValue().set(mobile, checkCode, 5, TimeUnit.MINUTES);
    
        return R.ok().message("短信发送成功");
    }
}

2、短信发送业务

接口:SmsService.java

package com.atguigu.guli.service.sms.service;

public interface SmsService {
    void send(String mobile, String checkCode) throws ClientException;
}

实现:SmsServiceImpl.java

package com.atguigu.guli.service.sms.service.impl;

@Service
@Slf4j
public class SmsServiceImpl implements SmsService {

    @Autowired
    private SmsProperties smsProperties;
    
    @Override
    public void send(String mobile, String checkCode) throws ClientException {
    
        //调用短信发送SDK,创建client对象
        DefaultProfile profile = DefaultProfile.getProfile(
                smsProperties.getRegionId(),
                smsProperties.getKeyId(),
                smsProperties.getKeySecret());
        IAcsClient client = new DefaultAcsClient(profile);
    
        //组装请求参数
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", smsProperties.getRegionId());
        request.putQueryParameter("PhoneNumbers", mobile);
        request.putQueryParameter("SignName", smsProperties.getSignName());
        request.putQueryParameter("TemplateCode", smsProperties.getTemplateCode());
    
        Map<String, Object> param = new HashMap<>();
        param.put("code", checkCode);
    
        //将包含验证码的集合转换为json字符串
        Gson gson = new Gson();
        request.putQueryParameter("TemplateParam", gson.toJson(param));
    
        //发送短信
        CommonResponse response = client.getCommonResponse(request);
    
        //得到json字符串格式的响应结果
        String data = response.getData();
    
        //解析json字符串格式的响应结果
        HashMap<String, String> map = gson.fromJson(data, HashMap.class);
        String code = map.get("Code");
        String message = map.get("Message");
    
        //配置参考:短信服务->系统设置->国内消息设置
        //错误码参考:
        //https://help.aliyun.com/document_detail/101346.html?spm=a2c4g.11186623.6.613.3f6e2246sDg6Ry
        //控制所有短信流向限制(同一手机号:一分钟一条、一个小时五条、一天十条)
        if ("isv.BUSINESS_LIMIT_CONTROL".equals(code)) {
            log.error("短信发送过于频繁 " + "【code】" + code + ", 【message】" + message);
            throw new GuliException(ResultCodeEnum.SMS_SEND_ERROR_BUSINESS_LIMIT_CONTROL);
        }
    
        if (!"OK".equals(code)) {
            log.error("短信发送失败 " + " - code: " + code + ", message: " + message);
            throw new GuliException(ResultCodeEnum.SMS_SEND_ERROR);
        }
    }
}
posted @ 2020-10-28 22:48  碧水云天4  阅读(384)  评论(0编辑  收藏  举报