t com.xtw.SmsApplication;
import com.xtw.component.SmsComponent;
import com.xtw.config.SmsConfig;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(classes= SmsApplication.class)
@Slf4j
public class SmsTest {
@Autowired
private SmsConfig smsConfig;
@Autowired
private SmsComponent smsComponent;
@Test
public void testProperties(){
System.out.println(smsConfig.getAppCode());
}
@Test
public void testSend(){
smsComponent.send("15070159890",smsConfig.getTemplateId(),"652421");
}
}
异步配置
@Configuration
@EnableAsync
public class ThreadPoolTaskConfig {
@Bean("threadPoolTaskExecutor")
public ThreadPoolTaskExecutor threadPoolTaskExecutor(){
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//核心线程数
executor.setCorePoolSize(16);
//阻塞队列容量
executor.setQueueCapacity(3000);
//最大线程数
executor.setMaxPoolSize(300);
//非核心线程空闲时,30s后被释放
executor.setKeepAliveSeconds(30);
//如果allowCoreThreadTimeout=true,核心线程也会被释放
executor.setAllowCoreThreadTimeOut(false);
//线程名前缀
executor.setThreadNamePrefix("自定义线程池-");
//线程溢出,处理方案
//CallerRunsPolicy():交由调用方线程运行,比如 main 线程;如果添加到线程池失败,那么主线程会自己去执行该任务,不会等待线程池中的线程去执行
//AbortPolicy():该策略是线程池的默认策略,如果线程池队列满了丢掉这个任务并且抛出RejectedExecutionException异常。
//DiscardPolicy():如果线程池队列满了,会直接丢掉这个任务并且不会有任何异常
//DiscardOldestPolicy():丢弃队列中最老的任务,队列满了,会将最早进入队列的任务删掉腾出空间,再尝试加入队列
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
//初始化
executor.initialize();
return executor;
}
}
使用异步
@Async("threadPoolTaskExecutor")
public void send(String to,String template,String value) {
String url = String.format(URL_TEMPLATE, to, template, value);
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.set("Authorization","APPCODE "+smsConfig.getAppCode());
HttpEntity<Object> entity = new HttpEntity<>(httpHeaders);
// ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
ResponseEntity<String> responseEntity = restTemplate.exchange("http://localhost:8002/api/visit_stats/v1/str", HttpMethod.POST, entity, String.class);
if(responseEntity.getStatusCode().is2xxSuccessful()){
log.info("验证码发送成功");
}else {
log.error("发送短信验证码失败:{}",responseEntity.getBody());
}
}