需求是这样的:
offer表:offerId,offerName
source表: sourceId,sourceName,offerId
source表中关联了了offer表的offerId,但是在做展现的时候并不能直接展现id,要把offerName展现在界面上,那就得通过source表里的id查offer,也就是说每次进source的展示界面的时候不仅要访问一次source表还要访问一次offer表,而且要根据每条source记录的id一个个查出来offer,数据库访问次数瞬间翻倍。
解决方案:
在sourceAction中设置一个静态map来缓存offer,如果在条件不改变的情况下,就只需查一次数据库就可以,如果offer那边有改动,比如某个offer的name被修改了,就只需清一个静态缓存就可以,再对数据库查询一次。这样避免了每次进入source展现页面都要查询offer表的麻烦。
代码:
public class Offer {
private Integer offerId; //提供者Id
private String offerName; //提供者
public class Source {
private Integer sourceId; //Id
private String sourceName; //数据源代码
private Integer offerId; //提供者ID
public class OfferAction implements ActionSupport{
@Autowired
private OfferManager offerManager;
public void save(Offer offer){
offerManager.save(offer);
SourceAction.clearCache();//offer有修改或删除时都要清除缓存;
}
}
public class SourceAction implements ActionSupport{
@Autowired
private SourceManager sourceManager;
@Autowired
private OfferManager offerManager;
private static Map<Integer, String> offerMap = new HashMap<Integer, String>();
//提供清除静态缓存的方法
public static void clearCache() {
offerMap.clear();
}
public String execute(){
//source表的查询省略
//下面把offer放入静态Map
if (offerMap.isEmpty()) {
Map<String, Object> queryMap = new HashMap<String, Object>();
List<Offer> offerList = offerManager.find(queryMap);
for (Offer offer : offerList) {
offerMap.put(offer.getOfferId(), offer.getOfferName());
}
}
//下面需要offer的地方直接从offerMap里拿
}
}
其实方法很简单,就是用静态Map缓存需要的数据。但碰到有循环取值的情况,这种方法还是能很有效的减少数据库访问次数提高程序运行速度的。