|
| 1 | +/* |
| 2 | + * Copyright 2018-2021 ProfunKtor |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package dev.profunktor.redis4cats.caching |
| 18 | + |
| 19 | +import cats.effect.{ ContextShift, Effect, Resource, Sync } |
| 20 | +import dev.profunktor.redis4cats.effect.RedisExecutor |
| 21 | +import io.lettuce.core.TrackingArgs |
| 22 | +import io.lettuce.core.api.StatefulRedisConnection |
| 23 | +import io.lettuce.core.support.caching.{ |
| 24 | + CacheAccessor => JCacheAccessor, |
| 25 | + CacheFrontend => JCacheFrontend, |
| 26 | + ClientSideCaching => JClientSideCaching |
| 27 | +} |
| 28 | + |
| 29 | +object ClientSideCaching { |
| 30 | + |
| 31 | + def make[F[_]: ContextShift: Sync: Effect, K, V]( |
| 32 | + connection: StatefulRedisConnection[K, V], |
| 33 | + args: TrackingArgs, |
| 34 | + cacheAccessor: CacheAccessor[F, K, V] |
| 35 | + ): Resource[F, JCacheFrontend[K, V]] = |
| 36 | + RedisExecutor.make[F].flatMap { redisExecutor => |
| 37 | + Resource.make[F, JCacheFrontend[K, V]] { |
| 38 | + Sync[F].delay { |
| 39 | + JClientSideCaching.enable( |
| 40 | + new JCacheAccessor[K, V] { |
| 41 | + override def get(key: K): V = redisExecutor.unsafeRun(cacheAccessor.get(key)) |
| 42 | + override def put(key: K, value: V): Unit = redisExecutor.unsafeRun(cacheAccessor.put(key, value)) |
| 43 | + override def evict(key: K): Unit = redisExecutor.unsafeRun(cacheAccessor.evict(key)) |
| 44 | + }, |
| 45 | + connection, |
| 46 | + args |
| 47 | + ) |
| 48 | + } |
| 49 | + }(cacheFrontend => Sync[F].delay(cacheFrontend.close())) |
| 50 | + } |
| 51 | +} |
0 commit comments