场景:
业务开发中,有时需要通过短信验证就行身份验证,此时可以调用阿里云的短信服务
步骤一:导入依赖和配置参数
<dependency> <groupId>com.aliyun</groupId> <artifactId>dysmsapi20170525</artifactId> <version>2.0.23</version> </dependency>
//创建一个参数配置类
@Data //从application.yml中找到对应的值,自动映射到配置类的属性中 @ConfigurationProperties(prefix = "aliyun.sms") public class AliyunSMSProperties { private String accessKeyId; private String accessKeySecret; private String endpoint; }
//在application.yml中添加
aliyun: sms: access-key-id: <自己的> access-key-secret: <自己的> endpoint: dysmsapi.aliyuncs.com
步骤二:配置阿里云对象
@Configuration //启用之前的参数配置类,使下面创建的配置类自带参数 @EnableConfigurationProperties(AliyunSMSProperties.class) //此注解意为:只有当application.yml中参数不为空时,才会进行实例化 //如果此配置类只被当前包下的的启动类启动,则可不加 @ConditionalOnProperty(name = "aliyun.sms.endpoint") public class AliyunSMSConfiguration { @Autowired private AliyunSMSProperties aliyunSMSProperties; @Bean public Client createClient(){ Config config = new Config(); config.setAccessKeyId(aliyunSMSProperties.getAccessKeyId()); config.setAccessKeySecret(aliyunSMSProperties.getAccessKeySecret()); config.setEndpoint(aliyunSMSProperties.getEndpoint()); try { return new Client(config); } catch (Exception e) { throw new RuntimeException(e); } } }
步骤三:创建阿里云对象并使用
@Service
public class SmsServiceImpl implements SmsService {
//创建阿里云对象,创建时,会自动调用步骤二,为此对象进行参数配置
@Autowired
private Client client;
//主要调用此方法,就可以发送短信
@Override
public void sendCode(String phone, String code) {
//固定写法
SendSmsRequest smsRequest = new SendSmsRequest();
smsRequest.setPhoneNumbers(phone);
smsRequest.setSignName("阿里云短信测试");
smsRequest.setTemplateCode("SMS_154950909");
smsRequest.setTemplateParam("{\"code\":\"" + code + "\"}");
try {
client.sendSms(smsRequest);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}