您的位置:首页 > 编程语言 > Java开发

java后台系统实现动态新闻列表实时更新

2017-03-11 19:47 543 查看
1.首先我们有了这样一个需求:实现网站的动态数据更新,前台滚动刷新.

一个人说:我们可以再前台设置ajax定时发起请求,动态请求数据,并刷新页面.

分析:功能实现,技术简单

缺点:倘若系统的使用量较大,每个用户长时间驻留页面都会发起大量的后台请求,并查询数据库,数据库压力增大

这也是一种实现方法,虽然实现了功能但是并不适合大数据量的网站.

其实我们仔细分析一下,我们只是需要所有用户展示动态数据,那么有什么是所有用户都可以共享的尼?对,恭喜你想到了,application域.我们只要每个一定的时间就将最新的数据取出,比如10条数据取出,放到application域中,然后后台每次请求application 域中的数据即可.这样每个用户请求都不会穿透数据库.



说干就干

假设系统是spring系统,那么我们如何执行定时任务尼

三种方案:

jdk的timertask,

spring的定时任务,

quartz的定时任务调度

这里采用第二种:实现简单,定时实现:

开启定时注解:

<task:annotation-driven  />
或者设定线程池大小
<task:scheduler id="excutor" pool-size="3"/>


定时方法实现简单,但是难点我们如何定时对象中获取spring容器对象和web的application域对象

好了不卖关子了,

spring容器对象获取可以继承ApplicationObjectSupport对象,并将该类交给spring管理自然可以获取spring对象

而获取application对象可以继承WebApplicationObjectSupport,获取

具体代码:

/**
* @author ll
*该类用于保存WebApplicationContext
*/
@Component
public class WebContext extends WebApplicationObjectSupport {
public WebApplicationContext getWebApp(){
return this.getWebApplicationContext();
}
}


定时任务实现:

/**
* @author ll
*定时操作类
*/
@Lazy(false)
@Component
@EnableScheduling
public class EcrTimerTask extends ApplicationObjectSupport implements SchedulingConfigurer{
private static String refrsh_cron;
static{
PropertiesUtils.init("config/deploy.properties");
refrsh_cron=PropertiesUtils.getValue(Constants.TIMER_REFRESH__CONTRACT).toString();
}

public void refreshListCon(){
ApplicationContext springApp = this.getApplicationContext();
WebApplicationContext webApp = springApp.getBean(WebContext.class).getWebApp();
SingedLogic singedLogic= springApp.getBean(SingedLogic.class);
List<ConstractListVo> vos = singedLogic.queryActualContract();
//放置到application域里
webApp.getServletContext().setAttribute(Constants.CONTRACT_LIST_KEY,vos);
}
@Override
public void configureTasks(ScheduledTaskRegistrar register) {
/**
* 定时刷新实时动态数据
*/
register.addTriggerTask(new Runnable() {

@Override
public void run() {
refreshListCon();
}
}, new Trigger() {

@Override
public Date nextExecutionTime(TriggerContext triggerContext) {
CronTrigger trigger=new CronTrigger(refrsh_cron);
Date nextExec=trigger.nextExecutionTime(triggerContext);
System.out.println("执行了刷新缓存");
return nextExec;
}
});

}

}


注意:定时任务不要简单的使用注解实现,我们大部分的需求实现是将定时执行频率写在配置文件中,然后动态配置

TIMER_REFRESH=0/5 * * * * ?


cron表达式可以自行百度
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java
相关文章推荐