定时任务(刷新memcache缓存)

本文介绍如何使用Spring框架配置定时任务,通过java类CacheJob中的refreshFundInfo方法,定期从数据库查询基金信息并更新到memcache中,实现缓存数据的自动刷新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

定时任务(刷新memcache缓存)

xml配置文件spring-job.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:task="http://www.springframework.org/schema/task"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
	                    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd	                    
	                    http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">
    <!-- 配置注解扫描 -->
    <context:annotation-config />
    <!-- 自动扫描的包名 -->
    <context:component-scan base-package="com.yhfund.wx" />
    <task:scheduler id="springScheduler" pool-size="1" />
	<task:scheduled-tasks scheduler="springScheduler">
		<task:scheduled ref="cacheJob" method="refreshFundInfo" fixed-rate="3600000" />
	</task:scheduled-tasks>
</beans>

注:
cacheJob 执行任务的java类名
refreshFundInfo 执行任务的方法(cacheJob 中的refreshFundInfo方法 )
3600000 刷新频率(毫秒)

查询数据库并将结果放入memcache(键值对)

package com.yhfund.wx.quartzjob;

import com.yhfund.api.middleware.exception.MiddlewareException;
import com.yhfund.api.middleware.response.query.FundInfo;
import com.yhfund.app.tools.utils.JsonMapper;
import com.yhfund.wx.constants.CacheConstants;
import com.yhfund.wx.service.MemCacheService;
import net.rubyeye.xmemcached.MemcachedClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class CacheJob {
	private static final Logger logger = LoggerFactory.getLogger(CacheJob.class);
	private static final JsonMapper normalJsonMapper = JsonMapper.buildNormalMapper();
	@Autowired
	private MemCacheService memCacheService;
	@Autowired
	private MemcachedClient memcachedClient;
	
	public void refreshFundInfo(){
		try {
			List<FundInfo> resultList = memCacheService.queryFundInfoList();//查数据库过程
			memcachedClient.set(key, cachetime, value);
			logger.debug("刷新成功:"+ normalJsonMapper.toJson(resultList));
		} catch (MiddlewareException appe) {
			logger.debug("刷新失败", appe);
		} catch (Exception e) {
			e.printStackTrace();
			logger.debug("刷新失败", e);
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值