1,目录结构
2,相关依赖
<
!-- https
://mvnrepository.com/artifact/com.alibaba/fastjson
-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.72</version>
</dependency>
<!-- 阿里云发送短息相关 aliyun-java-sdk-core -->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>4.5.2</version>
</dependency>
3,配置类
定义了连接阿里云的key秘钥等信息
@Component
@PropertySource({"classpath:oss.properties"})
public class OSSConfig implements InitializingBean {
@Value("${endpoint}")
private String endpoint
;
@Value("${accessKeyId}")
private String accessKeyId
;
@Value("${accessKeySecret}")
private String accessKeySecret
;
public static String ENDPOINT
;
public static String ACCESSKEYID
;
public static String ACCESSKEYSECRET
;
@Override
public void afterPropertiesSet() throws Exception
{
ENDPOINT
=endpoint
;
ACCESSKEYID
=accessKeyId
;
ACCESSKEYSECRET
=accessKeySecret
;
}
}
4,controller
发送成功后将验证码存在了redis缓存中,设置过期时间,每次发送前先读取,如果不存在就发送,存在就直接返回
@Controller
@CrossOrigin
@RequestMapping("/msm")
public class MsmController {
@Autowired
private MsmService msmService
;
@Autowired
private RedisTemplate
<String,String> redisTemplate
;
@GetMapping("/send/{phone}")
@ResponseBody
public String
sendMsm(@PathVariable("phone") String phone
){
String code
= redisTemplate
.opsForValue().get(phone
);
if (!StringUtils
.isEmpty(code
)){
return "已发送";
}
code
= RandomUtil
.getFourBitRandom();
Map
<String,Object> map
= new HashMap<>();
map
.put("code",code
);
Boolean success
= msmService
.sendMsm(map
,phone
);
if (success
){
redisTemplate
.opsForValue().set(phone
,code
,5, TimeUnit
.MINUTES
);
return "成功";
}
return "失败";
}
}
5,service发送短信
@Service
public class MsmServiceImpl implements MsmService {
@Override
public Boolean
sendMsm(Map
<String, Object> map
, String phone
) {
if (StringUtils
.isEmpty(phone
)){
return false;
}
DefaultProfile profile
= DefaultProfile
.getProfile("default",OSSConfig
.ACCESSKEYID
,OSSConfig
.ACCESSKEYSECRET
);
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("PhoneNumbers",phone
);
request
.putQueryParameter("SignName","纵横江湖");
request
.putQueryParameter("TemplateCode","SMS_195190***");
request
.putQueryParameter("TemplateParam", JSONObject
.toJSONString(map
));
try {
CommonResponse response
= client
.getCommonResponse(request
);
boolean success
= response
.getHttpResponse().isSuccess();
return success
;
} catch (ClientException e
) {
e
.printStackTrace();
}
return false;
}
}