All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.zodiac.cache.reactive.supports.GuavaReactiveCache Maven / Gradle / Ivy

The newest version!
package org.zodiac.cache.reactive.supports;

import com.google.common.cache.Cache;

import org.reactivestreams.Publisher;
import org.zodiac.cache.reactive.AbstractReactiveCache;

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.Arrays;

public class GuavaReactiveCache extends AbstractReactiveCache {

    private Cache cache;

    public GuavaReactiveCache(Cache cache) {
        this.cache = cache;
    }

    @Override
    public Flux getFlux(Object key) {
        return (Flux)Flux.defer(() -> {
            Object v = cache.getIfPresent(key);
            if (v == null) {
                return Flux.empty();
            }
            if (v instanceof Iterable) {
                return Flux.fromIterable(((Iterable) v));
            }
            return Flux.just(v);
        });
    }

    @Override
    public Mono getMono(Object key) {
        return (Mono)Mono.defer(() -> {
            Object v = cache.getIfPresent(key);
            if (v == null) {
                return Mono.empty();
            }
            return (Mono) Mono.just(v);
        });
    }

    @Override
    public Mono put(Object key, Publisher data) {
        return Mono.defer(() -> {
            if (data instanceof Flux) {
                return ((Flux) data).collectList()
                        .doOnNext(v -> cache.put(key, v))
                        .then();
            }
            if (data instanceof Mono) {
                return ((Mono) data)
                        .doOnNext(v -> cache.put(key, v))
                        .then();
            }
            return Mono.error(new UnsupportedOperationException("unsupport publisher:" + data));
        });
    }

    @Override
    public Mono evictAll(Iterable key) {
        return Mono.fromRunnable(() -> cache.invalidateAll(key));
    }

    @Override
    public Mono evict(Object key) {
        return Mono.fromRunnable(() -> cache.invalidate(key));
    }
    @Override
    public Flux getAll(Object... keys) {
        return Flux.defer(() -> {
            return Flux.fromIterable(cache.getAllPresent(Arrays.asList(keys)).values())
                    .map(e -> (E) e);
        });
    }

    @Override
    public Mono clear() {
        return Mono.fromRunnable(() -> cache.invalidateAll());
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy