memcache 的使用方法:
一個(gè)配置文件:
一個(gè)memcache的工具類
public final class MemcachedUtils{
/**
* memcached客戶端單例
*/
private static MemCachedClient cachedClient = new MemCachedClient();
private MemcachedUtils(){
}
public static boolean add(String key, Object value) {
return cachedClient.add(key, value);
}
public static boolean add(String key, Object value, Integer expire) {
return cachedClient.add(key, value, expire);
}
public static boolean put(String key, Object value) {
return cachedClient.set(key, value);
}
public static boolean put(String key, Object value, Integer expire) {
return cachedClient.set(key, value, expire);
}
public static boolean replace(String key, Object value) {
return cachedClient.replace(key, value);
}
public static boolean replace(String key, Object value, Integer expire) {
return cachedClient.replace(key, value, expire);
}
public static Object get(String key) {
return cachedClient.get(key);
}
}
應(yīng)用:
在service 的實(shí)現(xiàn)類使用
@Service
public class StudentServiceImpl implements StudentService {
@Resource
private StudentMapper studentMapper;
public List<Student> findGoodStudent() {
List<Student> goodStudents;
if(MemcachedUtils.get("goodStudents") != null){
goodStudents = (List<Student>) MemcachedUtils.get("goodStudents");
System.out.println("使用了memcache");
return goodStudents;
}
goodStudents = studentMapper.findGoodStudent();
System.out.println("沒有使用memcache");
MemcachedUtils.add("goodStudents",goodStudents);
return goodStudents;
}
這是我的使用方法,我想請教一下大佬們在實(shí)際工作中的使用場景和方法是如何做的???
3 回答

慕的地10843
TA貢獻(xiàn)1785條經(jīng)驗(yàn) 獲得超8個(gè)贊
有一些可能需要改進(jìn)的地方
KEY的設(shè)計(jì),這塊在實(shí)際使用中比較重要,需要考慮避免重復(fù),可讀可調(diào)。比如使用Group_Class_Cache_RN的形式,同樣良好的KEY設(shè)計(jì),可以通過校驗(yàn)KEY格式來防止緩存擊穿.
失效時(shí)間的設(shè)置,在高并發(fā)情況下,每個(gè)緩存的失效時(shí)間應(yīng)該盡量分散,避免緩存雪崩。一般是一個(gè)BaseExpire + Random.
此外,如果存在不同的業(yè)務(wù)需求,或者阻塞,IO瓶頸等等的,可以引入多級緩存。
你這種使用代碼侵入性有點(diǎn)強(qiáng),編碼有點(diǎn)多,出錯(cuò)的可能會比較高,如果使用Spring的話,可以研究下Spring Cache,一是通過注解AOP降低緩存與業(yè)務(wù)代碼的耦合,同時(shí)也可以對比下配置,命名,更新等相關(guān)的實(shí)現(xiàn)。

慕絲7291255
TA貢獻(xiàn)1859條經(jīng)驗(yàn) 獲得超6個(gè)贊
1.安全 。
每做一次查詢,保存或者跳轉(zhuǎn)頁面,從memcache 中去取出session,如果有值,則允許操作,反之則提示。
2.跨系統(tǒng)共享session
3.緩存。。。
添加回答
舉報(bào)
0/150
提交
取消