How to use Redis with Spring Boot via reactive way
Traditional caching implementation with Spring is easy, thanks to @Cacheable annotation. But when it comes to implementing that in a reactive way, unfortunately, it doesn’t work. Spring provides decent tools to use Redis in a reactive way.
For example, to access Redis, we could use ReactiveRedisTemplate provided by Spring. At first look, we can implement a cache service such as :
But, this implementation is too strict, not reusable, and not expandable. We are supposed to find a better way to fix these problems.
We talked about the @Cacheable annotation that Spring provides for traditional caching at the very first of the article. Could we inspire from that and create a similar annotation? Yeah, why not. We know that Spring uses aspects to make @Cacheable annotation work. So we can create an annotation and an aspect to meet our needs.
Let's create an annotation named RedisReactiveCacheGet:
Let's write an aspect to catch methods that are annotated with our annotation:
Well, as you can see, if we use ReactiveRedisTemplate as we have used before, we can have a reusable and expandable reactive caching implementation. For example, we can rewrite the getCustomerById(..) method like that:
In this article, we discussed how we can find a better way to use Reactive Redis. Our point was to find out how it could be done. We didn’t create a real implementation for the aspect. The implementation of the aspect may change to your requirements. This post should give you an idea. But if you want to see a real implementation, you can check ours that we have created for Kotlin and Coroutines:
Also, there is a Java and Reactor implementation that has been created by github/Bryksin. You can check that too. https://github.com/Bryksin/redis-reactive-cache