当前位置: 代码网 > it编程>编程语言>Java > Java 实现缓存的三种方式及问题汇总

Java 实现缓存的三种方式及问题汇总

2024年05月18日 Java 我要评论
java 实现缓存的三种方式一、hashmap实现缓存​ 可以实现简单的本地缓存,但是实际开发中不推荐,我们可以简单模拟一下缓存的实现,step-1:实现一个缓存管理类public class loc

java 实现缓存的三种方式

一、hashmap实现缓存

​ 可以实现简单的本地缓存,但是实际开发中不推荐,我们可以简单模拟一下缓存的实现,

step-1:实现一个缓存管理类

public class localcache {
    public static hashmap<string,string> cache = new hashmap<>();
    static {
        string name = uuid.randomuuid().tostring();
        localcache.cache.put(string.valueof(1),name);
        system.out.println("id为1的数据添加到了缓存");
    }
}
// 类中有 `static` 修饰的静态代码块,当类被加载的时候就会执行,如有不懂的可以如下博客
// https://blog.csdn.net/weixin_62636014/article/details/136851287

tips:我们在static中完成了对缓存的初始化,你可以往缓存里面放入初始数据。

step-2:将缓存管理类交给 spring 进行管理

@component
public class localcache {
    public static hashmap<string,string> cache = new hashmap<>();
    static {
        string name = uuid.randomuuid().tostring();
        localcache.cache.put(string.valueof(1),name);
        system.out.println("id为1的数据添加到了缓存");
    }
    @postconstruct
    public void init() {
        string name = uuid.randomuuid().tostring();
        localcache.cache.put(string.valueof(2),name);
        system.out.println("id为2的数据添加到了缓存");
    }
}

tips:在将缓存管理类交给了 spring进行管理后,在方法上加入@postconstruct,可以使方法默认执行,注意该注解不是 spring 框架提供,仅仅是由 java jdk 提供的,主要是作用于 servlet生命周期的注解,实现的是在 bean 初始化之前自定义操作

@postconstruct 方法在 bean初始化中的执行顺序

  • constructor(构造方法)
  • @autowired(依赖注入)
  • @postconstruct (注释的初始化方法)

step-3:编写接口测试缓存

@requestmapping("test")
public string test(long id) {
    string name = localcache.cache.get(string.valueof(id));
    if (name != null) {
        system.out.println("缓存中存在,查询缓存");
        system.out.println(name);
        return name;
    }
    system.out.println("缓存中不存在,查询数据库");
    // 查询数据库操作后,querydataname方法没有写了;
    // 大家可以自己配一下mybatis和jdbc进行数据库查询,达到效果是从库中查出来 name;
    name = querydataname(id);
    system.out.println(name);
    localcache.cache.put(string.valueof(id),name);
    return name;
}
public string querydataname(long id) {
    string name = uuid.randomuuid().tostring();
    return name;
}

step-4:结果展示

​ 这个是控制台输出,每个人的随机 uuid 不一致,我这个只是一个样例

id为1的数据添加到了缓存
id为2的数据添加到了缓存
缓存中存在,查询缓存
e2eadabe-3c42-4732-b465-e085ea5faf96
缓存中不存在,查询数据库
942ffe92-454f-4046-87e5-53e8b951d2a1

二、guava local cache 实现

tipsguavagoogle提供的一套java工具包,guava cache是一套非常完善的本地缓存机制(jvm缓存),工具类就是封装平常常用的方法,不需要你重复造轮子,节省开发人员时间,我们一般需要知道怎么使用。其设计来源于 currenthashmap,可以按照多种策略来清理存储在其中的缓存值且保持很高的并发读写性能。

guava 提供以下方面的能力

  • 集合 [collections]
  • 缓存 [caching]
  • 原生类型支持 [primitives support]
  • 并发库 [concurrency libraries]
  • 通用注解 [common annotations]
  • 字符串处理 [string processing]
  • i/o 等等。

step-1:导入guava 依赖

<dependency>
            <groupid>com.google.guava</groupid>
            <artifactid>guava</artifactid>
            <version>32.1.3-jre</version>
        </dependency>

step-2:使用guava创建简单缓存管理类

为了方便展示,这里面使用了5 秒的缓存保留时间。

import com.google.common.cache.cache;
import com.google.common.cache.cachebuilder;
import org.springframework.stereotype.component;
import java.util.concurrent.timeunit;
@component
public class guavalocalcache{
    private cache<string,string> fivesecondcache = cachebuilder.newbuilder()
        //设置缓存初始大小,应该合理设置,后续会扩容
        .initalcapacity(10)
        //最大值
        .maximumsize(100)
        //并发数设置
        .concurrencylevel(5)
        //缓存过期时间,写入后5秒钟过期
        .expireafterwrite(5,timeunit.seconds)
        //统计缓存命中率
        .recordstats()
        .build()
    public cache<string,string> getfivesecondcache() {
        return fivesecondcache;
    } // 这里就是拿到缓存对象。
    public void setfivesecondcache(cache<string,string> fivesecondcache) {
        this.fivesecondcache = fivesecondcache;
    }
}

step-3:使用 guava cache,并尝试统计命中率

public class test {
    @autowired
    private guavalocalcache guavalocalcache;
    @requestmapping("guavatest")
    public string guavatest(long id) {
        // 获取缓存
        cache<string,string> fivesecondcache = guavalocalcache.getfivesecondcache();
        // 从缓存中获取对象
        string namecache = fivesecondcache.getifpresent(string.valueof(id));
        // 缓存中存在
        if (namecache != null) {
            system.out.println("缓存命中:"+ namecache + "," + getcachestats(fivesecondcache));
            return namecache;
        }
        // 将数据存入缓存
        system.out.println("缓存未命中," + getcachestats(fivesecondcache));
        namecache = id + "-" + uuid.randomuuid().tostring();
        fivesecondcache.put(string.valueof(id),namecache);
        return namecache;
    }
    public string getcachestats(cache<string,string> cahce) {
        cachestats stats = cache.stats();
        return "缓冲命中率:"+stats.hitrate() +" 被清除缓冲数:" + stats.evictioncount();
    }
}

三、使用redis实现缓存

tipsredis (全称: remote dictionary server 远程字典服务)是一个开源的使用 ansi c语言 编写、支持网络、可基于内存亦可持久化的日志型、 key-value数据库 。redis 一般被用来做缓存用的,它实际上也是一种数据库(非关系型数据库),可以对经常使用到的数据进行存储,也就是大家所说的缓存。官方给出的数据是, redis 能达到 10w+qps( 每秒查询速度 ) 。

tips: 为什么 redis 的速度比 mysql 等这种数据快呢?

​ 因为 redis 存储的是 key-values 格式的数据,时间复杂度是 o(1) ,即直接通过 key 查询对应的 value 。 而如 mysql 数据库,底层的实现是 b+ 树,时间复杂度是 o(logn)

​ 最重要的一点是,数据库的数据是存储在磁盘中的,而 redis 是存储在内存当中的,它们的速度差距不言而喻。但 redis 也支持持久化存储

step-1:导入redis 依赖

        <dependency>
            <groupid>org.springframework.boot</groupid>
            <artifactid>spring-boot-starter-data-redis</artifactid>
        </dependency>

springboot 配置文件中加入设置,我使用的是yml 形式的文件,如果没有密码的话不填就好了

  redis:
    # ip地址
    host: xxx.xxx.xxx.xxx
    # 密码
    password: xxxxxxxx
    # 端口,默认为6379
    port: 6379
    # 数据库索引
    database: 0
    # 连接超时时间
    timeout: 10s
    lettuce:
      pool:
        # 连接池中的最小空闲连接
        min-idle: 1
        # 连接池中的最大空闲连接
        max-idle: 8
        # 连接池的最大数据库连接数
        max-active: 8
        # #连接池最大阻塞等待时间(使用负值表示没有限制)
        max-wait: -1ms

step-2:编写测试接口

public class testredis{
    // 下面stringredistemplate 是一个继承自 redistemplate的类
    @autowired
    private stringredistemplate stringredistemplate;
    @requestmapping("/redistest")
    public string rediscachetest(long id){
        string name = stringredistemplate.opsforvalue().get(string.valueof(id));
        if (name != null){
            system.out.println("缓存中存在,查询缓存");
            system.out.println(name);
            return name;
        }
        system.out.println("缓存中不存在,查询数据库");
        name = id + "-" + uuid.randomuuid().tostring();
        system.out.println(name);
        stringredistemplate.opsforvalue().set(string.valueof(id),name);
        return name;
    }
}

step-3:进行接口测试,并使用redis desktop manager 进行查看

参考文章 

  1. 【java缓存、redis缓存、guava缓存】java中实现缓存的几种方式_java缓存cache-csdn博客
  2. 一篇文章搞定 redis 基础知识 - 知乎 (zhihu.com)
  3. java本地缓存技术选型(guava cache、caffeine、encache) - 掘金 (juejin.cn)
  4. memcache原理超详细解读(仅学习) - 知乎 (zhihu.com)
  5. postconstruct注解详细使用说明及理解-csdn博客
  6. postconstruct (java platform se 8 ) (oracle.com)
  7. java开发利器guava cache之使用篇 - 掘金 (juejin.cn)
  8. google guava 工具类的介绍和使用 - 掘金 (juejin.cn)
  9. redis详细介绍(精简版)_redis 服务 精简-csdn博客
  10. 初识redis,看这一篇就够了

到此这篇关于java 实现缓存的三种方式问题汇总的文章就介绍到这了,更多相关java 实现缓存内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com