# Local Cache

## Basic Concept

The insurance administration system necessitates storing vast amounts of configuration data. It's super important to efficiently cache these data for better system performance and experience.

## User Scenario

For anybody who wants to know how to clean the cache and understand the cache mechanism for development purposes.

## UI Operation

Configuration data can be quite large. Each call to the DB for such data will greatly reduce the overall system performance. Thus, we need a cache mechanism to temporarily store the configuration data in memory for APIs to fetch. 

Normally, each time a configuration change is saved or deployed, the system will clean all caches in the back end automatically. Sometimes due to system performance issues, this cache cleaning might not work properly, which requires the system user to manually clean the cache. Some scenarios indicating a cache issue could be:

-  A field is mapped, but the system indicates it cannot be found.
-  A code table exists, but the system indicates it does not exist.

Generally speaking, when expected data has been added but the system reports its absence, it's advisable to suspect a cache problem and try to clear the current cache. Then, calling the resources, the local cache will be updated.

If a developer uses our platform to develop configuration-related functions in microservices, they can also utilize this feature to clean the cache.

![Local Cache](./image/monitor/local_cache.png)


## Development Practice

### Technology Selection

Ehcache 3.x

### Development Guidance

#### Maven Dependency

```
  <dependency>
         <groupId>com.ebao.vela</groupId>
            <artifactId>vela-cache-support</artifactId>
  </dependency>
```

#### Code Example

```
@Autowired
protected CacheManager cm;

 Cache cacheDDDataTableByName = cm.getCache("[CODETABLE]DataTableName->DataTable");
 String dataTableName="YesNoDataTable";
 Cache.ValueWrapper valueWrapper = cacheDDDataTableByName.get(dataTableName);
        if (valueWrapper != null) {
            return (BusinessDataTable) valueWrapper.get();
        }
        BusinessDataTable dataTable = noCacheService.loadDataTableByName(dataTableName);
        if (dataTable == null) {
            logger.warn("DataTable is not found! DataTable=[{}]", dataTableName);
            return null;
        }
        BusinessDataTable dataTableClone = dataTable.cloneEntity();
        
        //Maintain New Cache Entry
        cacheDDDataTableByName.put(dataTableName, dataTableClone);
        
        //Clean Cache Entry By Key
        cacheDDDataTableByName.evict(dataTableName);
        
        //Clean all Cache Entries for current Cache
        cacheDDDataTableByName.clear();
        
        //Clean Cache Entries By Bucket
       CacheUtils.clearBucket("[CODETABLE]");
```

## Tips for Cache Development with InsureMO App Framework

1. The use of the platform's cache scheme relies on the platform's cache-related function package. The most important is the `vela-cache-support` JAR, which encapsulates the `CacheManager` and the `Cache` object (`LocalCacheWrapper`).

2.  Customized cache configurations are stored in XML files under their respective module directories, adhering to the file path and naming rules: `resources/META-INF/v3-ehcache*.xml`.Taking dd module as an example:

    ![Local Cache](./image/monitor/ehcahcev3xml.png)

3. The cache between different application nodes is not shared, and the cache synchronization mechanism is completed through the clearing cache instruction in MQ messages. That is to say, when a node updates cached source data, it must call the cache clearing interface in the code to actively clean the cache and notify other service nodes to synchronously clean caches.

4. Methods used to actively clean up the cache and send MQ broadcasts are: `cache.evict(key)`, `cache.clear()`, and methods provided in `CacheUtils`.

5. All applications will receive the cached MQ message and make corresponding processing. 


## Tips for Cache Development without InsureMO App Framework

If your application does not rely on the InsureMO app framework, consider handling the configuration data cache at your local end by the application, especially for frequently accessed items like code tables.

Once there is a deployment at the InsureMO end updating configuration data, your application can listen to our cache history API to clean and refresh caches together at your local end.

```
curl --location --request GET 'TenantCode-gi-dev.insuremo.com/api/platform/platform-pub/public/cache/broadcast/message/v1/getRecordsByTimePeriod?startTime=2024-02-02T12:43:41'
```

The best way is to call this API at a frequent interval (e.g. every 1 minute) by specifying the time of the last local cache cleaning. If there's a new clearing history at the InsureMO end, clean your local cache.
