public interface LocalCacheService { void addChannel(String id, Channel channel); Channel getChannel(String id); boolean isChannelExists(String id); void removeChannel(String id); long getConnectNum(); } /** * @author jacky */ @Service public class LocalCacheServiceImpl implements LocalCacheService { private static final Logger LOGGER = LoggerFactory.getLogger(LocalCacheService.class); @Value("${channel_cache_max_size:100000}") private int cacheMaxSize; // channel cache 超时时间(秒) @Value("${cache_expire_after_access_seconds:600}") private int cacheExpireAfterAccessSeconds; // channel cache 日志打印间隔时间(分钟) @Value("${cache_stats_schedule_minutes:2}") private int cacheStatsScheduleMinutes; private Cache<String, Channel> channelCache; @PostConstruct private void init() { channelCache = CacheBuilder.newBuilder() .maximumSize(cacheMaxSize) .expireAfterAccess(cacheExpireAfterAccessSeconds, TimeUnit.SECONDS) .recordStats() .removalListener(new RemovalListener<String, Channel>() { @Override public void onRemoval(RemovalNotification<String, Channel> notification) { LOGGER.info("channel cache remove: {}, cause: {}.", notification.getKey(), notification.getCause()); } }) .build(); Executors.newScheduledThreadPool(1).scheduleAtFixedRate(new Runnable() { @Override public void run() { channelCache.cleanUp(); LOGGER.info("session cache size:{}, stats:{}.", channelCache.size(), channelCache.stats()); } }, cacheStatsScheduleMinutes, cacheStatsScheduleMinutes, TimeUnit.MINUTES); } @Override public void addChannel(String id, Channel channel) { channelCache.put(id, channel); } @Override public Channel getChannel(String id) { return channelCache.getIfPresent(id); } @Override public boolean isChannelExists(String id) { return null != channelCache.getIfPresent(id); } @Override public void removeChannel(String id) { channelCache.invalidate(id); } @Override public long getConnectNum() { return channelCache.size(); } }
Guava缓存实现
最新推荐文章于 2024-07-08 16:18:50 发布