All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.fartherp.shiro.ClearCache Maven / Gradle / Ivy

/*
 * Copyright (c) 2019. CK. All rights reserved.
 */

package com.github.fartherp.shiro;

import io.netty.util.HashedWheelTimer;
import io.netty.util.Timeout;
import io.netty.util.TimerTask;
import org.apache.shiro.cache.Cache;
import org.redisson.api.RScoredSortedSet;
import org.redisson.client.protocol.ScoredEntry;

import java.util.List;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * Created by IntelliJ IDEA.
 *
 * @author: CK
 * @date: 2019/1/4
 */
public class ClearCache implements TimerTask {
    private HashedWheelTimer hashedWheelTimer = new HashedWheelTimer();

    private RedisSessionDAO redisSessionDAO;

    public ClearCache(RedisSessionDAO redisSessionDAO) {
        this.redisSessionDAO = redisSessionDAO;
    }

    public void init() {
        hashedWheelTimer.newTimeout(this, redisSessionDAO.getRedisCacheManager().getTtl(), TimeUnit.SECONDS);
    }

    @SuppressWarnings("unchecked")
    public void clearSession() {
        RScoredSortedSet sessionKeys = redisSessionDAO.getSessionKeys();
        removeAll(sessionKeys, o -> (List) o.entryRange(0, false, System.currentTimeMillis(), true));
    }

    @SuppressWarnings("unchecked")
    public void clearCache() {
        ConcurrentMap caches = redisSessionDAO.getRedisCacheManager().getCaches();
        caches.forEach((k, v) -> {
            RedisCache redisCache = (RedisCache) v;
            RScoredSortedSet cacheKeys = redisCache.getCacheKeys();
            removeAll(cacheKeys, o -> (List) o.entryRange(0, false, System.currentTimeMillis(), true));
        });
    }

    @SuppressWarnings("unchecked")
    private void removeAll(RScoredSortedSet rScoredSortedSet, Function> fun) {
        List keys = fun.apply(rScoredSortedSet);
        List destroyKeys = keys.stream().map(ScoredEntry::getValue).collect(Collectors.toList());
        if (destroyKeys.size() > 0) {
            rScoredSortedSet.removeAll(destroyKeys);
        }
    }

    public void run(Timeout timeout) throws Exception {
        clearSession();
        clearCache();
        init();
    }
}