最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java中本地緩存的4種實現(xiàn)方式總結

 更新時間:2025年04月11日 10:04:52   作者:呱牛?do?IT  
這篇文章主要介紹了Java中本地緩存的4種實現(xiàn)方式,分別是基礎緩存實現(xiàn)、GuavaLoadingCache、SpringBoot整合Caffeine和JetCache,通過實例代碼,詳細講解了每種緩存技術的特點和使用方法,需要的朋友可以參考下

前言

在Java開發(fā)中,緩存技術是提高應用性能的關鍵手段之一。

今天,我們來聊聊Java中的四種主流本地緩存技術,并通過實例代碼幫助大家更好地理解和應用這些技術。

一、基礎緩存實現(xiàn)

首先,我們從最基礎的緩存實現(xiàn)講起。

一個簡單的緩存系統(tǒng)通常包括緩存實體類、添加、刪除、查詢和清除緩存的功能。

1. 緩存實體類

緩存實體類用于存儲緩存的鍵值對以及過期時間。

代碼如下:。

public class CacheEntity {
    private String cacheKey;
    private Object cacheValue;
    private long expireTime; // 過期時間戳

    // 構造方法、getter和setter省略
}

2. 緩存工具類

接下來,我們實現(xiàn)一個緩存工具類,使用ConcurrentHashMap作為存儲結構,并通過定時任務清除過期數(shù)據(jù)。

import java.util.concurrent.*;
import java.util.Map;

publicclassCacheUtil {
    privatefinalstatic Map<String, CacheEntity> CACHE_MAP = newConcurrentHashMap<>();
    privatestaticScheduledExecutorServiceexecutorService= Executors.newSingleThreadScheduledExecutor();

    static {
        executorService.scheduleAtFixedRate(() -> {
            longcurrentTime= System.currentTimeMillis();
            CACHE_MAP.values().removeIf(entity -> entity.getExpireTime() < currentTime);
        }, 0, 500, TimeUnit.MILLISECONDS);
    }

    publicstaticvoidput(String key, Object value, long expireTimeInSeconds) {
        longexpireTime= System.currentTimeMillis() + expireTimeInSeconds * 1000;
        CACHE_MAP.put(key, newCacheEntity(key, value, expireTime));
    }

    publicstatic Object get(String key) {
        CacheEntityentity= CACHE_MAP.get(key);
        if (entity == null || entity.getExpireTime() < System.currentTimeMillis()) {
            CACHE_MAP.remove(key);
            returnnull;
        }
        return entity.getCacheValue();
    }

    publicstaticvoiddelete(String key) {
        CACHE_MAP.remove(key);
    }

    publicstaticvoidclear() {
        CACHE_MAP.clear();
    }
}

測試代碼:

public class Test {
    public static void main(String[] args) throws InterruptedException {
        CacheUtil.put("name", "zzc", 10L);
        System.out.println("第一次查詢結果:" + CacheUtil.get("name"));
        Thread.sleep(2000L);
        System.out.println("第二次查詢結果:" + CacheUtil.get("name"));
    }
}

二、Guava LoadingCache

Guava是Google提供的一個Java基礎庫,其中的LoadingCache是一個強大的緩存工具。

1. 使用示例

import com.google.common.cache.*;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

publicclassTest {
    publicstaticvoidmain(String[] args)throws ExecutionException {
        LoadingCache<String, String> cache = CacheBuilder.newBuilder()
                .concurrencyLevel(8)
                .expireAfterWrite(10, TimeUnit.SECONDS)
                .build(newCacheLoader<String, String>() {
                    @Override
                    public String load(String key)throws Exception {
                        return"default_value";
                    }
                });

        cache.put("name", "zzc");
        StringnameValue= cache.get("name");
        StringageValue= cache.get("age", () -> "default_age");
        StringsexValue= cache.get("sex", () -> "key 不存在");

        System.out.println("nameValue: " + nameValue);
        System.out.println("ageValue: " + ageValue);
        System.out.println("sexValue: " + sexValue);
    }
}

在上面的代碼中,當調(diào)用cache.get(key)方法時,如果緩存中不存在對應的key,則會通過CacheLoaderload方法加載默認值。

三、SpringBoot整合Caffeine

Caffeine是一個高性能的Java緩存庫,SpringBoot提供了與Caffeine的無縫整合。

1. 開啟緩存功能

在啟動類上添加@EnableCaching注解。

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@EnableCaching
@SpringBootApplication
public class TestApplication {
    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
    }
}

2. 配置緩存管理器

import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

@Configuration
@EnableCaching
publicclassCacheConfig {

    @Bean("caffeineCacheManager")
    public CacheManager cacheManager() {
        CaffeineCacheManagercacheManager=newCaffeineCacheManager("userCache");
        cacheManager.getCache("userCache").getConfig().setCaffeine(caffeineCacheBuilder());
        return cacheManager;
    }

    Caffeine<Object, Object> caffeineCacheBuilder() {
        return Caffeine.newBuilder()
                .expireAfterWrite(10, TimeUnit.SECONDS)
                .maximumSize(100);
    }
}

3. 使用緩存注解

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
publicclassUserService {

    // 模擬數(shù)據(jù)庫操作
    private Map<Integer, User> userMap = newHashMap<>();

    @Cacheable(value = "userCache", key = "#id")
    public User getUserById(Integer id) {
        // 假設從數(shù)據(jù)庫獲取用戶數(shù)據(jù)
        Useruser=newUser();
        user.setId(id);
        user.setName("User" + id);
        userMap.put(id, user);
        return user;
    }

    @CacheEvict(value = "userCache", key = "#id")
    publicvoiddeleteUserById(Integer id) {
        userMap.remove(id);
    }
}

四、JetCache——阿里巴巴的分布式緩存框架

JetCache是阿里巴巴開源的一款基于Spring和Redis的分布式緩存框架,提供了強大的緩存抽象和注解支持。

1. 引入依賴

pom.xml中添加JetCache依賴。

<dependency>
    <groupId>com.alicp.jetcache</groupId>
    <artifactId>jetcache-starter-redis</artifactId>
    <version>最新版本號</version>
</dependency>

2. 配置JetCache

application.yml中配置JetCache。

jetcache:
  stat:enable# 開啟統(tǒng)計
remote:
    default:
      type:redis
      keyConvertor:fastjson# 序列化方式
      valueEncoder:java
      valueDecoder:java
      poolConfig:
        minIdle:5
        maxIdle:20
        maxTotal:50
      host:localhost
      port: 6379

3. 使用JetCache注解

import com.alicp.jetcache.anno.CacheType;
import com.alicp.jetcache.anno.Cached;
import com.alicp.jetcache.anno.CacheUpdate;
import com.alicp.jetcache.anno.CacheInvalidate;
import org.springframework.stereotype.Service;

@Service
publicclassUserService {
    @Cached(name = "userCache", key = "#id", cacheType = CacheType.BOTH)
    public String getUser(int id) {
        return"用戶:" + id;
    }

    @CacheUpdate(name = "userCache", key = "#id", value = "#user")
    publicvoidupdateUser(int id, String user) {
        System.out.println("更新用戶:" + user);
    }

    @CacheInvalidate(name = "userCache", key = "#id")
    publicvoiddeleteUser(int id) {
        System.out.println("刪除用戶:" + id);
    }
}

JetCache支持本地緩存和遠程緩存的組合,非常適合分布式系統(tǒng)。

總結

今天我們一起探索了Java本地緩存的多種實現(xiàn)方式,從手寫緩存到Guava Cache、Caffeine、Ehcache和JetCache。每種方式都有自己的特點和適用場景。

到此這篇關于Java中本地緩存的4種實現(xiàn)方式的文章就介紹到這了,更多相關Java本地緩存實現(xiàn)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • java學習筆記之馬踏棋盤算法

    java學習筆記之馬踏棋盤算法

    這篇文章主要為大家詳細介紹了java學習筆記之馬踏棋盤算法,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-02-02
  • Spring Cloud實現(xiàn)微服務調(diào)用的負載均衡(詳解)

    Spring Cloud實現(xiàn)微服務調(diào)用的負載均衡(詳解)

    負載均衡就是將負載(工作任務,訪問請求)進行分攤到多個操作單元(服務器,組件)上進行執(zhí)行,根據(jù)負載均衡發(fā)生位置的不同,一般分為服務端負載均衡和客戶端負載均衡,本文給大家介紹Spring Cloud實現(xiàn)微服務調(diào)用的負載均衡的相關知識,感興趣的朋友一起看看吧
    2024-03-03
  • IntelliJ?IDEA?2022安裝注冊永久激活

    IntelliJ?IDEA?2022安裝注冊永久激活

    java開發(fā)工具IntelliJ?IDEA深受用戶喜愛,很多朋友對這個idea開發(fā)工具比較忠心,一旦有新版本發(fā)出,很多小伙伴就迫不及待的想更新,今天小編給大家?guī)砹薸dea2022.1最新永久激活碼,親測有效,喜歡的朋友快來下載體驗吧
    2022-08-08
  • 解決新版 Idea 中 SpringBoot 熱部署不生效的問題

    解決新版 Idea 中 SpringBoot 熱部署不生效的問題

    這篇文章主要介紹了解決新版 Idea 中 SpringBoot 熱部署不生效的問題,本文通過圖文并茂的形式給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2023-08-08
  • Java利用Spire.XLS for Java實現(xiàn)在Excel文件中添加或刪除分節(jié)符

    Java利用Spire.XLS for Java實現(xiàn)在Excel文件中添加或刪除分節(jié)符

    在復雜的Excel報表中,合理設置分節(jié)符能有效提升文檔結構與可讀性,尤其在打印輸出時效果顯著,本文將深入探討如何利用Spire.XLS for Java輕松實現(xiàn)Excel分節(jié)符的添加與刪除,希望對大家有所幫助
    2025-11-11
  • springboot 配置文件配置項前綴為0的數(shù)字特殊處理方式

    springboot 配置文件配置項前綴為0的數(shù)字特殊處理方式

    這篇文章主要介紹了springboot 配置文件配置項前綴為0的數(shù)字特殊處理方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-02-02
  • Java基礎精講方法的使用

    Java基礎精講方法的使用

    方法,也稱函數(shù),如果想要重復一段或者多段代碼塊的使用,可以將這些代碼封裝成一個方法,方法具體表現(xiàn)為某種行為,使用方法可以提高代碼的復用性
    2022-05-05
  • Hibernate映射文件id的generator配置方法

    Hibernate映射文件id的generator配置方法

    下面小編就為大家分享一篇Hibernate映射文件id的generator配置方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2017-12-12
  • 深入了解Spring中的依賴注入DI

    深入了解Spring中的依賴注入DI

    這篇文章主要介紹了Spring?中的依賴注入,包括注入的方式,寫法,該選擇哪個注入方式以及可能出現(xiàn)的循環(huán)依賴問題等內(nèi)容,需要的可以參考一下
    2023-06-06
  • IntelliJ IDEA編譯提速的兩種配置指南(中性能&高性能)

    IntelliJ IDEA編譯提速的兩種配置指南(中性能&高性能)

    很多開發(fā)者發(fā)現(xiàn),明明電腦配置挺高,IDEA 編譯 Maven 項目依然卡,本文帶大家從原理到實戰(zhàn),提供 兩套可直接復制使用的 VM 參數(shù)方案,有需要的小伙伴可以了解下
    2025-10-10

最新評論

信丰县| 平定县| 绥棱县| 衡东县| 渭南市| 彰化县| 施秉县| 鹰潭市| 泰兴市| 行唐县| 柞水县| 遂川县| 阿荣旗| 巫山县| 东乌珠穆沁旗| 尉犁县| 大关县| 德清县| 黄龙县| 开化县| 宣武区| 涡阳县| 通海县| 河东区| 油尖旺区| 洪雅县| 永济市| 九江市| 隆昌县| 黄大仙区| 通州区| 盐池县| 闻喜县| 基隆市| 牟定县| 博爱县| 南宁市| 蒙山县| 苍溪县| 瑞安市| 图们市|