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

io.github.danielliu1123.httpexchange.Cache Maven / Gradle / Ivy

There is a newer version: 3.4.0-RC1
Show newest version
package io.github.danielliu1123.httpexchange;

import static io.github.danielliu1123.httpexchange.HttpExchangeProperties.Channel;
import static io.github.danielliu1123.httpexchange.HttpExchangeProperties.ClientType;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;
import lombok.experimental.UtilityClass;
import org.springframework.aop.framework.AopProxyUtils;

/**
 * @author Freeman
 */
@UtilityClass
class Cache {
    /**
     * Cache all clients.
     */
    private static final Map, Object> classToInstance = new ConcurrentHashMap<>();
    /**
     * {@link ClientId} to Http client instance.
     */
    private static final Map clientIdToHttpClient = new ConcurrentHashMap<>();

    /**
     * Add a client to cache.
     *
     * @param client client
     */
    public static void addClient(Object client) {
        classToInstance.put(AopProxyUtils.ultimateTargetClass(client), client);
    }

    /**
     * Get clients.
     *
     * @return unmodifiable map
     */
    public static Map, Object> getClients() {
        return Map.copyOf(classToInstance);
    }

    @SuppressWarnings("unchecked")
    public static  T getHttpClient(ClientId clientId, Supplier supplier) {
        return (T) clientIdToHttpClient.computeIfAbsent(clientId, k -> supplier.get());
    }

    /**
     * Clear cache.
     */
    public static void clear() {
        classToInstance.clear();
        clientIdToHttpClient.clear();
    }

    record ClientId(Channel channel, ClientType clientType) {}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy