您的位置:首页 > 数据库 > Memcache

定时任务(刷新memcache缓存)

2019-04-15 18:26 197 查看

定时任务(刷新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);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐