//缓存对象
public class User implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private int id;
private String name;
public User(){
}
public User(String name){
this.name= name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
2.对象服务实现类
package org.springframework.cache.demo;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
/**
* 业务服务
*
*/
public class UserService {
@Cacheable(value = "userCache",key="#userName")
// 使用了一个缓存名叫 userCache
public User getUserByName(String userName) {
// 方法内部实现不考虑缓存逻辑,直接实现业务
return getFromDB(userName);
}
@CacheEvict(value = "userCache", key = "#user.name")
// 清空 accountCache 缓存
public void updateUser(User user) {
updateDB(user);
}
@CacheEvict(value = "userCache", allEntries = true,beforeInvocation=true)
// 清空 accountCache 缓存
public void reload() {
}
private User getFromDB(String userName) {
System.out.println("查询数据库..." + userName);
return new User(userName);
}
private void updateDB(User user) {
System.out.println("更新数据库数据..." + user.getName());
}
}
3.缓存实现
package org.springframework.cache.demo.mycache;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.cache.Cache;
import org.springframework.cache.support.SimpleValueWrapper;
public class MyCache implements Cache {
private String name;
private Map<String, Object> store = new ConcurrentHashMap<String, Object>();;
public MyCache() {
}
public MyCache(String name) {
this.name = name;
}
public void setName(String name) {
this.name = name;
}
public void clear() {
store.clear();
}
public void evict(Object obj) {
}
public ValueWrapper get(Object key) {
ValueWrapper result = null;
Object thevalue = store.get(key);
if (thevalue != null) {
result = new SimpleValueWrapper(thevalue);
}
return result;
}
public <T> T get(Object key, Class<T> clazz) {
return clazz.cast(store.get(key));
}
public String getName() {
return name;
}
public Object getNativeCache() {
return store;
}
public void put(Object key, Object value) {
store.put((String) key, value);
}
public ValueWrapper putIfAbsent(Object key, Object value) {
put(key, value);
return new SimpleValueWrapper(value);
}
}
4.spring配置