java - Memcache的使用方法和场景

查看:211
本文介绍了java - Memcache的使用方法和场景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

  1. memcache 的使用方法:

    一个配置文件:
    一个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);
    }
}

应用:

在service 的实现类使用

@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;
    }

这是我的使用方法,我想请教一下大佬们在实际工作中的使用场景和方法是如何做的???

解决方案

有一些可能需要改进的地方

  • KEY的设计,这块在实际使用中比较重要,需要考虑避免重复,可读可调。比如使用Group_Class_Cache_RN的形式,同样良好的KEY设计,可以通过校验KEY格式来防止缓存击穿.

  • 失效时间的设置,在高并发情况下,每个缓存的失效时间应该尽量分散,避免缓存雪崩。一般是一个BaseExpire + Random.
    此外,如果存在不同的业务需求,或者阻塞,IO瓶颈等等的,可以引入多级缓存。

你这种使用代码侵入性有点强,编码有点多,出错的可能会比较高,如果使用Spring的话,可以研究下Spring Cache,一是通过注解AOP降低缓存与业务代码的耦合,同时也可以对比下配置,命名,更新等相关的实现。

这篇关于java - Memcache的使用方法和场景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆