首页 > 其他分享 >使用guava的cache实现缓存

使用guava的cache实现缓存

时间:2023-06-29 10:11:06浏览次数:38  
标签:缓存 String cache connection Connection split key import guava

一、maven

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>sshcache</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>sshcache</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>

        <dependency>
            <groupId>ch.ethz.ganymed</groupId>
            <artifactId>ganymed-ssh2</artifactId>
            <version>build210</version>
        </dependency>

        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>23.3-jre</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

二、代码

import ch.ethz.ssh2.Connection;
import com.google.common.base.Joiner;
import com.google.common.cache.*;

import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

public class SshConnectionUtil {

    private static LoadingCache<String,Connection> sshLoadingCache = null;
    static {
        sshLoadingCache = CacheBuilder.newBuilder()
                .expireAfterAccess(5,TimeUnit.MINUTES)
                .maximumSize(1000)
                .removalListener(new RemovalListener<String, Connection>(){
                    @Override
                    public void onRemoval(RemovalNotification<String, Connection> removalNotification) {
                        if(!Objects.isNull(removalNotification.getValue())){
                            removalNotification.getValue().close();
                            removalNotification.setValue(null);
                        }
                        String key = removalNotification.getKey();
                        System.out.println("ip:" + key.substring(0,key.indexOf(',')) + " removed");

                    }
                } )
                .build(new CacheLoader<String, Connection>() {
                    @Override
                    public Connection load(String key) {
                        //从SQL或者NoSql 获取对象
                        //Iterable<String> split = Splitter.on(',').split(key);
                        String[] split = key.split(",");
                        String username = split.length == 3 ? split[2] : "root";
                        String password = split[1];
                        String ip = split[0];


                        Connection connection = new Connection(ip, 22);
                        boolean b = false;
                        try {
                            connection.addConnectionMonitor(v -> {
                                System.out.println(v);
                            });
                            b = connection.authenticateWithPassword(username, password);
                            if(b) {
                                return connection;
                            }else {
                                return null;
                            }
                        }catch (IOException e){
                            e.printStackTrace();
                        }catch (Exception e){
                            e.printStackTrace();
                        }finally {
                            if(!b){
                                connection.close();
                            }
                        }
                        return null;
                    }
        });
    }



    public static Connection getConnection(String ip,String password,String username){
        String join = Joiner.on(',').skipNulls().join(ip, password, username);
        try {
            Connection connection = sshLoadingCache.get(join);
            return connection;
        }catch (ExecutionException e){
            e.printStackTrace();
        }
        return null;
    }


    public static void main(String[] args) {
        Connection root = SshConnectionUtil.getConnection("192.168.11.110", "123456", "root");
        System.out.println(root);
    }

}

 

 

博客原文:https://blog.csdn.net/xiaolixi199311/article/details/117902680

标签:缓存,String,cache,connection,Connection,split,key,import,guava
From: https://www.cnblogs.com/robots2/p/17513300.html

相关文章

  • 10redis列表操作,其他操作,redis管道,django中使用redis,django缓存,序列化json和pickle,cel
    字符串和字节转换的两种方式#字符串和字节转换的两种方式 -decode,encode-直接类型转换-bytes格式的16进制,2进制,10进制的显示#字符串需要用encode,bytes格式需要用decode,但是有时候忘了#可以直接进行强转b1=bytes(s,encoding='utf-8') print(......
  • 【Java技术专题】「Guava开发指南」手把手教你如何进行使用Guava工具箱进行开发系统实
    为什么要使用不可变集合不可变集合包括元组和冻结集合,其特点是不能被修改。元组有序、不可变、可包含不同类型元素,不能进行修改、删除操作,可通过索引访问元素。冻结集合是一种无序的集合类型,内部元素不能修改、添加或删除,因此常用于处理集合的不可变。不可变对象有很多优点不可变对......
  • gdb.exe: warning: Couldn't determine a path for the index cache directory.
    GDB调试中出现的警告D:\\gitee\\luatos-soc-2022\\out\\example_copy>arm-none-eabi-gdbexample.elfC:\\SysGCC\\bin\\arm-none-eabi-gdb.exe:warning:**Couldn'tdetermineapathfortheindexcachedirectory.......
  • django缓存的使用
    缓存:可以把django中的一个变量(数据),存放到某个位置,下次还可以取出来之前用过:默认放在:内存中,其实可以放在文件中,数据库,redis。。。。fromdjango.core.cacheimportcachecache.set('key','value',5)#存放值res=cache.get('key')#取值通过配置,控制存放在哪,只要如下写,就会......
  • 什么是缓存穿透、缓存击穿、缓存雪崩
     缓存穿透(CachePenetration)是指在使用缓存时,对于一些不存在于缓存中的数据进行频繁访问,导致这些请求直接绕过缓存,查询数据库,并返回空结果。由于缓存无法命中,每次请求都需要经过数据库查询,这会增加数据库的负载压力,并可能导致缓慢的响应时间。缓存击穿(CacheBr......
  • vue组件动态缓存与动态刷新
    动态缓存前言在项目中,为了减少性能消耗,有时我们需要使用keep-alive把组件缓存起来,但是并不是所有组件都需要被缓存,那么如何控制那些组件需要缓存呢?主要使用到路由meta,路由前置守卫,vux,动态组件。实现APP.vue<scriptsetup>import{ref,computed}from'vue'import{useRo......
  • 缓存同步
    大多数情况下,浏览器查询到的都是缓存数据,如果缓存数据与数据库数据存在较大差异,可能会产生比较严重的后果。所以我们必须保证数据库数据、缓存数据的一致性,这就是缓存与数据库的同步。数据同步策略缓存数据同步的常见方式有三种:设置有效期:给缓存设置有效期,到期后自动删除。再......
  • MacOS 清除软件缓存和配置文件
    MacOS清除软件缓存和配置文件最近在mac上安装并激活软件的时候遇到问题,不论如何重新安装软件,软件都不会更新软件信息,推断需要删除软件的配置文件macos软件安装后,文件所在的路径在macos上,软件安装会将缓存等文件存放到如下可能的路径:Binaryanddockiconsarelocatedin/Ap......
  • ABP - 缓存模块(2)
    1.缓存模块源码解析个人觉得ABP分布式缓存模块有三个值得关注的核心点。首先是AbpRedisCache类继承了微软原生的RedisCache,并通过反射的方式获取RedisCache的私有方法对RedisCache进行扩展,实现了ABP分布式缓存中的批量操作方法。为什么要这么做呢?因为基于Redis缓......
  • 缓存的常见问题以及SpringCache的解决方案
    总体来说,缓存在使用的过程中主要面临以下几个问题:缓存击穿(某个热点数据的key失效了)缓存中无数据,但是数据库中有数据,由于是热点key,如果同一时间大量请求进来会导致数据库压力大增缓存雪崩与缓存击穿类似,只不过缓存雪崩是多个热点key同时失效缓存穿透查询不存在的数据,当同时......