这段代码是我自己生成一个uuid和验证码然后把它保存在redis缓存里面,以确保发送的短信是唯一的。
int ret = (int)((Math.random()*9+1)*100000);
String uuid = UUID.randomUUID().toString().replace("-", "");
redisUtils.set(uuid,ret);
Map<String,Object> map=new HashMap<>();
map.put("uuid", uuid);
map.put("ret", ret);
return map;
redis的操作类型,最基本类型是string,可以包含任何数据(图片和序列化的对象都可以),单个值最大上限为1Gbtye;如果只使用String类型,redis可以看作加上持久化特性的memcache。
这时候不得不说一下redis的优点:性能好,也不需要优化,对数据高并发读写,对海量数据的高效率存储和访问,对数据的高扩展性和高可用性(没有表结构,分布式简单)
- 1接下来看发送短信的方法
ServiceResult<Object> verifyResult = senderService.SMSNewCall(map);
- 2具体实现
ServiceResult<Object> result = new ServiceResult<Object>();
try {
SMSSendModel.sendSMSWidthCallable(map);
result.setResult(true);
} catch (Exception e) {
if (e instanceof BusinessException) {
result.setSuccess(false);
result.setMessage(e.getMessage());
} else {
e.printStackTrace();
log.error("短信发送出现未知异常:" + e);
result.setError(ConstantsEJS.SERVICE_RESULT_CODE_SYSERROR, "服务异常,请联系系统管理员。");
result.setMessage("短信发送出现未知异常");
}
}
return result;
3
public void sendSMSWidthCallable(Map<String, Object> map) throws Exception {
//创建一个线程池
ExecutorService pool = Executors.newFixedThreadPool(EjavashopConfig.DEFAULT_RUN_THREAD_NUM);
Object obj = null;
if (map.get("mobile") == null) {
throw new BusinessException("请指定要发送的手机号码");
}
if (map.get("content") == null) {
throw new BusinessException("请指定短信参数");
}
pool.submit(new SMSNewCall(map, TEMPLATE_SMS));
//关闭线程池
pool.shutdown();
}
思想也很简单。就是建一个线程池,然后重写里面的方法
4接下来看重写的方法
class SMSNewCall implements Callable<Object> {
private Map<String, Object> param;
private int type;
SMSNewCall(Map<String, Object> param, int type) {
this.param = param;
this.type = type;
}
@Override
public Object call() throws Exception {
AbstractSMSSender sender = null;
if (type == VERIFY_CODE)
sender = new VerifyCodeSender(param.get("mobile").toString());
else if (type == TEMPLATE_SMS)
sender = new TemplateSMSSender(param.get("mobile").toString(), param.get("content")
.toString());
if (sender == null) {
throw new ArgumentException("参数错误");
}
sender.sendNewMSM(param.get("mobile").toString(), param.get("content").toString());
return null;
}
}
第三方接口
public void sendNewMSM(String phone,String msg) throws Exception{
Map<String,Object> paramMap = new HashMap<>();
paramMap.put("username", "caojinghua");
paramMap.put("passwd", "qiubojun123");
paramMap.put("phone", phone);
paramMap.put("msg", msg);
paramMap.put("needstatus", "true");
paramMap.put("port", "0");
paramMap.put("sendtime", DateUtil.now());
String body = HttpRequest.post("http://www.qybor.com:8500/shortMessage")
.form(paramMap)
.execute()
.body();
if(JSONUtil.isJson(body)) {
JSONObject jsonObject = JSONUtil.parseObj(body);
String str = jsonObject.get("respcode").toString();
System.out.println(str);
}
}