场景
定时任务中需要获取数据库中数据进行数据转换成需要的格式并进行后续的业务处理。
数据库中的数据更新频率不高。
可将数据库中数据在项目启动后读取一遍数据,然后再通过定时任务定时查询数据库更新数据。
实现数据库缓存的方式有多种,比如以下:
SpringBoot中通过自定义缓存注解(AOP切面拦截)实现数据库数据缓存到Redis:
SpringBoot中通过自定义缓存注解(AOP切面拦截)实现数据库数据缓存到Redis_redis切面-CSDN博客
SpringBoot中集成阿里开源缓存访问框架JetCache实现声明式实例和方法缓存:
SpringBoot中集成阿里开源缓存访问框架JetCache实现声明式实例和方法缓存_springboot集成jetcache-CSDN博客
Java工具库Guava本地缓存Cache的使用、回收、刷新、统计等示例:
Java工具库Guava本地缓存Cache的使用、回收、刷新、统计等示例-CSDN博客
若msyql中数据量不大或不想引入redis等三方中间件。可通过如下简单方式实现。
注:
博客:
霸道流氓气质_C#,架构之路,SpringBoot-CSDN博客
实现
1、新建定时任务类
方法initBusRegion()则是从数据库中读取数据并进行数据转换为需要的格式。
声明一个变量lineStrings,用来定时接收更新从数据库中查询转换后的数据。
然后将变量传递给其他定时任务的方法作为后续业务处理使用。
示例代码:
@Component("getDataTask")
@EnableScheduling
@Slf4j
public class GetDataTask {
private List<LineString> lineStrings;
@PostConstruct
@Scheduled(cron = "0 0 * * * ?")
public void initBusRegion() {
QueryWrapper<BusRegionCoreEntity> qw = new QueryWrapper<>();
List<BusRegionCoreEntity> busRegions = busRegionCoreMapper.selectList(qw);
lineStrings = busRegions.stream().map(busRegion -> {
double startX = bigDecimal2Double(busRegion.getStartX());
double startY = bigDecimal2Double(busRegion.getStartY());
double endX = bigDecimal2Double(busRegion.getEndX());
double endY = bigDecimal2Double(busRegion.getEndY());
LineString lineString = null;
try {
lineString = GeometryUtil.createLineString(startX, startY, endX, endY);
lineString.setUserData(busRegion.getRegionName());
} catch (Exception exception) {
exception.printStackTrace();
}
return lineString;
}).collect(Collectors.toList());
}
@Scheduled(cron = "0/1 * * * * ?")
public void getData() {
positionCar(lineStrings);
}
private Double bigDecimal2Double(BigDecimal bigDecimal) {
if (bigDecimal == null) {
return null;
}
return bigDecimal
.setScale(15, RoundingMode.HALF_UP)
.doubleValue();
}
}
这里的示例代码是使用mybatisplus从表中读取数据,然后将x y字段从double转换成bigDecimal,然后调用工具类方法
将其映射成List<LineString>所需要的数据格式。