java线程池的使用-发送短信验证码

package com.wei.service.sms.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import javax.annotation.PostConstruct;

import org.apache.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.wei.constants.CacheConstant;
import com.wei.constants.SysConstants;
import com.wei.service.CacheService;
import com.wei.service.sms.SmsService;
import com.wei.util.DateUtil;
import com.wei.util.ErrorCode;
import com.wei.util.HttpResult;
import com.wei.util.HttpUtils;
import com.wei.util.VerifyUtils;
/**
 * @author changning
 */
@SuppressWarnings("unchecked")
@Service("smsService")
public class SmsServiceImpl implements SmsService {
	private static final transient Logger logger = LoggerFactory.getLogger(SmsServiceImpl.class);
	@Autowired@Qualifier("cacheService")
	private CacheService cacheService;
	private static final String SMS_URL = "http://116.213.72.20/SMSHttpService/send.aspx";
	private static final String SMS_USERNAME = "bdxx1";
	private static final String SMS_PASSWORD = "bd111111";
	private ThreadPoolExecutor smsPoolExecutor;
	private int corePoolSize = 5;
	private int maximumPoolSize = 10;
	
	@Override
	public void sendSms(String type, String mobile, String content) {
		if (type.equals(SysConstants.SMS_TYPE_VERIFYMOBILE)) {
			smsPoolExecutor.execute(new VerifyMobileSmsTask(mobile));
		}
	}

	@PostConstruct
	public void init() {
		BlockingQueue<Runnable> taskQueue = new ArrayBlockingQueue<Runnable>(3000);
		smsPoolExecutor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, 30, TimeUnit.SECONDS, taskQueue);
		smsPoolExecutor.allowCoreThreadTimeOut(false);
	}
	
	private ErrorCode<String> sendVerifyMobileSms(String mobile) {
		if (!VerifyUtils.isMobileNo(mobile)) {
			return ErrorCode.CODE_PARAM_ERROR_MOBILE;
		}
		String mobileValidateCode = String.valueOf(Math.random()*9000+1000).substring(0, 4);
		String content = SysConstants.SMS_TITLE_VERIFYMOBILE + mobileValidateCode;
		Map<String,String> params=new HashMap<String,String>();
		params.put("username", SMS_USERNAME);
		params.put("password", SMS_PASSWORD);
		params.put("mobile", mobile);
		params.put("content", content);
		params.put("extcode", "");
		params.put("senddate",DateUtil.formatTimestamp(new Date()));
		params.put("batchID", "");
		HttpResult result = HttpUtils.postUrlAsString(SMS_URL, params);
		if (result.getStatus() == HttpStatus.SC_OK && result.getResponse().equals(SysConstants.SMS_SUCCESS)) {
			String key = SysConstants.CACHE_KEY_VERIFYMOBILE + mobile;
			cacheService.set(CacheConstant.REGION_TENMIN, key, mobileValidateCode);
			return ErrorCode.getSuccess(mobile + SysConstants.SMS_VERIFYMOBILE_SUCCESS);
		} else {
			return ErrorCode.getFailure(mobile + SysConstants.SMS_VERIFYMOBILE_ERROR);
		}
	}
	
	private class VerifyMobileSmsTask implements Runnable {
		private String mobile;
		public VerifyMobileSmsTask(String mobile) {
			this.mobile = mobile;
		}
		@Override
		public void run() {
			ErrorCode<String> code = sendVerifyMobileSms(mobile);
			if (!code.isSuccess()) {
				logger.error(code.getMsg());
			}
		}
	}
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
发送短信验证码,你需要使用短信服务提供商的 API。以下是一个使用阿里云短信服务的示例代码: ```java import java.util.Random; import com.aliyuncs.DefaultAcsClient; import com.aliyuncs.IAcsClient; import com.aliyuncs.exceptions.ClientException; import com.aliyuncs.profile.DefaultProfile; import com.aliyuncs.profile.IClientProfile; import com.aliyuncs.sms.model.v20170605.SendSmsRequest; import com.aliyuncs.sms.model.v20170605.SendSmsResponse; public class SmsSender { private static final String ACCESS_KEY_ID = "your_access_key_id"; private static final String ACCESS_KEY_SECRET = "your_access_key_secret"; private static final String SIGN_NAME = "your_sign_name"; private static final String TEMPLATE_CODE = "your_template_code"; public static void sendSms(String phone) throws ClientException { IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", ACCESS_KEY_ID, ACCESS_KEY_SECRET); DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", "Sms", "sms.aliyuncs.com"); IAcsClient client = new DefaultAcsClient(profile); SendSmsRequest request = new SendSmsRequest(); request.setPhoneNumbers(phone); request.setSignName(SIGN_NAME); request.setTemplateCode(TEMPLATE_CODE); String code = String.format("%04d", new Random().nextInt(10000)); request.setTemplateParam("{\"code\":\"" + code + "\"}"); SendSmsResponse response = client.getAcsResponse(request); System.out.println("短信发送结果:" + response.getCode()); } } ``` 在上面的代码中,你需要替换以下常量: - `your_access_key_id`:你的阿里云 Access Key ID - `your_access_key_secret`:你的阿里云 Access Key Secret - `your_sign_name`:你在阿里云短信服务中设置的签名名称 - `your_template_code`:你在阿里云短信服务中设置的短信模板编号 使用时,你只需要调用 `sendSms` 方法并传入要发送的手机号码即可。该方法会生成一个 4 位的随机验证码并发送到指定的手机号码上。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值