SpringBoot使用Google guava緩存

SpringBoot使用Google guava緩存

  • 開發環境
    • springboot
    • guava
    • docker-client
  • 應用場景
    • 用來存儲DockerClient的client連接,項目通過操作docker-client提供對docker的可視化界面操作,操作範圍沒有固定,可以是當前k8s集羣上的任意節點,或者是任意主機的docker,所以只能根據接口傳遞的主機ip和docker.service配置的port端口操作不同節點上的docker,因爲無法固定操作節點,當操作不同節點的時候需要重新對docker發起連接請求,比較耗時,所以打算將連接成功後的節點DockerClient對象存儲到緩存中,這樣用到的時候從緩存中,這樣避免頻繁發起連接請求。
  • 選擇Google guava的原因
    • guava是一個內存緩存模塊,用於將數據緩存到JVM內存中,在項目開發中可以將一些公共或者常用的數據緩存起來方便快速訪問,可以自動回收元素。
    • 願意消耗一些內存來提升速度
    • DockerClient會被查詢n次
    • 存放的數據總量不會超出內存容量

開始使用

  1. maven導包
    <dependency>
       <groupId>javax.cache</groupId>
        <artifactId>cache-api</artifactId>
        <version>1.1.0</version>
    </dependency>
    
    <dependency>
        <groupId>com.google.guava</groupId>
        <artifactId>guava</artifactId>
        <version>18.0</version>
    </dependency>
    
  2. 代碼示例
    import com.spotify.docker.client.DefaultDockerClient;
    import org.apache.commons.lang.StringUtils;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    import java.net.URI;
    
    public class DockerClientUtil {
    
        private static final Logger LOGGER = LoggerFactory.getLogger(DockerClientUtil.class);
    
        private static String DEFAULT_PORT = "2375";
    
        private static long CONNECT_TIMEOUT_MILLIS = 10000L;
    
        public static DefaultDockerClient getDockerClient(String hostPath, String port) throws Exception{
            if (StringUtils.isBlank(port)){
                port = DEFAULT_PORT;
            }
            DefaultDockerClient dockerClient;
            try {
                dockerClient = DefaultDockerClient.builder()
                        .connectTimeoutMillis(CONNECT_TIMEOUT_MILLIS)
                        .uri(URI.create("http://" + hostPath + ":" + port)).build();
            }catch (Exception e){
                LOGGER.error("DockerClient連接超時", e.getMessage());
                throw new Exception(e.getMessage());
            }
            return dockerClient;
        }
    }
    
    
    注:dockerclient相關jar包請參考:https://blog.csdn.net/weixin_42518062/article/details/103668710
    import com.csdn.demo.utils.DockerClientUtil;
    import com.google.common.cache.*;
    import com.spotify.docker.client.DefaultDockerClient;
    import org.slf4j.LoggerFactory;
    import org.slf4j.Logger;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    public class GuavaConfig {
    
        private static final Logger LOGGER = LoggerFactory.getLogger(GuavaConfig.class);
    
        public LoadingCache getDockerClient(){
            LoadingCache<Object, Object> loadingCache = CacheBuilder.newBuilder()
                    //設置併發級別,指可以同時進行緩存的線程數
                    .concurrencyLevel(5)
                    //設置緩存最大容量,超過之後就會按照LUR算反來移除緩存項
                    .maximumSize(5)
                    //設置緩存容器的初始化容量
                    .initialCapacity(2)
                    //設置緩存的移除通知
                    .removalListener(new RemovalListener<Object, Object>() {
                        @Override
                        public void onRemoval(RemovalNotification<Object, Object> removalNotification) {
                            LOGGER.info("緩存移除通知:" + removalNotification.getKey() + "被移除, 移除原因:" + removalNotification.getCause());
                        }
                    })
                    //在緩存不存在時通過cacheLoader實現自動加載緩存
                    .build(new CacheLoader<Object, Object>() {
                        @Override
                        public DefaultDockerClient load(Object key) throws Exception {
                            String[] split = ((String) key).split(":");
                            DefaultDockerClient dockerClient = DockerClientUtil.getDockerClient(split[0], split[1]);
                            return dockerClient;
                        }
                    });
    
            if (LOGGER.isInfoEnabled()){
                LOGGER.info("-----------------guava本地緩存初始化成功------------------");
            }
            return loadingCache;
        }
    }
    
    注:項目關閉重啓後緩存清空
發佈了45 篇原創文章 · 獲贊 6 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章