返回介绍

4.3 Caching 缓存

发布于 2025-04-21 20:58:44 字数 2516 浏览 0 评论 0 收藏

缓存在现代应用中无处不在,它为服务的高可用提供了很大的帮助。Spring 框架提供了对缓存的支持。Spring Boot 通过 @EnableCaching 注解开启全局服务缓存功能。对于某个服务类方法的返回值缓存,可以采用 @Cacheable 注解实现。spring-boot-starter-cache 模块集成了现有的一些缓存框架,如 EhCache 和 Couchbase 等。

4.3.1 访问 EhCache

EhCache 是一个常用的缓存框架,可以通过配置文件 ehcache.xml 生成 EhCache-CacheManager。Spring Boot 的配置文件内容如下:

spring:
  cache:
    ehcache:
      config: classpath:ehcache.xml
    type: ehcache

配置文件 ehcache.xml 的内容如下:

<ehcache>
    <diskStore path="java.io.tmpdir"/>
    <defaultCache
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="6000"
            timeToLiveSeconds="6000"
            overflowToDisk="false"
            diskPersistent="false"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU"
    />
    <cache name="testCache"
           maxElementsInMemory="10000"
           overflowToDisk="false"
           eternal="false"
           timeToLiveSeconds="72000"
           timeToIdleSeconds="72000"
           diskPersistent="false"
           diskExpiryThreadIntervalSeconds="600"
           memoryStoreEvictionPolicy="LRU"
    />
</ehcache>

下面是一个具体的示例:

@Service
public class UserService {
    @Autowired
    private UserDao userDao;
    //缓存返回数据
    @Cacheable(value="user")
    public User findOne(Integer userId){
        return userDao.findOne(userId);
    }
    //清除缓存
    @CacheEvict(value="user")
    public String delete(Integer userId){
        return userDao.delete(userId);
    }
    //缓存结果
    @CachePut(value="userAll")
    public List<User> findAll(){
        return userDao.findAll();
    }
}

以上代码中 3 个注解的作用如下:

  • @Cacheable:缓存结果,只执行一次方法,下一次不会调用方法,直接返回缓存结果。
  • @CachePut:可以根据参数进行缓存,与 @Cacheable 不同的是,不判断缓存中是否有之前执行的结果,每次都会调用方法。
  • @ CacheEvict:从缓存中删除响应的数据。

4.3.2 访问 Couchbase

Couchbase 是一个面向文档的分布式和多模型开源数据库,主要用于交互式应用程序。Spring Boot 为 Couchbase 提供了自动配置,Spring Data 为 Couchbase 提供了抽象封装。Spring Boot 提供了 Couchbase 的 Starter,即 spring-boot-starter-data-couchbase。

由于 Couchbase 是存放在内存中,所以读取速度非常快。Couchbase 还自带集群方案,支持多副本和持久化,可以满足系统的高可用方案。

Spring Boot 集成 Couchbase 的配置示例如下:

spring:
  couchbase:
    bootstrap-hosts: localhost
    username: admin
    password: 123456
    bucket:
      name: test
      password: 123456
    env:
      timeouts:
        connect: 30000
        query: 2000

Spring Boot 通过 CouchbaseTemplate 模板类操作数据库。

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。