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

com.github.bootfastconfig.cache.caffeine.CaffeineBuilder Maven / Gradle / Ivy

package com.github.bootfastconfig.cache.caffeine;

import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.bootfastconfig.cache.CacheBuilder;
import com.github.bootfastconfig.cache.Duration;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import org.springframework.cache.caffeine.CaffeineCache;

import java.util.concurrent.TimeUnit;

/**
 * @author mister
 */
@Data
@Accessors(chain = true)
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class CaffeineBuilder implements CacheBuilder {

    /**
     * 初始的缓存空间大小
     */
    private Integer initialCapacity;
    /**
     * 缓存的最大条数
     */
    private Long maximumSize;
    /**
     * 缓存的最大权重
     */
    private Long maximumWeight;
    /**
     * 最后一次写入或访问后经过固定时间过期
     */
    private Duration expireAfterAccess;
    /**
     * 最后一次写入后经过固定时间过期
     */
    private Duration expireAfterWrite;

    /**
     * 缓存名称
     */
    private String name;

    public Integer getInitialCapacity() {
        if (initialCapacity == null) {
            return 100;
        }
        return initialCapacity;
    }

    public Long getMaximumSize() {
        if (maximumWeight == null && maximumSize == null) {
            return 300L;
        }
        return maximumSize;
    }

    public Long getMaximumWeight() {
        return maximumWeight;
    }

    public Duration getExpireAfterAccess() {

        return expireAfterAccess;
    }

    public Duration getExpireAfterWrite() {
        if (expireAfterAccess == null && expireAfterWrite == null) {
            expireAfterWrite = new Duration(120, TimeUnit.SECONDS);
            return expireAfterWrite;
        }
        return expireAfterWrite;
    }

    @Override
    public CaffeineCache get() {
        Caffeine objectObjectCaffeine = Caffeine.newBuilder();
        if (getInitialCapacity() != null) {
            objectObjectCaffeine.initialCapacity(getInitialCapacity());
        }
        if (getExpireAfterAccess() != null) {
            objectObjectCaffeine.expireAfterAccess(getExpireAfterAccess().getDuration(), getExpireAfterAccess().getUnit());
        }
        if (getExpireAfterWrite() != null) {
            objectObjectCaffeine.expireAfterWrite(getExpireAfterWrite().getDuration(), getExpireAfterWrite().getUnit());
        }
        if (getMaximumSize() != null) {
            objectObjectCaffeine.maximumSize(getMaximumSize());
        } else if (getMaximumWeight() != null) {
            objectObjectCaffeine.maximumWeight(getMaximumWeight());
        }
        return new CaffeineCache(name, objectObjectCaffeine.build());
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy