第一步:导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
第二步:定时任务接口
public interface WeatherDataService {
/**
* 根据城市Id来同步天气
* @param cityId
*/
void syncDataByCityId(String cityId);
}
第三步:定时任务实现类
@Service
public class WeatherDataServiceImpl implements WeatherDataService {
private static final String WEATHER_URI = "http://wthrcdn.etouch.cn/weather_mini?";
private static final long TIME_OUT = 1800L;//1800s
@Autowired
private RestTemplate restTemplate;
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Override
public void syncDataByCityId(String cityId) {
String uri = WEATHER_URI + "citykey=" + cityId;
this.saveWeatherData(uri);
}
/**
* 把天气数据放入缓存
* 相当于更新缓存
* @param uri
*/
private void saveWeatherData(String uri) {
String key = uri;
String strBody = null;
ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
//调用服务接口来获取
ResponseEntity<String> respString = restTemplate.getForEntity(uri,String.class);
//将接口返回的Json字符串转换成对象
if (respString.getStatusCodeValue() == 200) {
strBody = respString.getBody();
}
//数据写入缓存
ops.set(uri,strBody,TIME_OUT, TimeUnit.SECONDS);
}
}
第四步:具体的数据同步Job类
public class WeatherDataSyncJob extends QuartzJobBean{
private static final Logger logger = LoggerFactory.getLogger(WeatherDataSyncJob.class);
@Autowired
private CityDataService cityDataService;
@Autowired
private WeatherDataService weatherDataService;
@Override
protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
logger.info("天气数据同步Job,Start!");
//获取城市ID列表
List<City> cityList = null;
try {
cityList = cityDataService.listCity();
} catch (Exception e) {
logger.error("Exception!!",e);
}
//遍历城市ID获取天气
for (City city : cityList) {
String cityId = city.getCityId();
logger.info("天气数据同步Job,cityId:" + cityId);
weatherDataService.syncDataByCityId(cityId);
}
logger.info("天气数据同步Job,End!");
}
}
第五步:Quartz配置类(声明和绑定Job、Trigger、Schedule)
@Configuration
public class QuartzConfiguration {
private static final int TIME = 1800;//更新频率
//JobDetail
@Bean
public JobDetail weatherDataSyncJobDetail() {
return JobBuilder.newJob(WeatherDataSyncJob.class).withIdentity("weatherDataSyncJob")
.storeDurably().build();
}
//Trigger触发器
//还可以使用CronScheduleBuilder来自定义cron表达式,更加灵活
@Bean
public Trigger weatherDataSyncTrigger() {
SimpleScheduleBuilder schedBuilder = SimpleScheduleBuilder.simpleSchedule()
.withIntervalInSeconds(TIME).repeatForever();
return TriggerBuilder.newTrigger().forJob(weatherDataSyncJobDetail())
.withIdentity("weatherDataSyncTrigger").withSchedule(schedBuilder).build();
}
}
完成,运行项目