代码:
package com.sougou;
import java.io.ObjectInputStream.GetField;
import java.util.HashMap;
import java.util.Map;
public class CacheDemo {
public static Map cache = new HashMap();
/**
* @param args
*/
public static void main(String[] args) {
User user = getUser(1);
}
/**
* 如果查到后1用户信息被更新了那么怎么办呢?
* @param id
* @return
*/
public static User getUser(int id){
//要保证key的值设置的比较合理,如果不合理的话会出现覆盖的情况,因为id可能重复
String key = User.class.getName()+id;
User user = (User) cache.get(key);
if(user != null){
return user;
}
user = getDataFromDB(id);
cache.put(key, user);
return user;
}
public static void upData(User user){
udDataDB(user);
String key = User.class.getName()+user.getId();
cache.remove(key);
}
private static void udDataDB(User user) {
// TODO Auto-generated method stub
}
private static User getDataFromDB(int id) {
// TODO Auto-generated method stub
return null;
}
}