你从不重用
您在每次调用时都会创建一个新的记忆供应商,因此
我们在每 30 秒运行一次的 HeartBeat
线程中有以下方法,我们引入了 Guava 缓存,刷新 5 分钟,如下所示ClientsDAO.getClients()
这样我们就不会每 30 秒访问一次数据库。
private List<String> getClients() {
final Supplier<List<String>> supplier = () -> ClientsDAO.getClients();
if(Server.CACHE_REFRESH_DURATION <=0)
return supplier.get();
else{
LOG.debug("Fetching Clients from cache, duration = "+Server.CACHE_REFRESH_DURATION+". timeunit = "+Server.CACHE_REFRESH_TIMEUNIT);
return Suppliers.memoizeWithExpiration(supplier, Server.CACHE_REFRESH_DURATION, Server.CACHE_REFRESH_TIMEUNIT).get();
}
}
正如您在下面的日志中看到的那样,每次线程HeartBeat
运行它访问数据库而不是从缓存中获取它时。 有人可以帮我修复它吗?
[Jun 10 10:16:05] pool-16-thread-1 | DEBUG | com.server.Heartbeat | Fetching Clients from cache, duration = 5. timeunit = MINUTES
[Jun 10 10:16:05] pool-16-thread-1 | DEBUG | com.server.ClientsDAO | Getting DB connection
[Jun 10 10:16:05] pool-16-thread-1 | DEBUG | com.server.ClientsDAO | Queried for Clients
[Jun 10 10:16:35] pool-16-thread-1 | DEBUG | com.server.Heartbeat | Fetching Clients from cache, duration = 5. timeunit = MINUTES
[Jun 10 10:16:35] pool-16-thread-1 | DEBUG | com.server.ClientsDAO | Getting DB connection
[Jun 10 10:16:35] pool-16-thread-1 | DEBUG | com.server.ClientsDAO | Queried for Clients
[Jun 10 10:17:05] pool-16-thread-1 | DEBUG | com.server.Heartbeat | Fetching Clients from cache, duration = 5. timeunit = MINUTES
[Jun 10 10:17:05] pool-16-thread-1 | DEBUG | com.server.ClientsDAO | Getting DB connection
[Jun 10 10:17:05] pool-16-thread-1 | DEBUG | com.server.ClientsDAO | Queried for Clients
你从不重用Suppliers.memoizeWithExpiration
所以它总是一个新的调用
您在每次调用时都会创建一个新的记忆供应商,因此您基本上每次都会进行一个新调用,因为新的记忆供应商是空的,因此会传播调用以填充自身。你应该只创建一次记忆供应商,并像这样反复调用它:
private final Supplier<List<Client>> getClientsSupplier = Suppliers.memoizeWithExpiration(ClientsDao::getClients, Server.CACHE_REFRESH_DURATION, Server.CACHE_REFRESH_TIMEUNIT);
public List<Client> getClients() {
return getClientsSupplier.get();
}