您的位置:首页 > 编程语言 > Java开发

利用spring线程池ThreadPoolTaskExecutor发送手机短信

2016-07-14 16:08 696 查看
import java.awt.image.BufferedImage;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import redis.clients.jedis.JedisCluster;

/**
* 激活用户
*
* @author skyler
* @time 2016-05-23
*/
@RestController
@RequestMapping("version{vv:\\d+}/user")
@Validated
public class UserController {

private static Logger log = LoggerFactory.getLogger(UserController.class);

@Resource
private ThreadPoolTaskExecutor taskExecutor;

@RequestMapping("/send_msg")
public ResponseJson sendMsg(long id) throws InterruptedException, ExecutionException {

//FutureTask<String> futureTask = new FutureTask<>(new MyCallable(200));
System.out.println(taskExecutor.getActiveCount());
taskExecutor.submit(new MyCallable(10));
Future<Object> f = taskExecutor.submit(new MyCallable(5));
System.out.println(f.get());
//taskExecutor.shutdown();
return new ResponseJson();
}

class MyCallable implements Callable<Object> {
private int id;

public MyCallable(int id) {
this.id = id;
}

@Override
public String call() throws Exception {
System.out.println("call()方法被调用!" + Thread.currentThread().getName());
// Thread.sleep(200);
List<Integer> list = new ArrayList<Integer>(10);
List<MessageInfo> msgList = new ArrayList<MessageInfo>();
// for (Integer i : list) {
// 1.组装短信对象
Message info = new Message("******", "您的验证码是:"
+ RandomStringUtils.random(6, true, true));
Message info2 = new Message("*******", "您的验证码是:
+ RandomStringUtils.random(6, true, true));
// 2.放入list中,为批量发送短信做准备
msgList.add(info);
msgList.add(info2);
// 3.组装staff_invite对象
// }

SenderUtils.batchSend(msgList);
return "结果是:" + id;
}
}
}

配置类:

@Bean
public ThreadPoolTaskExecutor taskExecutor() {
ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
// 线程池所使用的缓冲队列
pool.setQueueCapacity(queueCapacity);
// 线程池维护线程的最少数量
pool.setCorePoolSize(corePoolSize);
// 线程池维护线程的最大数量
pool.setMaxPoolSize(maxPoolSize);
// 线程池维护线程所允许的空闲时间
pool.setKeepAliveSeconds(keepAliveSeconds);
// pool.setWaitForTasksToCompleteOnShutdown(true);
System.out.println("------------ThreadPoolTaskExecutor init--------------------");

return pool;
}


发送短信工具类,短信发送需要向第三方购买短信服务,这里用的是创瑞的

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SenderUtils {

private static Logger log = LoggerFactory.getLogger(SenderUtils.class);

/**
* 发送短信
*
* @param content
*            要发送的短信内容
* @param phoneNumber
*            发送目的号码
* @throws IOException
*             {@link send.MessageInfo}
* @time 2016-05-20
*/
public static void send(MessageInfo info) throws IOException {

// 创建StringBuffer对象用来操作字符串
StringBuffer sb = new StringBuffer(MessageInfo.url);

// 向StringBuffer追加用户名
sb.append("name=").append(MessageInfo.name);

// 向StringBuffer追加密码(登陆网页版,在管理中心--基本资料--接口密码,是28位的)
sb.append("&pwd=").append(MessageInfo.pwd);

// 向StringBuffer追加手机号码
sb.append("&mobile=").append(info.getMobile());

// 向StringBuffer追加消息内容转URL标准码
sb.append("&content=" + URLEncoder.encode(info.getContent(), "UTF-8"));

// 追加发送时间,可为空,为空为及时发送
sb.append("&stime=").append(info.getStime());

// 加签名
sb.append("&sign=" + URLEncoder.encode(info.getSign(), "UTF-8"));

// type为固定值pt extno为扩展码,必须为数字 可为空
sb.append("&type=").append(info.getType()).append("&extno=").append(info.getExtno());
// 创建url对象
// String temp = new String(sb.toString().getBytes("GBK"),"UTF-8");
System.out.println("sb:" + sb.toString());
URL url = new URL(sb.toString());

// 打开url连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();

// 设置url请求方式 ‘get’ 或者 ‘post’
connection.setRequestMethod("POST");

// 发送
InputStream is = url.openStream();

// 转换返回值
String returnStr = SenderUtils.convertStreamToString(is);

// 返回结果为‘0,20140009090990,1,提交成功’ 发送成功 具体见说明文档
log.info(returnStr);
// 返回发送结果
}

public static void batchSend(List<MessageInfo> list) throws IOException {

// 创建StringBuffer对象用来操作字符串
StringBuffer sb = new StringBuffer(MessageInfo.url);

// 向StringBuffer追加用户名
sb.append("name=").append(MessageInfo.name);

// 向StringBuffer追加密码(登陆网页版,在管理中心--基本资料--接口密码,是28位的)
sb.append("&pwd=").append(MessageInfo.pwd);

String contents = "";

// 追加发送时间,可为空,为空为及时发送
sb.append("&stime=").append("");

// 加签名
sb.append("&sign=" + URLEncoder.encode("公司名", "UTF-8"));

// type为固定值pt extno为扩展码,必须为数字 可为空
sb.append("&type=").append("gx").append("&extno=").append("");

// 你好张三#@#13566666666#@@#你好李四#@#13999999999
for (MessageInfo info : list) {
contents += info.getContent() + "#@#" + info.getMobile() + "#@@#";
}

String c = "";
if (contents.endsWith("#@@#")) {
c = contents.substring(0, contents.lastIndexOf("#@@#"));
}
// 向StringBuffer追加手机号码
// sb.append("&mobile=").append(mobiles);

// 向StringBuffer追加消息内容转URL标准码
sb.append("&content=" + URLEncoder.encode(c, "UTF-8"));

// 创建url对象
// String temp = new String(sb.toString().getBytes("GBK"),"UTF-8");
System.out.println("sb:" + sb.toString());
URL url = new URL(sb.toString());

// 打开url连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();

// 设置url请求方式 ‘get’ 或者 ‘post’
connection.setRequestMethod("POST");

// 发送
InputStream is = url.openStream();

// 转换返回值
String returnStr = SenderUtils.convertStreamToString(is);

// 返回结果为‘0,20140009090990,1,提交成功’ 发送成功 具体见说明文档
log.info(returnStr);
// 返回发送结果

}

public static String batchSend(String msgUrl) throws IOException {

// String temp = new String(sb.toString().getBytes("GBK"),"UTF-8");
System.out.println("msgUrl:" + msgUrl);
URL url = new URL(msgUrl);

// 打开url连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();

// 设置url请求方式 ‘get’ 或者 ‘post’
connection.setRequestMethod("POST");

// 发送
InputStream is = url.openStream();

// 转换返回值
String returnStr = SenderUtils.convertStreamToString(is);

// 返回结果为‘0,20140009090990,1,提交成功’ 发送成功 具体见说明文档
log.info(returnStr);
// 返回发送结果
return returnStr;
}

/**
* 转换返回值类型为UTF-8格式.
*
* @param is
* @return
*/
public static String convertStreamToString(InputStream is) {
StringBuilder sb1 = new StringBuilder();
byte[] bytes = new byte[4096];
int size = 0;

try {
while ((size = is.read(bytes)) > 0) {
String str = new String(bytes, 0, size, "UTF-8");
sb1.append(str);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb1.toString();
}
}


短信发送对象

/**
* 发送信息类,用于发送短信
*
* @time 2016-05-20
* @author skyler
*
*/
public class Message {

public final static String url = "http://web.cr6868.com/asmx/smsservice.aspx?";
public final static String name = "********";
public final static String pwd = "********";

private String sign = "公司";
private String mobile = "";
private String content = "";
private String stime = "";
private String type = "pt";
private String extno = "";

public Message() {
}

public Message(String mobile, String content) {
super();
this.mobile = mobile;
this.content = content;
}

public Message(String sign, String mobile, String content, String stime, String type, String extno) {
super();
this.sign = sign;
this.mobile = mobile;
this.content = content;
this.stime = stime;
this.type = type;
this.extno = extno;
}

public String getSign() {
return sign;
}

public void setSign(String sign) {
this.sign = sign;
}

public String getMobile() {
return mobile;
}

public void setMobile(String mobile) {
this.mobile = mobile;
}

public String getContent() {
return content;
}

public void setContent(String content) {
this.content = content;
}

public String getStime() {
return stime;
}

public void setStime(String stime) {
this.stime = stime;
}

public String getType() {
return type;
}

public void setType(String type) {
this.type = type;
}

public String getExtno() {
return extno;
}

public void setExtno(String extno) {
this.extno = extno;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息