缓存之SpringCache整合redis

Spring Cache 是 Spring 框架提供的一种缓存抽象,在应用中可以方便地使用它来进行方法级别的缓存。结合 Redis 作为缓存存储后端,可以实现高性能的缓存服务。下面是一个简单的示例,演示了如何在 Spring Boot 项目中整合 Spring Cache 和 Redis。

首先,确保你的 Spring Boot 项目中引入了相关的依赖。你需要引入 Spring Boot Starter Cache 和 Spring Boot Starter Data Redis。

xml 复制代码
<!-- Maven 依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

接下来,在 Spring Boot 的配置文件中配置 Redis 连接信息:

properties 复制代码
# Redis 配置
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=
spring.redis.database=0

然后,在你的 Spring Boot 应用中,定义一个 Service 类,并在其中使用 Spring Cache 注解来实现方法级别的缓存。

java 复制代码
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class MyService {

    @Cacheable(value = "myCache", key = "#id")
    public String getDataById(int id) {
        // 模拟从数据库或其他数据源中获取数据的操作
        System.out.println("Fetching data from backend for id: " + id);
        return "Data for id " + id;
    }
}

在上面的代码中,@Cacheable 注解用于标记 getDataById 方法,指定了缓存名称为 "myCache",并指定了缓存的 key 为方法的参数 id。当方法被调用时,如果缓存中已经存在对应 key 的数据,则直接返回缓存中的数据;如果缓存中不存在对应 key 的数据,则执行方法体中的代码,并将结果存入缓存。

最后,在你的应用程序中,可以直接调用 MyService 中的方法来获取数据,Spring Cache 会自动处理缓存逻辑。

java 复制代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@EnableCaching
public class Application {

    @Autowired
    private MyService myService;

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    public void exampleUsage() {
        // 调用 MyService 中的方法,数据会被缓存
        String data = myService.getDataById(1);
        System.out.println("Data: " + data);

        // 再次调用相同的方法,数据将直接从缓存中获取,不会执行方法体中的代码
        data = myService.getDataById(1);
        System.out.println("Data: " + data);
    }
}

通过以上配置,Spring Boot 就会自动使用 Redis 作为缓存存储后端,并且通过 Spring Cache 抽象来管理缓存。

相关推荐
magic 24524 分钟前
MyBatis的缓存、逆向工程、使用PageHelper、使用PageHelper
java·spring·maven·mybatis
XiaoLeisj1 小时前
【图书管理系统】深入解析基于 MyBatis 数据持久化操作:全栈开发图书管理系统:查询图书属性接口(注解实现)、修改图书属性接口(XML 实现)
xml·java·数据库·spring boot·sql·java-ee·mybatis
dr李四维2 小时前
解决缓存穿透的布隆过滤器与布谷鸟过滤器:谁更适合你的应用场景?
redis·算法·缓存·哈希算法·缓存穿透·布隆过滤器·布谷鸟过滤器
axinawang2 小时前
spring boot 整合redis
spring boot·redis·bootstrap
烟沙九洲3 小时前
MyBatis-Plus 的 FieldStrategy 属性
java·mybatis
Pitayafruit4 小时前
【📕分布式锁通关指南 09】源码剖析redisson之公平锁的实现
redis·分布式·后端
Pitayafruit4 小时前
【📕分布式锁通关指南 10】源码剖析redisson之MultiLock的实现
redis·分布式·后端
八股文领域大手子5 小时前
从接口400ms到20ms,记录一次JVM、MySQL、Redis的混合双打
jvm·数据库·redis·mysql·jar
qq_260241236 小时前
怎么检查网站CDN缓存是否生效
运维·前端·缓存
堕落年代6 小时前
SpringBoot使用Redisson时候进行Redis事务回滚
spring boot·redis·后端