作者:vivo 互联网服务器团队- wang zhi
caffeine 作为一个高性能的缓存框架而被大量使用。本文基于caffeine已有的基础进行定制化开发实现可视化功能。
一、背景
caffeine缓存是一个高性能、可扩展、内存优化的 java 缓存库,基于 google 的 guava cache演进而来并提供了接近最佳的命中率。
caffeine 缓存包含以下特点:
-
高效快速:caffeine 缓存使用近似算法和并发哈希表等优化技术,使得缓存的访问速度非常快。
-
内存友好:caffeine 缓存使用一种内存优化策略,能够根据需要动态调整缓存的大小,有效地利用内存资源。
-
多种缓存策略:caffeine 缓存支持多种缓存策略,如基于容量、时间、权重、手动移除、定时刷新等,并提供了丰富的配置选项,能够适应不同的应用场景和需求。
-
支持异步加载和刷新:caffeine 缓存支持异步加载和刷新缓存项,可以与 spring 等框架无缝集成。
-
清理策略:caffeine 使用 window tinylfu 清理策略,它提供了接近最佳的命中率。
-
支持自动加载和自动过期:caffeine 缓存可以根据配置自动加载和过期缓存项,无需手动干预。
-
统计功能:caffeine 缓存提供了丰富的统计功能,如缓存命中率、缓存项数量等,方便评估缓存的性能和效果。
正是因为caffeine具备的上述特性,caffeine作为项目中本地缓存的不二选择,越来越多的项目集成了caffeine的功能,进而衍生了一系列的业务视角的需求。
日常使用的需求之一希望能够实时评估caffeine实例的内存占用情况并能够提供动态调整缓存参数的能力,但是已有的内存分析工具mat需要基于dump的文件进行分析无法做到实时,这也是整个事情的起因之一。
二、业务的技术视角
能够对项目中的caffeine的缓存实例能够做到近实时统计,实时查看缓存的实例个数。
能够对caffeine的每个实例的缓存配置参数、内存占用、缓存命中率做到实时查看,同时能够支持单个实例的缓存过期时间,缓存条目等参数进行动态配置下发。
能够对caffeine的每个实例的缓存数据做到实时查看,并且能够支持缓存数据的立即失效等功能。
基于上述的需求背景,结合caffeine的已有功能和定制的部分源码开发,整体作为caffeine可视化的技术项目进行推进和落地。
三、可视化能力
caffeine可视化项目目前已支持功能包括:
项目维度的全局缓存实例的管控。
单缓存实例配置信息可视化、内存占用可视化、命中率可视化。
单缓存实例的数据查询、配置动态变更、缓存数据失效等功能。
3.1 缓存实例的全局管控
说明:
以应用维度+机器维度展示该应用下包含的缓存实例对象,每个实例包含缓存设置中的大小、过期策略、过期时间、内存占用、缓存命中率等信息。
单实例维度的内存占用和缓存命中率支持以趋势图进行展示。
单实例维度支持配置变更操作和缓存查询操作。
3.2 内存占用趋势
说明:
内存占用趋势记录该缓存实例对象近一段时间内存占用的趋势变化。
时间周期目前支持展示近两天的数据。
3.3 命中率趋势
说明:
命中率趋势记录该缓存实例对象近一段时间缓存命中的变化情况。
时间周期目前支持展示近两天的数据。
3.4 配置变更
说明:
配置变更目前支持缓存大小和过期时间的动态设置。
目前暂时支持单实例的设置,后续会支持全量生效功能。
3.5 缓存查询
说明:
单实例维度支持缓存数据的查询。
目前支持常见的缓存key类型包括string类型、long类型、int类型。
四、原理实现
4.1 整体设计框架
caffeine框架功能整合
说明:
沿用caffeine的基础功能包括caffeine的缓存功能和caffeine统计功能。
新增caffeine内存占用预估功能,该功能主要是预估缓存实例对象占用的内存情况。
新增caffeine实例命名功能,该功能是针对每个实例对象提供命名功能,是全局管控的基础。
新增caffeine实例全局管控功能,该功能主要维护项目运行中所有的缓存实例。
caffeine可视化框架
说明:
【项目工程侧】:caffeine的可视化框架基于caffeine框架功能整合的基础上增加通信层进行数据数据上报和配置的下发。
【管控平台侧】:负责缓存数据上报的接收展示,配置变更命令的下发。
【通信层支持push和pull两种模式】,push模式主要用于统计数据的实时上报,pull模式主要用于配置下发和缓存数据查询。
4.2 源码实现
业务层-缓存对象的管理
static cache<string, list<string>> accountwhitecache = caffeine.newbuilder()
.expireafterwrite(vivoconfigmanager.getinteger("trade.account.white.list.cache.ttl", 10), timeunit.minutes)
.recordstats().maximumsize(vivoconfigmanager.getinteger("trade.account.white.list.cache.size", 100)).build();
常规的caffeine实例的创建方式
static cache<string, list<string>> accountwhitecache = caffeine.newbuilder().applyname("accountwhitecache")
.expireafterwrite(vivoconfigmanager.getinteger("trade.account.white.list.cache.ttl", 10), timeunit.minutes)
.recordstats().maximumsize(vivoconfigmanager.getinteger("trade.account.white.list.cache.size", 100)).build();
支持实例命名的caffeine实例的创建方式
说明:
在caffeine实例创建的基础上增加了缓存实例的命名功能,通过.applyname("accountwhitecache")来定义缓存实例的命名。
public final class caffeine<k, v> {
/**
* caffeine的实例名称
*/
string instancename;
/**
* caffeine的实例维护的map信息
*/
static map<string, cache> cacheinstancemap = new concurrenthashmap<>();
public <k1 extends k, v1 extends v> cache<k1, v1> build() {
requireweightwithweigher();
requirenonloadingcache();
"unchecked") (
caffeine<k1, v1> self = (caffeine<k1, v1>) this;
cache localcache = isbounded() ? new boundedlocalcache.boundedlocalmanualcache<>(self) : new unboundedlocalcache.unboundedlocalmanualcache<>(self);
if (null != localcache && stringutils.isnotempty(localcache.getinstancename())) {
cacheinstancemap.put(localcache.getinstancename(), localcache);
}
return localcache;
}
}
说明:
每个caffeine都有一个实例名称instancename。
全局通过cacheinstancemap来维护caffeine实例对象的名称和实例的映射关系。
通过维护映射关系能够通过实例的名称查询到缓存实例对象并对缓存实例对象进行各类的操作。
caffeine实例的命名功能是其他功能整合的基石。
业务层-内存占用的预估
import jdk.nashorn.internal.ir.debug.objectsizecalculator;
public abstract class boundedlocalcache<k, v> extends blcheader.drainstatusref<k, v>
implements localcache<k, v> {
final concurrenthashmap<object, node<k, v>> data;
public long getmemoryused() {
// 预估内存占用
return objectsizecalculator.getobjectsize(data);
}
}
说明:
通过objectsizecalculator.getobjectsize预估内存的缓存值。
data值是caffeine实例用来保存真实数据的对象。
业务层-数据上报机制
public static statsdata getcachestats(string instancename) {
cache cache = caffeine.getcachebyinstancename(instancename);
cachestats cachestats = cache.stats();
statsdata statsdata = new statsdata();
statsdata.setinstancename(instancename);
statsdata.settimestamp(system.currenttimemillis()/1000);
statsdata.setmemoryused(string.valueof(cache.getmemoryused()));
statsdata.setestimatedsize(string.valueof(cache.estimatedsize()));
statsdata.setrequestcount(string.valueof(cachestats.requestcount()));
statsdata.sethitcount(string.valueof(cachestats.hitcount()));
statsdata.sethitrate(string.valueof(cachestats.hitrate()));
statsdata.setmisscount(string.valueof(cachestats.misscount()));
statsdata.setmissrate(string.valueof(cachestats.missrate()));
statsdata.setloadcount(string.valueof(cachestats.loadcount()));
statsdata.setloadsuccesscount(string.valueof(cachestats.loadsuccesscount()));
statsdata.setloadfailurecount(string.valueof(cachestats.loadfailurecount()));
statsdata.setloadfailurerate(string.valueof(cachestats.loadfailurerate()));
optional<eviction> optionaleviction = cache.policy().eviction();
optionaleviction.ifpresent(eviction -> statsdata.setmaximumsize(string.valueof(eviction.getmaximum())));
optional<expiration> optionalexpiration = cache.policy().expireafterwrite();
optionalexpiration.ifpresent(expiration -> statsdata.setexpireafterwrite(string.valueof(expiration.getexpiresafter(timeunit.seconds))));
optionalexpiration = cache.policy().expireafteraccess();
optionalexpiration.ifpresent(expiration -> statsdata.setexpireafteraccess(string.valueof(expiration.getexpiresafter(timeunit.seconds))));
optionalexpiration = cache.policy().refreshafterwrite();
optionalexpiration.ifpresent(expiration -> statsdata.setrefreshafterwrite(string.valueof(expiration.getexpiresafter(timeunit.seconds))));
return statsdata;
}
说明:
通过caffeine自带的统计接口来统计相关数值。
统计数据实例维度进行统计。
public static void sendreportdata() {
try {
if (!vivoconfigmanager.getboolean("memory.caffeine.data.report.switch", true)) {
return;
}
// 1、获取所有的cache实例对象
method listcacheinstancemethod = handler_manager_class.getmethod("listcacheinstance", null);
list<string> instancenames = (list)listcacheinstancemethod.invoke(null, null);
if (collectionutils.isempty(instancenames)) {
return;
}
string appname = system.getproperty("app.name");
string localip = getlocalip();
string localport = string.valueof(netportutils.getworkport());
reportdata reportdata = new reportdata();
instancedata instancedata = new instancedata();
instancedata.setappname(appname);
instancedata.setip(localip);
instancedata.setport(localport);
// 2、遍历cache实例对象获取缓存监控数据
method getcachestatsmethod = handler_manager_class.getmethod("getcachestats", string.class);
map<string, statsdata> statsdatamap = new hashmap<>();
instancenames.stream().foreach(instancename -> {
try {
statsdata statsdata = (statsdata)getcachestatsmethod.invoke(null, instancename);
statsdatamap.put(instancename, statsdata);
} catch (exception e) {
}
});
// 3、构建上报对象
reportdata.setinstancedata(instancedata);
reportdata.setstatsdatamap(statsdatamap);
// 4、发送http的post请求
httppost httppost = new httppost(getreportdataurl());
httppost.setconfig(requestconfig);
stringentity stringentity = new stringentity(json.tojsonstring(reportdata));
stringentity.setcontenttype("application/json");
httppost.setentity(stringentity);
httpresponse response = httpclient.execute(httppost);
string result = entityutils.tostring(response.getentity(),"utf-8");
entityutils.consume(response.getentity());
logger.info("caffeine 数据上报成功 url {} 参数 {} 结果 {}", getreportdataurl(), json.tojsonstring(reportdata), result);
} catch (throwable throwable) {
logger.error("caffeine 数据上报失败 url {} ", getreportdataurl(), throwable);
}
}
说明:
通过获取项目中运行的所有caffeine实例并依次遍历收集统计数据。
通过http协议负责上报对应的统计数据,采用固定间隔周期进行上报。
业务层-配置动态下发
public static executionresponse dispose(executionrequest request) {
executionresponse executionresponse = new executionresponse();
executionresponse.setcmdtype(cmdtypeenum.instance_configure.getcmd());
executionresponse.setinstancename(request.getinstancename());
string instancename = request.getinstancename();
cache cache = caffeine.getcachebyinstancename(instancename);
// 设置缓存的最大条目
if (null != request.getmaximumsize() && request.getmaximumsize() > 0) {
optional<eviction> optionaleviction = cache.policy().eviction();
optionaleviction.ifpresent(eviction ->eviction.setmaximum(request.getmaximumsize()));
}
// 设置写后过期的过期时间
if (null != request.getexpireafterwrite() && request.getexpireafterwrite() > 0) {
optional<expiration> optionalexpiration = cache.policy().expireafterwrite();
optionalexpiration.ifpresent(expiration -> expiration.setexpiresafter(request.getexpireafterwrite(), timeunit.seconds));
}
// 设置访问过期的过期时间
if (null != request.getexpireafteraccess() && request.getexpireafteraccess() > 0) {
optional<expiration> optionalexpiration = cache.policy().expireafteraccess();
optionalexpiration.ifpresent(expiration -> expiration.setexpiresafter(request.getexpireafteraccess(), timeunit.seconds));
}
// 设置写更新的过期时间
if (null != request.getrefreshafterwrite() && request.getrefreshafterwrite() > 0) {
optional<expiration> optionalexpiration = cache.policy().refreshafterwrite();
optionalexpiration.ifpresent(expiration -> expiration.setexpiresafter(request.getrefreshafterwrite(), timeunit.seconds));
}
executionresponse.setcode(0);
executionresponse.setmsg("success");
return executionresponse;
}
说明:
通过caffeine自带接口进行缓存配置的相关设置。
业务层-缓存数据清空
/**
* 失效缓存的值
* @param request
* @return
*/
public static executionresponse invalidate(executionrequest request) {
executionresponse executionresponse = new executionresponse();
executionresponse.setcmdtype(cmdtypeenum.instance_invalidate.getcmd());
executionresponse.setinstancename(request.getinstancename());
try {
// 查找对应的cache实例
string instancename = request.getinstancename();
cache cache = caffeine.getcachebyinstancename(instancename);
// 处理清空指定实例的所有缓存 或 指定实例的key对应的缓存
object cachekeyobj = request.getcachekey();
// 清除所有缓存
if (objects.isnull(cachekeyobj)) {
cache.invalidateall();
} else {
// 清除指定key对应的缓存
if (objects.equals(request.getcachekeytype(), 2)) {
cache.invalidate(long.valueof(request.getcachekey().tostring()));
} else if (objects.equals(request.getcachekeytype(), 3)) {
cache.invalidate(integer.valueof(request.getcachekey().tostring()));
} else {
cache.invalidate(request.getcachekey().tostring());
}
}
executionresponse.setcode(0);
executionresponse.setmsg("success");
} catch (exception e) {
executionresponse.setcode(-1);
executionresponse.setmsg("fail");
}
return executionresponse;
}
}
业务层-缓存数据查询
public static executionresponse inspect(executionrequest request) {
executionresponse executionresponse = new executionresponse();
executionresponse.setcmdtype(cmdtypeenum.instance_inspect.getcmd());
executionresponse.setinstancename(request.getinstancename());
string instancename = request.getinstancename();
cache cache = caffeine.getcachebyinstancename(instancename);
object cachevalue = cache.getifpresent(request.getcachekey());
if (objects.equals(request.getcachekeytype(), 2)) {
cachevalue = cache.getifpresent(long.valueof(request.getcachekey().tostring()));
} else if (objects.equals(request.getcachekeytype(), 3)) {
cachevalue = cache.getifpresent(integer.valueof(request.getcachekey().tostring()));
} else {
cachevalue = cache.getifpresent(request.getcachekey().tostring());
}
if (objects.isnull(cachevalue)) {
executionresponse.setdata("");
} else {
executionresponse.setdata(json.tojsonstring(cachevalue));
}
return executionresponse;
}
说明:
通过caffeine自带接口进行缓存信息查询。
通信层-监听服务
public class servermanager {
private server jetty;
/**
* 创建jetty对象
* @throws exception
*/
public servermanager() throws exception {
int port = netportutils.getavailableport();
jetty = new server(port);
servletcontexthandler context = new servletcontexthandler(servletcontexthandler.no_sessions);
context.setcontextpath("/");
context.addservlet(clientservlet.class, "/caffeine");
jetty.sethandler(context);
}
/**
* 启动jetty对象
* @throws exception
*/
public void start() throws exception {
jetty.start();
}
}
public class clientservlet extends httpservlet {
private static final logger logger = loggerfactory.getlogger(clientservlet.class);
protected void doget(httpservletrequest req, httpservletresponse resp) throws servletexception, ioexception {
super.doget(req, resp);
}
protected void dopost(httpservletrequest req, httpservletresponse resp) throws servletexception, ioexception {
executionresponse executionresponse = null;
string requestjson = null;
try {
// 获取请求的相关的参数
string contextpath = req.getcontextpath();
string servletpath = req.getservletpath();
string requesturi = req.getrequesturi();
requestjson = ioutils.tostring(req.getinputstream(), standardcharsets.utf_8);
// 处理不同的命令
executionrequest executionrequest = json.parseobject(requestjson, executionrequest.class);
// 通过反射来来处理类依赖问题
executionresponse = disposecenter.dispatch(executionrequest);
} catch (exception e) {
logger.error("vivo-memory 处理请求异常 {} ", requestjson, e);
}
if (null == executionresponse) {
executionresponse = new executionresponse();
executionresponse.setcode(-1);
executionresponse.setmsg("处理异常");
}
// 组装相应报文
resp.setcontenttype("application/json; charset=utf-8");
printwriter out = resp.getwriter();
out.println(json.tojsonstring(executionresponse));
out.flush();
}
}
说明:
通信层通过jetty启动http服务进行监听,安全考虑端口不对外开放。
通过定义clientservlet来处理相关的请求包括配置下发和缓存查询等功能。
通信层-心跳设计
/**
* 发送心跳数据
*/
public static void sendheartbeatdata() {
try {
if (!vivoconfigmanager.getboolean("memory.caffeine.heart.report.switch", true)) {
return;
}
// 1、构建心跳数据
string appname = system.getproperty("app.name");
string localip = getlocalip();
string localport = string.valueof(netportutils.getworkport());
heartbeatdata heartbeatdata = new heartbeatdata();
heartbeatdata.setappname(appname);
heartbeatdata.setip(localip);
heartbeatdata.setport(localport);
heartbeatdata.settimestamp(system.currenttimemillis()/1000);
// 2、发送http的post请求
httppost httppost = new httppost(getheartbeaturl());
httppost.setconfig(requestconfig);
stringentity stringentity = new stringentity(json.tojsonstring(heartbeatdata));
stringentity.setcontenttype("application/json");
httppost.setentity(stringentity);
httpresponse response = httpclient.execute(httppost);
string result = entityutils.tostring(response.getentity(),"utf-8");
entityutils.consume(response.getentity());
logger.info("caffeine 心跳上报成功 url {} 参数 {} 结果 {}", getheartbeaturl(), json.tojsonstring(heartbeatdata), result);
} catch (throwable throwable) {
logger.error("caffeine 心跳上报失败 url {} ", getheartbeaturl(), throwable);
}
}
说明:
心跳功能上报项目实例的ip和端口用来通信,携带时间戳用来记录上报时间戳。
实际项目中因为机器的回收等场景需要通过上报时间戳定时清理下线的服务。
五、总结
vivo技术团队在caffeine的使用经验上曾有过多次分享,可参考公众号文章《如何把 caffeine cache 用得如丝般顺滑》,此篇文章在使用的基础上基于使用痛点进行进一步的定制。
目前caffeine可视化的项目已经在相关核心业务场景中落地并发挥作用,整体运行平稳。使用较多的功能包括项目维度的caffeine实例的全局管控,单实例维度的内存占用评估和缓存命中趋势评估。
如通过单实例的内存占用评估功能能够合理评估缓存条目设置和内存占用之间的关系;通过分析缓存命中率的整体趋势评估缓存的参数设置合理性。
期待此篇文章能够给业界缓存使用和监控带来一些新思路。
end
猜你喜欢
发表评论