SpringBoot 整合 Redis 缓存

Spring Boot提供了对Spring Cache抽象的支持,可以很容易地与Redis集成。

添加Redis依赖

在pom.xml文件中添加Spring Boot Starter Redis依赖:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
</dependencies>

配置Redis连接信息

在application.properties或application.yml中配置Redis连接信息:

spring.redis.host=your-redis-host
spring.redis.port=your-redis-port
spring.redis.password=your-redis-password

启用缓存支持

在Spring Boot应用的主类(通常是带有@SpringBootApplication注解的类)上添加@EnableCaching注解,启用缓存支持:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@EnableCaching
public class YourApplication {
   

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

使用缓存注解

在你的Service类或方法上使用Spring Cache注解,比如@Cacheable、@CachePut、@CacheEvict等。以下是一个简单的示例:

import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class MyService {
   

    @Cacheable(value = "myCache", key = "#id")
    public String getCachedData(Long id) {
   
        // Your business logic to fetch data from a data source
        return "Data for id " + id;
    }
}

在上述例子中,@Cacheable注解表示在调用getCachedData方法时,会先检查缓存中是否存在对应的数据,如果存在则直接返回缓存的数据,否则执行方法体逻辑,并将结果缓存起来。

清理缓存

使用@CacheEvict注解可以在数据变更时清理缓存,例如:

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;

@Service
public class MyService {
   

    @CacheEvict(value = "myCache", key = "#id")
    public void updateData(Long id) {
   
        // Your business logic to update data
    }
}

上述代码中,updateData方法在执行后会清理缓存中指定id的数据。
以上是一个简单的Spring Boot整合Redis缓存的示例,你可以根据实际需求进一步扩展和配置。

相关推荐

  1. SpringBoot 整合 Redis 缓存

    2024-01-16 14:24:02       70 阅读
  2. SpringBoot整合Redis实现缓存信息监控

    2024-01-16 14:24:02       53 阅读
  3. 缓存之SpringCache整合redis

    2024-01-16 14:24:02       38 阅读
  4. SpringBoot整合Redis

    2024-01-16 14:24:02       59 阅读
  5. SpringBoot3 整合Redis

    2024-01-16 14:24:02       47 阅读
  6. SpringBoot 整合redis

    2024-01-16 14:24:02       59 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-16 14:24:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-16 14:24:02       100 阅读
  3. 在Django里面运行非项目文件

    2024-01-16 14:24:02       82 阅读
  4. Python语言-面向对象

    2024-01-16 14:24:02       91 阅读

热门阅读

  1. LeetCode每周五题_2024/01/15~01/19

    2024-01-16 14:24:02       62 阅读
  2. RKE安装k8s及部署高可用rancher之证书通过cert-manager

    2024-01-16 14:24:02       84 阅读
  3. Vuex中的dispatch用来触发(派发)action

    2024-01-16 14:24:02       59 阅读
  4. 2、python函数和获取帮助

    2024-01-16 14:24:02       57 阅读
  5. python之except关键字

    2024-01-16 14:24:02       57 阅读