对于有些简单项目不涉及redis但又要频繁向数据库请求数据的时候,可以考虑自己建立一个静态map,在项目运行的时候把一部分固定不变又频繁请求的数据放入这个map中。
首先,创建一个自定义缓存的类(静态map)
实现CommandLineRunner接口,重写run方法(实现项目运行完成就马上执行某个方法,主题来了)
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import com.jxgp.modules.gpjc.service.CityService;
import com.jxgp.modules.gpjc.vo.CityTree;
import com.jxgp.modules.tb.entity.CompanyCatalogueEntity;
import com.jxgp.modules.tb.service.CompanyCatalogueService;
/**
* 自定义缓存
* */
@Component
public class rdisMap implements CommandLineRunner{
@Autowired
private CompanyCatalogueService companyCatalogueService;
@Autowired
private CityService cityService;
public static Map<String, Object> result;
/**单例模式*/
public static Map<String, Object> result(){
if(result==null) {
result=new HashMap<String,Object>();
}
return result;
}
public static Object getResult(String key) {
return result.get(key);
}
//定义一个启动加载的类方法(启动完成后自动运行)
@Override
public void run(String... args) throws Exception {
Map<String, Object> map=new HashMap<String, Object>();
List<CompanyCatalogueEntity> list=companyCatalogueService.queryList(map);
result();
result.put("companyCatalogue",list);
System.out.println("企业目录录入完成!");
List<CityTree> trees=cityService.geCityTrees();
result.put("cityTrees",trees);
System.out.println("city tree 加载完成!");
}
}
以上就完成了初始状态的类方法调用,map中也存放了部分固定不变又频繁请求的数据。
对于map的调用:
@SuppressWarnings("unchecked")
@ApiOperation("获取city tree")
@GetMapping("/tree")
public R tree() {
List<CityTree> trees=new ArrayList<CityTree>();
if(rdisMap.result==null || rdisMap.getResult("cityTrees")!=null) {
trees=(List<CityTree>) rdisMap.getResult("cityTrees");
}else {
trees=cityService.geCityTrees();
}
return R.ok().put("cityTrees", trees);
}