当前位置:首页 > 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 缓存实现原理 Vue 中的缓存主要通过 keep-alive 组件实现,用于缓存动态组件或路由组件,避免重复渲染和销毁,提升性能。 keep-alive 的核心机制 keep-alive 是…

vue路由如何实现缓存

vue路由如何实现缓存

Vue 路由实现缓存的方法 在 Vue 中,可以通过 keep-alive 组件结合路由配置实现页面缓存,从而保留组件状态或避免重复渲染。 基本用法 将 keep-alive 包裹 router-v…

node实现vue页面缓存

node实现vue页面缓存

使用 keep-alive 组件实现缓存 在 Vue 中,可以通过 <keep-alive> 组件缓存动态组件或路由组件。在 template 中包裹需要缓存的组件: <tem…

react如何设置代理

react如何设置代理

设置代理的几种方法 在React项目中设置代理主要用于解决开发环境下的跨域问题,以下是常见的配置方式: 通过package.json配置 在项目根目录的package.json文件中添加proxy字…

react如何设置动画

react如何设置动画

在React中设置动画的常用方法 使用CSS Transition 通过CSS的transition属性实现简单动画效果。在React组件中直接添加CSS类或内联样式。 .box { trans…

react如何设置默认需要

react如何设置默认需要

设置默认值的常见方法 在React中,可以通过多种方式为组件或表单元素设置默认值。以下是几种常见场景的解决方案: 为表单元素设置默认值 使用defaultValue属性(非受控组件)或通过状态初始化…