SpringBoot中使用本地缓存

本文介绍了如何在SpringBoot中配置和使用Caffeine作为本地缓存,以提高数据读取速度并减轻数据库压力。通过示例展示了Caffeine的配置,包括弱引用和软引用的使用,并提供了缓存接口的实现。此外,还强调了在缓存接口中直接使用Caffeine而非注解方式的操作。
摘要由CSDN通过智能技术生成

        使用本地缓存的目的是加快数据读取速度,减少对数据库的访问,降低数据库压力。本地缓存是直接从本地内存中读取数据,没有网络开销。不同与Redis,Redis能够很好的作为分布式缓存组件提供多个服务间的缓存,但是Redis还是需要网络开销,增加了时耗。

        此处记录Caffeine的使用,关于Caffeine的使用有多种方式,例如在SpringBoot中单纯的使用Caffeine,还有Caffeine与spring-boot-starter-cache结合的实现方式,以及Caffeine、Guaua、spring-boot-starter-cache的实现方式等多种方式。

一、添加依赖

        <dependency>
            <groupId>com.github.ben-manes.caffeine</groupId>
            <artifactId>caffeine</artifactId>
            <version>2.9.3</version>
        </dependency>

二、书写配置类

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.TimeUnit;

@Configuration
public class CacheConfig {

    @Bean("apiCacheManager")
    public Cache<String, Object> cacheManager() {
        return Caffeine.newBuilder()
                .expireAfterAccess(60, TimeUnit.SECONDS)
                .initialCapacity(100)
                .maximumSize(1000)
                .build();
    }


}

关于Caffeine的配置说明如下所示

 

弱引用与软引用

弱引用:弱引用的对象拥有更短暂的生命周期。在垃圾回收器线程扫描它所管辖的内存区域的过程中,一旦发现了只具有弱引用的对象,不管当前内存空间足够与否,都会回收它的内存。

Caffeine.newBuilder().weakKeys().weakValues().build();

软引用 :如果一个对象只具有软引用,则内存空间足够,垃圾回收器就不会回收它;如果内存空间不足了,就会回收这些对象的内存。

Caffeine.newBuilder().softValues().build();

三、书写缓存接口

        在使用缓存的时候,需要注意的是:1、此处直接使用的是Caffeine,不是使用注解的方式;2、@CacheConfig加载的是上一步定义好的bean

import com.github.benmanes.caffeine.cache.Cache;
import com.smile.transport.mapper.TokenMapper;
import com.smile.transport.model.ApiBaseModel;
import com.smile.transport.service.ApiCacheService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.stereotype.Service;


@Service
@Slf4j
@CacheConfig(cacheNames = "apiCacheManager")
public class ApiCacheServiceImpl implements ApiCacheService {

    //数据库操作层
    @Autowired
    private TokenMapper tokenMapper;

    @Autowired
    private Cache<String, Object> caffeineCache;

    //新增缓存
    @Override
    public void addApiInfo(ApiBaseModel apiBaseModel) {
        caffeineCache.put(apiBaseModel.getId(), apiBaseModel);
    }

    //获取缓存数据
    @Override
    public ApiBaseModel getAccount() {
        //先从缓存中查询数据
        ApiBaseModel apiBaseModel = (ApiBaseModel) caffeineCache.asMap().get("api_account");
        if (apiBaseModel != null) {
            return apiBaseModel;
        }
        //如果缓存中不存在,则从库中查询
        apiBaseModel = this.tokenMapper.selectAccount();
        //如果账号信息不为空,则加入缓存
        if (apiBaseModel != null) {
            caffeineCache.put(apiBaseModel.getId(), apiBaseModel);
        }
        return apiBaseModel;
    }

    //更新缓存
    @Override
    public ApiBaseModel updateAccount(ApiBaseModel apiBaseModel) {
        log.info("update");
        //此处没有写具体的更新流程,可以根据自己实际需要编写
        return apiBaseModel;
    }

    //删除缓存
    @Override
    public void deleteAccount(String id) {
        log.info("delete");
        caffeineCache.asMap().remove(id);
    }
}

四、使用

Controller层调用service层接口,实现具体方法即可

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Spring Boot提供了对本地缓存的支持,可以使用不同的缓存实现来提高应用程序的性能和响应速度。以下是使用Spring Boot进行本地缓存的步骤和示例代码: 1. 在pom.xml文件添加Spring Boot缓存依赖项[^1]: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> ``` 2. 在应用程序的配置文件(例如application.yml)配置缓存: ```yaml spring: cache: type: <cache-provider> ``` 其,`<cache-provider>`可以是以下之一: - `simple`:使用SimpleCacheManager作为缓存提供程序,适用于开发和测试环境。 - `caffeine`:使用Caffeine作为缓存提供程序,适用于高性能和低延迟的应用程序。 - `ehcache`:使用Ehcache作为缓存提供程序,适用于分布式和高可用性的应用程序。 - `redis`:使用Redis作为缓存提供程序,适用于分布式和高可用性的应用程序。 3. 在需要缓存的方法上添加`@Cacheable`注解,指定缓存的名称和缓存的键。例如: ```java @Service public class MyService { @Cacheable("myCache") public String getData(String key) { // 从数据库或其他数据源获取数据 return data; } } ``` 4. 运行应用程序并调用带有缓存注解的方法,第一次调用会执行方法体内的逻辑并将结果缓存起来,后续调用相同的方法会直接从缓存获取结果。 这样,你就可以使用Spring Boot进行本地缓存了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

one_smail

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值