WSO2 Mediator Tutorial: How to use the cache

Daniel S. Blanco
2 min readJan 15, 2021

--

Today we will return to post about WSO2 and its mediators. We will see how the Cache Mediator works, which can be very useful although it is not very well known.

The idea is simple, through this mediator, WSO2 will cache the response of a given backend based on the request we are going to make. How does it do it? It obtains a hash value associated with the message stored in the flow. If it exists it will execute the sequence configured in the onCacheHit parameter, which is optional. It obtains the response stored in the cache and sends the response. If it does not exist, it calls the backend and stores the response for possible future use.

Let’s see a simple example of its use. We are going to create an API resource that calls a backend, made with Wiremock, and before which we will configure the Cache Mediator for its use. In the mediator we will also configure several things apart from the default ones. Like the cache is remained for 20 seconds, that it only caches the calls of POST methods and that at most it stores 10 elements in the cache.

Next, we will perform an API invocation using cURL. If we look at the wso2carbon.log with wire enable, the first time we will see how the Wiremock is invoked, and when we call again a second time not.

curl --location --request POST 'http://localhost:8280/cache/sample1' 
--header 'Content-Type: application/json'
--data-raw '{}'

As you can see in the example, the use of cache mediator is divided into two parts. The first one contains the configuration of the cache itself before calling the backend. The second, a new invocation to the mediator. This time to indicate that it returns the value associated with it. If it exists any. In this second invocation is not necessary to configure anything, just indicate true the collector parameter.

The cache mediator can also be used for calls to the backend through the call mediator. In the case that we decide that we want to use it this way, we will also have to indicate to Synapse after the call to the backend, that we are dealing with an answer message. We will do this through the RESPONSE property. Without that property, in this example, the cache mediator will not work.

As you can see, it is very simple to use and requires almost no configuration. With the only problem that it does not have a method that allows you to delete the cache for a particular message, so if the answer is no longer valid, it can only be changed once the cache expires.

--

--

No responses yet