SpringBoot集成阿里云发送短信

步骤:导包,写配置,写启动,写业务类

第一步:导包

 <dependencies>
        
        <dependency>
            <groupId>com.aliyungroupId>
            <artifactId>aliyun-java-sdk-coreartifactId>
        dependency>
    dependencies>

第二步:写配置

server:
  port: 8150 # 服务端口

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

#阿里云短信
aliyun:
  sms:
    regionId: cn-hangzhou
    keyId: LTAI5tMGtKPbL2bCp6zSU4Bz
    keySecret: baAdNzxAjnIMKU3wroxZLlpAACpy02
    templateCode: SMS_183195440
    signName: 我的谷粒在线教育网站

第三步:主启动

@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
@ComponentScan({"com.erke.guli"})
@EnableDiscoveryClient
public class ServiceSmsApplication {

    public static void main(String[] args) {
        SpringApplication.run(ServiceSmsApplication.class, args);
    }
}

第四步:业务类:
准备几个工具:SmsProperties.java获取参数,FormUtils.java:用来校验手机号是否正确,
RandomUtils.java:用来生成验证码

@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;
}
public class FormUtils {
    /**
     * 手机号验证
     */
    public static boolean isMobile(String str) {
        Pattern p = Pattern.compile("^[1][3,4,5,7,8,9][0-9]{9}$"); // 验证手机号
        Matcher m = p.matcher(str);
        return m.matches();
    }
}
public class RandomUtils {

	private static final Random random = new Random();

	private static final DecimalFormat fourdf = new DecimalFormat("0000");

	private static final DecimalFormat sixdf = new DecimalFormat("000000");

	public static String getFourBitRandom() {
		return fourdf.format(random.nextInt(10000));
	}

	public static String getSixBitRandom() {
		return sixdf.format(random.nextInt(1000000));
	}

	/**
	 * 给定数组,抽取n个数据
	 * @param list
	 * @param n
	 * @return
	 */
	public static ArrayList getRandom(List list, int n) {

		Random random = new Random();

		HashMap<Object, Object> hashMap = new HashMap<Object, Object>();

		// 生成随机数字并存入HashMap
		for (int i = 0; i < list.size(); i++) {

			int number = random.nextInt(100) + 1;

			hashMap.put(number, i);
		}

		// 从HashMap导入数组
		Object[] robjs = hashMap.values().toArray();

		ArrayList r = new ArrayList();

		// 遍历数组并打印数据
		for (int i = 0; i < n; i++) {
			r.add(list.get((int) robjs[i]));
			System.out.print(list.get((int) robjs[i]) + "\t");
		}
		System.out.print("\n");
		return r;
	}
}

开始写业务:
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)) {
            throw new GuliException(ResultCodeEnum.LOGIN_PHONE_ERROR);
        }
        //生成验证码
        String code = RandomUtils.getFourBitRandom();

        //发送验证码
        smsService.send(mobile,code);
        //将验证码存储到redis中

        redisTemplate.opsForValue().set(mobile,code,5, TimeUnit.MINUTES);
        //将结果返回

        return R.ok().message("短信发送成功!!");
    }

}

service:

public interface SmsService {
    //发送验证码
    void send(String mobile,String code) throws ClientException;
}

seviceimpl

@Service
@Slf4j
public class SmsServiceImpl implements SmsService {

    @Autowired
    private SmsProperties smsProperties;

    //发送验证码
    @Override
    public void send(String mobile, String code) throws ClientException {
        //调用SDK短信发送,创建Client对象
        DefaultProfile profile = DefaultProfile.getProfile(
                smsProperties.getRegionId(),
                smsProperties.getKeyId(),
                smsProperties.getKeySecret()
        );
        //组装请求参数
        DefaultAcsClient 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> map = new HashMap<>();
        map.put("code",code);

        //格式化参数对象
        Gson gson = new Gson();
        request.putQueryParameter("TemplateParam", gson.toJson(map));

        //发送短信
        CommonResponse response = client.getCommonResponse(request);

        //得到json字符串格式的响应结果
        String data = response.getData();

        HashMap<String,String> hashMap = gson.fromJson(data, HashMap.class);
        String code1 = hashMap.get("code");
        String message = hashMap.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);
        }
    }
}

你可能感兴趣的:(spring,boot,阿里云,java)