当前位置:首页 > Java

java 如何设置缓存

2026-03-20 22:50:37Java

设置缓存的基本方法

在Java中设置缓存可以通过多种方式实现,包括使用内置的集合类、第三方缓存库或框架。以下是几种常见的方法:

使用ConcurrentHashMap实现简单缓存

import java.util.concurrent.ConcurrentHashMap;

public class SimpleCache<K, V> {
    private final ConcurrentHashMap<K, V> cache = new ConcurrentHashMap<>();

    public void put(K key, V value) {
        cache.put(key, value);
    }

    public V get(K key) {
        return cache.get(key);
    }

    public void remove(K key) {
        cache.remove(key);
    }
}

使用Guava Cache Google Guava库提供了强大的缓存功能,支持过期策略、最大容量限制等:

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;

public class GuavaCacheExample {
    public static void main(String[] args) {
        Cache<String, String> cache = CacheBuilder.newBuilder()
            .maximumSize(100) // 最大缓存条目数
            .expireAfterWrite(10, TimeUnit.MINUTES) // 写入后10分钟过期
            .build();

        cache.put("key1", "value1");
        String value = cache.getIfPresent("key1");
    }
}

使用Spring Cache抽象

Spring框架提供了缓存抽象,可以方便地与多种缓存实现集成:

启用Spring缓存

@Configuration
@EnableCaching
public class CacheConfig {
    @Bean
    public CacheManager cacheManager() {
        return new ConcurrentMapCacheManager("products");
    }
}

在方法上使用缓存注解

@Service
public class ProductService {
    @Cacheable("products")
    public Product getProductById(String id) {
        // 模拟数据库查询
        return findProductInDatabase(id);
    }

    @CacheEvict("products")
    public void refreshProduct(String id) {
        // 清除缓存
    }
}

使用Ehcache

Ehcache是一个广泛使用的Java缓存库:

配置Ehcache

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="ehcache.xsd">
    <cache name="products"
           maxEntriesLocalHeap="1000"
           timeToLiveSeconds="3600"/>
</ehcache>

Java代码中使用Ehcache

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

public class EhcacheExample {
    public static void main(String[] args) {
        CacheManager cacheManager = CacheManager.newInstance();
        Cache cache = cacheManager.getCache("products");

        Element element = new Element("key1", "value1");
        cache.put(element);

        Element cached = cache.get("key1");
    }
}

使用Redis作为分布式缓存

对于分布式系统,可以使用Redis作为缓存:

Spring Boot集成Redis

java 如何设置缓存

@Configuration
public class RedisConfig {
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        return template;
    }
}

@Service
public class ProductService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public void cacheProduct(String id, Product product) {
        redisTemplate.opsForValue().set(id, product);
    }

    public Product getCachedProduct(String id) {
        return (Product) redisTemplate.opsForValue().get(id);
    }
}

缓存策略考虑因素

  • 过期时间:设置合理的缓存过期时间,避免数据过时
  • 缓存大小:限制缓存大小防止内存溢出
  • 淘汰策略:LRU(最近最少使用)或FIFO(先进先出)等
  • 线程安全:确保缓存在多线程环境下安全访问
  • 持久化:考虑是否需要将缓存持久化到磁盘

选择哪种缓存实现取决于具体需求,简单场景可以使用内存缓存,分布式系统则需要考虑Redis等分布式缓存解决方案。

分享给朋友:

相关文章

vue实现页面缓存

vue实现页面缓存

Vue 实现页面缓存的常用方法 使用 <keep-alive> 组件 <keep-alive> 是 Vue 内置组件,用于缓存动态组件或路由组件。通过包裹需要缓存的组件,可以保…

react如何设置数据

react如何设置数据

设置数据的常见方法 在React中设置数据通常涉及组件的状态管理,可以通过以下几种方式实现: 使用useState Hook(函数组件) import React, { useState } fr…

vue实现缓存视频

vue实现缓存视频

Vue 实现视频缓存的方法 在 Vue 中实现视频缓存可以通过多种方式完成,包括使用浏览器的缓存机制、Service Worker 或者借助第三方库。以下是几种常见的方法: 使用 Service W…

vue路由实现缓存

vue路由实现缓存

Vue 路由实现缓存的常用方法 使用 <keep-alive> 组件 在 Vue 中可以通过 <keep-alive> 组件缓存路由组件,避免重复渲染。需要将 <keep…

vue实现页面跳转缓存

vue实现页面跳转缓存

Vue 实现页面跳转缓存的方法 在 Vue 中实现页面跳转缓存通常需要使用 keep-alive 组件结合路由配置。以下是几种常见的实现方式: 使用 keep-alive 包裹 router-vie…

vue实现页面的缓存

vue实现页面的缓存

Vue 实现页面缓存的方法 在 Vue 中实现页面缓存可以通过 keep-alive 组件结合路由配置或动态组件实现。以下是几种常见的方法: 使用 keep-alive 缓存路由组件 在路由出口外包…