良好的系统是不会不断的创建销毁线程的,而是有线程池进行维护
/**
spring默认就是单例的 当在controller类上去掉@scope(“prototype”),变成默认的单例模式
* 单例模式下会共享普通成员变量和静态成员变量,多例模式下普通成员变量不共享,静态成员共享.
*在开发中,springMVC优先使用单例模式,而且尽量不要在controller中设定成员变量.
*饿汉单例,将查询的list放入内存,缓存起来,减少数据库压力
*使用场景:
* 解析csv文件并入库monitor_cell表,然后写如下代码,从缓存中获取数据
* OneMinuteCache.getInstance().getMonitorCellList();//缓存中有数据,取内存中的数据,如果内存没有数据,则查询数据库
* 解析一个csv文件入库,当重新上传一个文件时,就需要调用set方法刷新内存中list的值;
* 当没有重新上传,就会取上一次解析后缓存到内存中的list
*/
public class OneMinuteCache {
private List<CellBean> monitorCellList = null;//需要缓存的list定义到成员变量中,这里不需要static也可以使用 单例下普通成员变量被共享
private static OneMinuteCache instance = new OneMinuteCache(); //饿汉单利类,保证系统中只有一个实例
private OneMinuteCache(){}
public static OneMinuteCache getInstance() {
if(null == instance) {
instance = new OneMinuteCache();
}
return instance;
}
public List<CellBean> getMonitorCellList() {
if(monitorCellList == null || (monitorCellList.size() == 0) {
monitorCellList=dao.getList(); //查询数据库
}
return monitorCellList;
}
public void setMonitorCellList() throws Exception {
monitorCellList=dao.getList(); //查询数据库
}
}