java 动态更新,Java缓存和动态更新

I need to "preload" some data from a database on servlet startup.

So I thought to create some cache e.g. using a HashMap or some similar synchronized version.

I also need to update the cache on database update changes.

So I thought to add some kind of "listener".

My question is: is this somehow available or do I have to actually implement it?

If yes what design pattern would be the best approach here?

Update:

No JPA or ORM used. But Spring is available

解决方案

Yes of course you can implement that

I'll draw a small architecture then ill explain it to u:

zOaWL.jpg

first of all , you can learn about Mappers here and TDGs here.

A mapper has a method called cacheAll() which calls and delegate to TDG's method cacheAll() which in its turn has a mission to get all rows from a table from the db( the rows you want to cache in the cache object).

so basically first you have to create a listener implementing "ServletContextListener"

which means its a listener for the whole servlet context, and inside its contextInitialized you have to call mp.fill(Mapper.cacheAll()), so it is sthg like ( this is general code, of course write it better and optimize it)

public class myServletContextListener implements ServletContextListener{

@Override

public void contextInitialized(ServletContextEvent sce) {

mp.fill(Mapper.cacheAll());

}

//

}

Don't forget to add your listener in web.xml:

myServletContextListener

so what this will do , is on startup of the server, will cache all record into a hashmap mp in a cache object.

As for updating cache based on database change, you will have to use observer pattern.

UPDATE

I forgot to mention, about the cache object, i assume you want it accessible for all users or your app, so you should code it as a singleton (singleton pattern), code like that:

public class cacheObject

{

private static Map cMap;

private static cacheObject cObject;

private cacheObject()

{

cMap = Mapper.cacheAll();

}

public static synchronized cacheObject getInstance()

{

if (cObject == null){

cObject = new cacheObject();

}

return cObject;

}

}

Also if the data that you want to cache can be changed by users, so make it a Threadlocal singleton.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值