1. 两种实现
① 直接在单例类里创建一个map,key是 类名方法名参数列表和实参组合,value为值
②在单例类里创建两个map(嵌套map),外层map的key 是service层全限定名,内层key 是方法名形参,value为值
代码实现如下:
/** * 单例模式结合 hashTable 作缓存 测试 */ @Controller public class SingleCacheTest { private static Map<String,Object> cacheManager = null; private static Map<String,Map<String,Object>> cacheManagers = null; private static SingleCacheTest instance = new SingleCacheTest(); private SingleCacheTest(){ cacheManager = new HashMap<String,Object>(); cacheManagers = new HashMap<String,Map<String,Object>>(); } public static SingleCacheTest getInstance(){ return instance; } public static Map<String,Object> getCacheManager(){ return cacheManager; } public static Map<String,Map<String,Object>> getCacheManagers(){ return cacheManagers; } public static Map<String,Map<String,Object>> putValue(String serviceFullName,String methodName,String args,Object value){ Map classMap = cacheManagers.get(serviceFullName); if(null == classMap){ classMap = new HashMap<String,Object>(); } classMap.put(methodName+args,value); cacheManagers.put(serviceFullName,classMap); return cacheManagers; } public static void main(String[] args) { //第一版本 Map<String,Object> cacheManager = SingleCacheTest.getCacheManager(); List list = new ArrayList<>(); Employee employee1 = new Employee(); employee1.setEmpName("郭靖"); Employee employee2 = new Employee(); employee2.setEmpName("杨康"); list.add(employee1); list.add(employee2); cacheManager.put("com.gupaoedu.crud.service.EmployeeService.getAll()",list); List dlist = new ArrayList<>(); Department department1 = new Department(); department1.setDeptName("研发部门"); dlist.add(department1); cacheManager.put("com.gupaoedu.crud.service.DepartmentService.getDepts()",dlist); //第二版本 Map<String,Map<String,Object>> cacheManagers = SingleCacheTest.putValue("com.gupaoedu.crud.service.EmployeeService","getAll()","",list); Map<String,Map<String,Object>> cacheManagers2 = SingleCacheTest.putValue("com.gupaoedu.crud.service.DepartmentService","getDepts()","",dlist); System.out.println(cacheManagers2); }
打断点: