基于IM消息场景实现的LRU缓存淘汰算法

前段时间做了Android端IM消息模块的重构,重构的过程中优化了对聊天消息的缓存设计,其中就包括实现的一个LRU缓存淘汰算法的工具类。旧代码里对缓存使用较少,重构的时候,考虑到多个IM会话聊天消息的场景很适合用LRU缓存。

为啥用缓存?

缓存是一种提高数据读取性能的技术。在软件和硬件设计中都广泛在使用,如CPU缓存、数据库缓存、浏览器缓存、Redis缓存等。

缓存淘汰有哪些策略?

缓存的空间大小有限,缓存满时哪些数据保留,哪些被清除,常见有三种策略:

  1. 先进先出策略FIFO(First In, First Out)
  2. 最少使用策略LFU(Least Frequently Used)
  3. 最近最少使用策略LRU(Least Recently Used)

LRU缓存淘汰算法

维护一个按访问时间从小到大有序排列的链表结构,越靠近链表头部的节点就是越早之前访问过的。

每次访问缓存时,将节点移动到链表尾部表示最近才访问过的,所以最近使用越多的越接近链表尾部,最近使用越少的越接近链表头部。

每次添加缓存时,缓存空间够的情况下,直接添加到链表尾部,否则当缓存空间不够时,优先淘汰链表头部的节点,即离最近最少使用的节点。

  1. 访问或添加缓存,链表中存在时:将其从原位置删除,再插入到链表尾部;
  2. 添加缓存,链表中不存在时:
  • 缓存未满:将数据直接插入链表尾部;
  • 缓存已满:先淘汰删除链表头结点,再将数据插入链表尾部;

代码实现:

1. 缓存接口
/**
 * 缓存接口
 *
 * @author LiuFeng
 * @date 2020/10/20
 */
public interface ICache {

    /**
     * 存入缓存
     *
     * @param key
     * @param value
     */
    void put(K key, V value);

    /**
     * 获取缓存
     *
     * @param key
     * @return
     */
    V get(K key);

    /**
     * 删除缓存
     *
     * @param key
     */
    void remove(K key);

    /**
     * 缓存中是否存在
     *
     * @param key
     * @return
     */
    boolean containsKey(K key);

    /**
     * 判断是否为空
     *
     * @return
     */
    boolean isEmpty();

    /**
     * 清空缓存
     */
    void clear();
}
2. 缓存实现类:
/**
 * 自定义LRU缓存
 * 描述:基于双向循环链表和散列表实现的LRU缓存
 * 时间复杂度:get和put都为O(1)
 *
 * @author LiuFeng
 * @data 2020/10/20
 */
public class CustomLRUCache implements ICache {

    // 缓存键的最大数量
    private int keyMaxNum;

    // 双向循环链表头结点
    private Node head;

    // 缓存数据
    private Map> cacheMap = new ConcurrentHashMap<>();

    /**
     * 构造方法
     *
     * @param keyMaxNum 缓存键的最大数量
     */
    public CustomLRUCache(int keyMaxNum) {
        if (keyMaxNum < 1) {
            throw new IllegalArgumentException("keyMaxNum has to be greater than 0");
        }

        this.keyMaxNum = keyMaxNum;
    }


    /**
     * 存入缓存
     *
     * @param key
     * @param value
     */
    @Override
    public synchronized void put(K key, V value) {
        // 超出缓存容量、且无此缓存数据时,移除尾结点的key
        if (cacheMap.size() >= keyMaxNum && !cacheMap.containsKey(key)) {
            Node tail = head.prev;
            remove(tail.key);
        }

        Node node = cacheMap.get(key);
        if (node != null) {
            // 当前结点是头结点时,就不更新结点位置
            if (node == head) {
                return;
            }

            // 存在前驱结点时,将前驱结点next指针指向后继结点
            if (node.prev != node) {
                node.prev.next = node.next;
            }

            // 存在后继结点时,将后继结点prev指针指向前驱结点
            if (node.next != node) {
                node.next.prev = node.prev;
            }
        } else {
            node = new Node<>(key, value, null, null);
        }

        // 头结点为空时,此时为链表无数据,让第一个结点前后指针都指向自己
        if (head == null) {
            node.prev = node;
            node.next = node;
        } else {
            // 头结点的前驱结点即tail尾结点
            Node tail = head.prev;

            // 修改当前结点前后指针
            node.prev = tail;
            node.next = tail.next;

            // 修改head头结点prev指针,指向新的头结点
            tail.next.prev = node;

            // 修改tail尾结点next指针,指向新的头结点
            tail.next = node;
        }

        // 保存最新头结点数据
        head = node;

        // 缓存数据
        cacheMap.put(key, node);
    }

    /**
     * 获取缓存
     *
     * @param key
     * @return
     */
    @Override
    public synchronized V get(K key) {
        Node node = cacheMap.get(key);
        if (node == null) {
            return null;
        }

        if (node != head) {
            // 存在前驱结点时,将前驱结点next指针指向后继结点
            if (node.prev != node) {
                node.prev.next = node.next;
            }

            // 存在后继结点时,将后继结点prev指针指向前驱结点
            if (node.next != node) {
                node.next.prev = node.prev;
            }

            // 头结点的前驱结点即tail尾结点
            Node tail = head.prev;

            // 修改当前结点前后指针
            node.prev = tail;
            node.next = tail.next;

            // 修改head头结点prev指针,指向新的头结点
            tail.next.prev = node;

            // 修改tail尾结点next指针,指向新的头结点
            tail.next = node;

            // 保存最新头结点数据
            head = node;
            cacheMap.put(key, node);
        }

        return node.value;
    }

    /**
     * 删除缓存
     *
     * @param key
     */
    @Override
    public synchronized void remove(K key) {
        Node node = cacheMap.get(key);
        if (node != null) {
            // 存在前驱结点时,将前驱结点next指针指向后继结点
            if (node.prev != node) {
                node.prev.next = node.next;
            }

            // 存在后继结点时,将后继结点prev指针指向前驱结点
            if (node.next != node) {
                node.next.prev = node.prev;
            }

            // 移除的是头结点时
            if (node == head) {
                // 链表仅包含一个结点时,head置空,否则指向后继结点
                if (node == head.next) {
                    head = null;
                } else {
                    head = head.next;
                }
            }

            cacheMap.remove(key);
        }
    }

    /**
     * 缓存中是否存在
     *
     * @param key
     * @return
     */
    @Override
    public synchronized boolean containsKey(K key) {
        return cacheMap.containsKey(key);
    }

    /**
     * 判断是否为空
     *
     * @return
     */
    @Override
    public synchronized boolean isEmpty() {
        return cacheMap.isEmpty();
    }

    /**
     * 清空缓存
     */
    @Override
    public synchronized void clear() {
        head = null;
        cacheMap.clear();
    }

    /**
     * 双向链表结点
     *
     * @param 
     * @param 
     */
    private class Node {
        K key;
        V value;
        Node prev;
        Node next;

        Node(K key, V value, Node prev, Node next) {
            this.key = key;
            this.value = value;
            this.prev = prev;
            this.next = next;
        }
    }
}
3. 业务简化消息实体类
/**
 * 简化消息实体类
 *
 * @author LiuFeng
 * @data 2020/10/20
 */
public class Message {
    /**
     * 消息唯一序列号id
     */
    public long messageId;
    
    /**
     * 时间戳
     */
    public long timestamp;

    /**
     * 消息会话id(一个群、好友等)
     */
    public String sessionId;

    /**
     * 消息内容
     */
    public String content;
}
4. 业务IM消息缓存类
/**
 * 最近会话缓存
 *
 * @author LiuFeng
 * @data 2020/10/20
 */
public class MessageCache {
    private static final MessageCache instance = new MessageCache();

    // 缓存池最多缓存多少个最近会话消息
    public static final int SESSION_MAX_NUM = 50;

    // 缓存池每个最近会话消息最多缓存多少个消息体
    public static final int MESSAGE_MAX_NUM = 20;

    // LRU缓存容器
    private CustomLRUCache> cache = new CustomLRUCache<>(SESSION_MAX_NUM);

    /**
     * 私有化构造函数
     */
    private MessageCache() {}

    /**
     * 获取单例
     *
     * @return
     */
    public static MessageCache getInstance() {
        return instance;
    }

    /**
     * 获取数据
     *
     * @param sessionId
     * @return
     */
    public List getData(@NonNull String sessionId) {
        Map messageMap = cache.get(sessionId);
        if (messageMap != null) {
            List messages = new ArrayList<>(messageMap.values());
            sort(messages);
            return messages;
        }

        return null;
    }

    /**
     * 设置新数据(将清理旧的缓存)
     *
     * @param sessionId
     * @param messages
     */
    public void setNewData(@NonNull String sessionId, @NonNull List messages) {
        cache.remove(sessionId);
        addData(sessionId, messages);
    }

    /**
     * 添加数据
     *
     * @param sessionId
     * @param message
     */
    public void addData(@NonNull String sessionId, @NonNull Message message) {
        addData(sessionId, Collections.singletonList(message));
    }

    /**
     * 添加数据
     *
     * @param sessionId
     * @param messages
     */
    public void addData(@NonNull String sessionId, @NonNull List messages) {
        // 边界值处理
        if (messages == null || messages.isEmpty()) {
            return;
        }

        Map messageMap = cache.get(sessionId);
        if (messageMap == null) {
            // 新添加缓存容器
            messageMap = new ConcurrentHashMap<>(MESSAGE_MAX_NUM);
            cache.put(sessionId, messageMap);
        }

        // 新消息超过最大数量,直接清空旧数据、截取集合
        int outSize = messages.size() - MESSAGE_MAX_NUM;
        if (outSize > 0) {
            messageMap.clear();
            // 消息时间从小到大排序,这里从集合尾部截取最新MESSAGE_MAX_NUM条
            messages = messages.subList(outSize, messages.size());
        }

        // 新旧总消息超过最大数量,整体移动清除旧数据
        outSize = (messageMap.size() + messages.size()) - MESSAGE_MAX_NUM;
        if (outSize > 0) {
            List oldMessages = new ArrayList<>(messageMap.values());
            sort(oldMessages);
            for (int i = 0; i < outSize; i++) {
                Message oldMessage = oldMessages.get(i);
                messageMap.remove(oldMessage.messageId);
            }
        }

        // 新存入缓存
        for (Message message : messages) {
            messageMap.put(message.messageId, message);
        }
    }

    /**
     * 移除会话
     *
     * @param sessionId
     */
    public void remove(@NonNull String sessionId) {
        cache.remove(sessionId);
    }

    /**
     * 移除会话的某条消息
     *
     * @param sessionId
     * @param messageId
     */
    public void remove(@NonNull String sessionId, long messageId) {
        if (cache.containsKey(sessionId)) {
            Map messageMap = cache.get(sessionId);
            if (messageMap != null && !messageMap.isEmpty()) {
                messageMap.remove(messageId);
            }
        }
    }

    /**
     * 判空
     *
     * @return
     */
    public boolean isEmpty() {
        return cache.isEmpty();
    }

    /**
     * 是否包含会话
     *
     * @param sessionId
     * @return
     */
    public boolean containsKey(@NonNull String sessionId) {
        return cache.containsKey(sessionId);
    }

    /**
     * 是否包含会话的某条消息
     *
     * @param sessionId
     * @param messageId
     * @return
     */
    public boolean containsKey(@NonNull String sessionId, long messageId) {
        if (cache.containsKey(sessionId)) {
            Map messageMap = cache.get(sessionId);
            if (messageMap != null && !messageMap.isEmpty()) {
                return messageMap.containsKey(messageId);
            }
        }

        return false;
    }

    /**
     * 清空缓存
     */
    public void clear() {
        cache.clear();
    }

    /**
     * 按时间戳升序排序
     *
     * @param messages
     */
    private void sort(List messages) {
        Collections.sort(messages, (o1, o2) -> {
            long diff = o1.timestamp - o2.timestamp;
            return diff > 0 ? 1 : diff == 0 ? 0 : -1;
        });
    }
}

以上代码实现中,1、2是LRU算法实现的容器类工具,可以直接使用,而3、4则是基于IM消息场景具体的封装使用,可供参考。

注意:在这个聊天消息的业务场景中,我以50个聊天会话作为LRU最大缓存数,每个会话存储了最多20条消息,多个会话来回点击时,每个会话是遵循LRU策略的,但具体的消息是value部分,不遵守LRU策略的,消息的条数限制是在MessageCache中限制的。

你可能感兴趣的:(基于IM消息场景实现的LRU缓存淘汰算法)