'Trigger Guava cache refresh when a table is updated

Presently am fectching the list of clients from db using ClientDAO.getClients() and caching using guava with 30 minutes refresh period as below

private List<String> getClients() {
        final Supplier<List<String>> supplier = () ->  ClientDAO.getClients();
        Suppliers.memoizeWithExpiration(supplier, 30, TimeUnit.MINUTES);
        return supplier.get();
    }

We have different application that updates client table and another application that reads from from the client table and caches as above and there is no Restful or any sort of api communication between these 2 applications. Is there any way to trigger this cache update whenever the corresponding client table in the database is updated instead of refreshing at specific time window 30 minutes?



Solution 1:[1]

So from the question I will assume:

  • there are two applications A and B
  • there's a client table - let's call it table X
  • A reads and caches data from table X
  • B writes data to table X

A needs to know when B has written in table X, so that A can update it's cached data.

option 1

If you control A and B, you can extend the behavior - when B writes to the database and the write is successful, B fires an event to A (e.g. invokes a REST endpoint) and A will know to update its cache.

option 2

If you can't control B, but you can control A and the DB, you can use the DB as integration point - it's a common approach for legacy apps - the DB is the only place where the applications can integrate.

So again you can apply the same concept of B fires an event to A, but this time the event (initiated by a trigger) is stored in a table in the DB and the REST call is made from the DB itself using an internal procedure.

A straight forward approach would be:

  • B writes data in table X
  • there's an insert trigger for table X, which does a single INSERT statement into event storage table (let's call it UPDATE_CACHE_EVENT)

Your "update_cache_event" is now fired (e.g. saved in that table) and from this point on you have more options:

  • A can monitor this table every second and trigger it's cache update when a new event is written

  • A exposes REST API, which is invoked from the DB - e.g. in SQL server write a procedure, that monitors UPDATE_CACHE_EVENT table and calls A's REST API.

option 3

Debezium

Some thoughts:

  • don't use a trigger itself to call the external API, use a dedicated procedure for that
  • the trigger has performance penalty (e.g. each write to table X will invoke another insert to the event table), so you should consider this when designing your solution.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1