下面列出了怎么用org.springframework.scheduling.annotation.Async的API类实例代码及写法,或者点击链接到github查看源代码。
@Async
public void xzbcdm(String url, String player) {
String json = HtmlUtils.getHtmlContentNp(url);
JSONObject jsonObject = JSON.parseObject(json);
JSONArray comments = jsonObject.getJSONArray("comments");
int maxc = comments.size();
for (int j = 0; j < maxc; j++) {
JSONObject comment = comments.getJSONObject(j);
Dan d = new Dan();
d.setReferer("https://v.qq.com");
d.setIp("::ffff:111.111.111.111");
d.setType(0);
d.setTime(comment.getDouble("timepoint"));
d.setAuthor(comment.getString("opername"));
d.setPlayer(player);
d.setText(comment.getString("content"));
d.setColor(14277107);
d.setDate(currentTimeMillis());
mongoTemplate.insert(d);
}
}
@Async
public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) {
log.debug("Send email[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}",
isMultipart, isHtml, to, subject, content);
// Prepare message using a Spring helper
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
try {
MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, CharEncoding.UTF_8);
message.setTo(to);
message.setFrom(jHipsterProperties.getMail().getFrom());
message.setSubject(subject);
message.setText(content, isHtml);
javaMailSender.send(mimeMessage);
log.debug("Sent email to User '{}'", to);
} catch (Exception e) {
if (log.isDebugEnabled()) {
log.warn("Email could not be sent to user '{}'", to, e);
} else {
log.warn("Email could not be sent to user '{}': {}", to, e.getMessage());
}
}
}
@Async
@Scheduled(fixedDelay = 60000)
public void cronJobSchedule() {
Set tagids = redisTemplate.opsForSet().members("tagids");
redisTemplate.delete("tagids");
Object[] das = tagids.toArray();
for (Object s : das) {
JSONObject jsonObject = JSON.parseObject(String.valueOf(s));
String tagid = jsonObject.getString("tagid");
String player = (jsonObject.getString("player"));
int timestamp = 0;
boolean flg = true;
while (flg) {
String url = "http://mfm.video.qq.com/danmu?otype=json&target_id=" + tagid + "×tamp=" + timestamp;
timestamp += 30;
as.xzbcdm(url, player);
if (timestamp > 60 * 120) {
flg = false;
}
}
redisTemplate.opsForSet().add("oktagids", tagid);
redisTemplate.delete("danmaku" + player);
}
}
@Async(AppConfig.ASYNC_EXECUTOR_NAME)
public void sendEmailAsync(AccountDto a, CompanyDto c) {
EmailRequest emailRequest = EmailRequest.builder()
.to("[email protected]")
.name("")
.subject(String.format("%s from %s just joined Staffjoy", a.getName(), c.getName()))
.htmlBody(String.format("Name: %s<br>Phone: %s<br>Email: %s<br>Company: %s<br>App: https://app.staffjoy.com/#/companies/%s/employees/",
a.getName(),
a.getPhoneNumber(),
a.getEmail(),
c.getName(),
c.getId()))
.build();
BaseResponse baseResponse = null;
try {
baseResponse = mailClient.send(emailRequest);
} catch (Exception ex) {
String errMsg = "Unable to send email";
logException(logger, ex, errMsg);
}
if (!baseResponse.isSuccess()) {
logError(logger, baseResponse.getMessage());
}
}
@Async(AppConfig.ASYNC_EXECUTOR_NAME)
public void trackEventAsync(String event) {
String userId = AuthContext.getUserId();
if (StringUtils.isEmpty(userId)) {
// Not an action performed by a normal user
// (noop - not an view)
return;
}
TrackEventRequest trackEventRequest = TrackEventRequest.builder()
.userId(userId).event(event).build();
BaseResponse resp = null;
try {
resp = accountClient.trackEvent(trackEventRequest);
} catch (Exception ex) {
String errMsg = "fail to trackEvent through accountClient";
handleErrorAndThrowException(logger, ex, errMsg);
}
if (!resp.isSuccess()) {
handleErrorAndThrowException(logger, resp.getMessage());
}
}
@KafkaListener(topics = {"async-task-topic"}, group = "umu")
@Async
public void receive(String message) {
log.info("Kafka received message='{}'", message);
JSONObject taskCommand = JSONObject.parseObject(message);
String taskType = taskCommand.getString("taskType");
String taskUuid = taskCommand.getString("taskUuid");
if (null != taskUuid) {
if (taskType.equals("ucumos-deploy")) {
this.deployService.deploy(taskUuid, taskCommand.getBoolean("isPublic"));
}
if (taskType.equals("ucumos-lcm-stop")) {
this.lifeCircleManagementService.stop(taskUuid, taskCommand.getString("deploymentUuid"));
}
}
}
@Async("threadPoolTaskExecutor")
public Future<String> onlineCount(String symbol) {
Future<String> future = new AsyncResult<>("更新首页用户在线数量");
Map<String, Channel> channelMapAll = ChannelManager.getAllChannel();
if (channelMapAll != null && !channelMapAll.isEmpty()) {
int onlineConut = 0;
if (StringUtils.isEmpty(symbol)) {
onlineConut = ChannelManager.sizeChannel();
} else if ("-".equals(symbol)) {
onlineConut = ChannelManager.sizeChannel() - 1;
} else if ("+".equals(symbol)) {
onlineConut = ChannelManager.sizeChannel() + 1;
} else {
onlineConut = ChannelManager.sizeChannel();
}
IMMessage imMessage = new IMMessage(RedisKeyEnum.NETTY_ONLINE_COUNT.getExpireTime(), onlineConut, null);
channelMapAll.forEach((s, channel) -> ChannelManager.ctxWrite(channel, imMessage));
}
return future;
}
@Async("taskExecutor")
public Future<String> doTaskOne() throws Exception {
log.info("开始做任务一");
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(1000));
long end = System.currentTimeMillis();
log.info("完成任务一,耗时:" + (end - start) + "毫秒");
return new AsyncResult<>("任务一完成");
}
/**
* 异步记录日志
*
* @param event event
*/
@Async
@Order
@EventListener(LogEvent.class)
public void saveSysLog(LogEvent event) {
Log log = (Log) event.getSource();
userServiceClient.saveLog(log);
}
/**
* 群发自定义消息
* */
@Async
public void sendInfo(String message) throws IOException {
for (TvDmSocket item : TvDmSocket.webSocketSet) {
try {
item.sendMessage(message);
} catch (IOException e) {
continue;
}
}
}
@Async("taskExecutor")
public Future<String> run() throws Exception {
long sleep = random.nextInt(10000);
log.info("开始任务,需耗时:" + sleep + "毫秒");
Thread.sleep(sleep);
log.info("完成任务");
return new AsyncResult<>("test");
}
/**
* 存储后台用户登录信息
* @param id
* @param token
*/
@Async
public void storeAgentUserLoginInfo(Long id, String token) {
if (StringUtils.isNotBlank(token)) {
//存储用户登录状态
String onlineFlag = generateAgentOnlineKey(id.toString());
JedisCache.setStr(onlineFlag, token);
JedisCache.expire(onlineFlag, myConfiguration.getSessionTimeout());
}
}
/**
* 删除灰度配置
*
* @param path
* @param regionList
*/
@Async
public void deleteGrayConfig(String path, String grayGroupId, List<Region> regionList) {
String pushId = SnowflakeIdWorker.getId();
Map<String, String> map = new HashMap<>();
map.put("path", path);
map.put("pushId", pushId);
map.put("grayGroupId", grayGroupId);
this.batchPost(DELETE_DATA_URL, map, regionList);
}
/**
* 短信模版消息通知
*
* @param phoneNumber 接收通知的电话号码
* @param notifyType 通知类别,通过该枚举值在配置文件中获取相应的模版ID
* @param params 通知模版内容里的参数,类似"您的验证码为{1}"中{1}的值
*/
@Async
public void notifySmsTemplate(String phoneNumber, NotifyType notifyType, String[] params) {
if (smsSender == null) {
return;
}
String templateIdStr = getTemplateId(notifyType, smsTemplate);
if (templateIdStr == null) {
return;
}
int templateId = Integer.parseInt(templateIdStr);
smsSender.sendWithTemplate(phoneNumber, templateId, params);
}
/**
* get block from chain by groupId
* ThreadPool configuration in /base/config/BeanConfig
*/
@Async(value = "mgrAsyncExecutor")
public void pullBlockByGroupId(CountDownLatch latch, int groupId) {
log.debug("start pullBlockByGroupId groupId:{}", groupId);
try {
//max block in chain
BigInteger maxChainBlock = frontInterface.getLatestBlockNumber(groupId);
//next block
BigInteger nextBlock = getNextBlockNumber(groupId);
//pull block
while (Objects.nonNull(maxChainBlock) && maxChainBlock.compareTo(nextBlock) >= 0) {
log.debug("continue pull block. maxChainBlock:{} nextBlock:{}", maxChainBlock,
nextBlock);
Thread.sleep(cProperties.getPullBlockSleepTime());
pullBlockByNumber(groupId, nextBlock);
nextBlock = getNextBlockNumber(groupId);
//reset maxChainBlock
if (maxChainBlock.compareTo(nextBlock) < 0) {
maxChainBlock = frontInterface.getLatestBlockNumber(groupId);
}
}
} catch (Exception ex) {
log.error("fail pullBlockByGroupId. groupId:{} ", groupId, ex);
}finally {
// finish one group, count down
latch.countDown();
}
log.debug("end pullBlockByGroupId groupId:{}", groupId);
}
/**
* 把tables信息记录到文件
*/
@Async
void downLoadToFileBatch(DataSource dataSource, List<Table> tables) {
try {
for (Table table : tables) {
String tablesStr = JSON.toJSONString(table, true);
FileUtils.writeStringToFile(BaseConstants.getTableFile(dataSource, table.getTableName()), tablesStr, StandardCharsets.UTF_8.toString());
}
} catch (IOException e) {
log.error("写入表文件错误", e);
}
}
@Async //这是一个异步方法
public void sendVerifyemail(String email) {
try {
Thread.sleep(3000);
String secretKey = UUID.randomUUID().toString(); // 密钥
Timestamp outDate = new Timestamp(System.currentTimeMillis() + 30 * 60 * 1000);// 30分钟后过期
long date = outDate.getTime() / 1000 * 1000;
userRepository.setOutDateAndValidataCode(outDate + "", secretKey, email);
String key = email + "$" + date + "$" + secretKey;
String digitalSignature = MD5Util.encode(key);// 数字签名
// String basePath = this.getRequest().getScheme() + "://" + this.getRequest().getServerName() + ":" + this.getRequest().getServerPort() + this.getRequest().getContextPath() + "/newPassword";
String resetPassHref = activeuserUrl + "?sid="
+ digitalSignature + "&email=" + email;
String emailContent = MessageUtil.getMessage(mailActiveContent, resetPassHref);
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom(mailFrom);
helper.setTo(email);
helper.setSubject(mailActiveSubject);
helper.setText(emailContent, true);
mailSender.send(mimeMessage);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(email);
}
@Async
public void plan(JobWorkflow jobWorkflow, TerraformModule module, Stack stack) {
treatJob(
jobWorkflow,
JobWorkflow::plan,
() -> managePlanScript(jobWorkflow.getJob(), stack, module),
result -> managePlanResult(result, jobWorkflow, stack)
);
}
@Async
public void apply(JobWorkflow jobWorkflow, TerraformModule module, Stack stack) {
treatJob(
jobWorkflow,
JobWorkflow::apply,
() -> manageApplyScript(jobWorkflow.getJob(), stack, module),
result -> manageApplyResult(result, jobWorkflow, stack)
);
}
@Async
public void retry(JobWorkflow jobWorkflow, TerraformModule module, Stack stack) {
stepRepository.deleteByJobId(jobWorkflow.getJob().getId());
treatJob(
jobWorkflow,
JobWorkflow::retry,
() -> managePlanScript(jobWorkflow.getJob(), stack, module),
result -> managePlanResult(result, jobWorkflow, stack)
);
}
@Async
@Order
@EventListener(SysLogEvent.class)
public void saveSysLog(SysLogEvent event) {
SysLog sysLog = (SysLog) event.getSource();
remoteLogService.saveLog(sysLog, SecurityConstants.FROM_IN);
}
@Async
public void sendInfoNothis(String message,String dmid,TvDmSocket t) throws IOException {
for (TvDmSocket item : TvDmSocket.webSocketSet) {
if(item.getDmid().equals(dmid)&&item!=t){
try {
item.sendMessage(message);
} catch (IOException e) {
continue;
}
}
}
}
@Override
@Async("threadPoolTaskExecutor")
public void udpHandleMethod(String message) throws Exception {
logger.info("业务开始处理");
Thread.sleep(3000);
logger.info("业务处理完成");
}
/**
* 邮件消息通知,
* 接收者在spring.mail.sendto中指定
*
* @param subject 邮件标题
* @param content 邮件内容
*/
@Async
public void notifyMail(String subject, String content) {
if (mailSender == null)
return;
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(sendFrom);
message.setTo(sendTo);
message.setSubject(subject);
message.setText(content);
mailSender.send(message);
}
@Override
@Async("threadPoolTaskExecutor")
public Future<String> task3() throws Exception {
logger.info("task3开始执行");
Thread.sleep(3000);
logger.info("task3执行结束");
return new AsyncResult<String>("task3 success");
}
@Override
@Async("threadPoolTaskExecutor")
public Future<String> task4() throws Exception {
logger.info("task4开始执行");
Thread.sleep(3000);
logger.info("task4执行结束");
return new AsyncResult<String>("task4 success");
}
/**
* 异步发送短信
*
* @param phone
* @param code
* @return void
* @throws
* @author wliduo[[email protected]]
* @date 2020/5/20 10:53
*/
@Async
public void sendCode(String phone, String code) {
logger.info("开始发送验证码...");
// 模拟调用接口发验证码的耗时
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
logger.info("发送成功: {}", phone);
}
/**
* @Async 告诉 Spring 这是一个异步方法
* 默认使用 Spring 内的线程池
* threadName:task-1
*
* @Async("BeanName") 从 IOC 容器中指定线程池
* threadName:myThreadPool-1
*
*/
@Async("myThreadPool")
public void hello() {
String threadName = Thread.currentThread().getName();
long threadId = Thread.currentThread().getId();
System.out.println(getClass()+" threadName:" + threadName + " , threadId:" + threadId);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(getClass()+" threadName:" + threadName + " , threadId:" + threadId + " ,处理数据中...");
}
@Async(AppConfig.ASYNC_EXECUTOR_NAME)
public void alertRemovedShiftAsync(AlertRemovedShiftRequest alertRemovedShiftRequest) {
BaseResponse baseResponse = null;
try {
baseResponse = botClient.alertRemovedShift(alertRemovedShiftRequest);
} catch (Exception ex) {
String errMsg = "failed to alert worker about removed shift";
handleErrorAndThrowException(logger, ex, errMsg);
}
if (!baseResponse.isSuccess()) {
handleErrorAndThrowException(logger, baseResponse.getMessage());
}
}
@Async
@Override
public void ipFallback(int ipVersion, String rangeId, String ipAddr) {
String ipManagerServiceUrl = ipUrl + ipVersion + "/" + rangeId + "/" + ipAddr;
restTemplate.delete(ipManagerServiceUrl, IpAddrRequest.class);
String ipRangeDeleteServiceUrl = ipUrl + "range/" + rangeId;
restTemplate.delete(ipRangeDeleteServiceUrl, IpAddrRangeRequest.class);
}