最近项目中需要做一个定时任务在某个固定的时间去执行一个任务,由于该定时任务的代码量已经超出可读性规范,并且处于性能的考虑,故使用线程池来做一个异步执行的方法
产品给到的需求是,让用户获得的能量根据有效期的规则配置,去实现一个能量过期的效果,因为是springboot单体项目,使用XXLJOB就过于繁琐,而且项目中没有其它的定时任务,私以为使用Scheduled执行比较简单,易用。然后编写过程中发现,代码行数太多,按照不能超过80行的规范,故将一部分业务拆分出去,并使用线程池异步执行。
代码如下:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ThreadPoolExecutor;
@Configuration
@EnableAsync//开启异步
public class ThreadPoolTaskConfig {
@Bean("threadPoolTaskExecutor")
public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(16);
executor.setQueueCapacity(1024);
executor.setMaxPoolSize(64);
executor.setKeepAliveSeconds(30);
executor.setThreadNamePrefix("thread-");
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
executor.initialize();
return executor;
}
}
犹豫还要考虑性能安全的问题,所以使用Redisson,做一个锁
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RedissonConfig {
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.password}")
private String password;
@Value("${spring.redis.port}")
private Integer port;
@Bean
public RedissonClient getRedisson() throws Exception {
RedissonClient redisson = null;
Config config = new Config();
//.setPassword(password)
config.useSingleServer().setAddress("redis://" + host + ":" + port);
redisson = Redisson.create(config);
System.out.println(redisson.getConfig());
return redisson;
}
}
需要注意的是,其中的@Value已经在yml配置文件中配置好了,这里不再记录
代码如下:
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hsbc.component.AddOutEnergyComponent;
import com.hsbc.enums.EnergyType;
import com.hsbc.mapper.EnergyRecordMapper;
import com.hsbc.model.EnergyRecord;
import com.hsbc.model.EnergyRule;
import com.hsbc.service.IEnergyRecordsService;
import com.hsbc.service.IEnergyRuleService;
import com.hsbc.enums.DelFlagEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
@Configuration
@EnableScheduling//开启定时任务
@Slf4j
public class EneryOutTask {
@Autowired
private EnergyRecordMapper energyRecordMapper;
@Resource
private RedissonClient redissonClient;
@Autowired
private AddOutEnergyComponent addOutEnergyComponent;
public static final String ENERGY_OUT_LOCK_KEY = "energy:out:lock:%s";
/**
* 定时任务
* 每月月初00:00:00执行
* 已过期的能量处理
*/
@Scheduled(cron = "0 0 0 1 * ?")
public void outEnergy() {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String format = sdf.format(date);
String accessLock = String.format(ENERGY_OUT_LOCK_KEY,format);
try {
RLock lock = redissonClient.getLock(accessLock);
boolean isLock = lock.tryLock(-1, 100, TimeUnit.SECONDS);
if (isLock) {
try {
/*获取到本月的最后时间*/
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MONTH, -1);
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
calendar.set(Calendar.HOUR_OF_DAY, calendar.getActualMaximum(Calendar.HOUR_OF_DAY));
calendar.set(Calendar.MINUTE, calendar.getActualMaximum(Calendar.MINUTE));
calendar.set(Calendar.SECOND, calendar.getActualMaximum(Calendar.SECOND));
calendar.set(Calendar.MILLISECOND, calendar.getActualMaximum(Calendar.MILLISECOND));
QueryWrapper<EnergyRecord> queryWrapper = new QueryWrapper<>();
queryWrapper.le("validity_time", calendar.getTime());
queryWrapper.eq("del_flag", DelFlagEnum.NO_DEL.getCode());
/*过期和代扣的能量不统计*/
queryWrapper.ne("type", EnergyType.REDUCE_ENERY.getCode());
queryWrapper.ne("type", EnergyType.EXPIRE.getCode());
/*所有到期的能量*/
List<EnergyRecord> energyRecords = energyRecordMapper.selectList(queryWrapper);
Map<String, Integer> outEnergyMap = new HashMap<>(energyRecords.size()); //会员即将到期的能量map
Map<String, List<String>> outEnergyIdsMap = new HashMap<>(); //全部到期准备删除的能量id
for (EnergyRecord energyRecord : energyRecords) {
Integer outEnergy = outEnergyMap.get(energyRecord.getMemberId());
if (outEnergy == null) {
outEnergy = 0;
}
outEnergy += energyRecord.getResidualEnergy();
outEnergyMap.put(energyRecord.getMemberId(), outEnergy);
List<String> list = outEnergyIdsMap.get(energyRecord.getMemberId());
if (list == null) {
list = new ArrayList<>();
}
list.add(energyRecord.getId());
outEnergyIdsMap.put(energyRecord.getMemberId(), list);
}
for (Map.Entry<String, Integer> entry : outEnergyMap.entrySet()) {
/*异步添加*/
addOutEnergyComponent.add(entry.getKey(), entry.getValue(), outEnergyIdsMap.get(entry.getKey()));
}
} finally {
log.info("操作业务完毕,开始释放锁");
lock.unlock();
}
} else {
log.info("当前过期能量定时任务已被执行!!");
}
} catch (Exception e) {
log.error("已过期能量定时任务报错", e);
}
}
}
代码如下:
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hsbc.enums.DelFlagEnum;
import com.hsbc.enums.EnergyReadEnum;
import com.hsbc.enums.EnergyType;
import com.hsbc.mapper.EnergyRecordMapper;
import com.hsbc.model.EnergyRecord;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.List;
@Component
@Slf4j
public class AddOutEnergyComponent {
@Autowired
private EnergyRecordMapper energyRecordMapper;
//配置线程池
@Async("threadPoolTaskExecutor")
public void add(String memberId, Integer energy, List<String> outIds) {
QueryWrapper<EnergyRecord> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("member_id", memberId);
queryWrapper.orderByDesc("id");
Page<EnergyRecord> page = new Page<>(1, 1);
Page<EnergyRecord> energyRecordPage = energyRecordMapper.selectPage(page, queryWrapper);
int lastEnergy = 0;
if (CollectionUtils.isNotEmpty(energyRecordPage.getRecords())) {
EnergyRecord energyRecord = energyRecordPage.getRecords().get(0);
lastEnergy = energyRecord.getBeforeEnergy() + energyRecord.getEnergyNumber();
}
EnergyRecord energyRecord = new EnergyRecord();
energyRecord.setMemberId(memberId);
energyRecord.setBeforeEnergy(lastEnergy);
energyRecord.setType(EnergyType.EXPIRE.getCode());
energyRecord.setEnergyNumber(-energy);
energyRecord.setCreateTime(new Date());
energyRecord.setAdditional("能量到期");
energyRecord.setStatus(EnergyReadEnum.READ.getCode());
energyRecord.setDelFlag(DelFlagEnum.DEL.getCode());
energyRecordMapper.insert(energyRecord);
//修改过期能量为已删除
energyRecordMapper.update(null,new UpdateWrapper<EnergyRecord>().in("id",outIds).set("del_flag",DelFlagEnum.DEL));
}
}
其中该需求是在能量过期以后,在能量记录表中添加数据,所以涉及另外一张表的数据插入操作,至此已经完全实现需求的功能