springboot 集成 @Cacheable简单示例

发布时间:2024年01月12日

在Spring Boot中,你可以使用@Cacheable注解来实现对方法结果的缓存。下面是一个示例代码:

首先,在pom.xml文件中添加以下依赖,以引入Spring Boot对缓存的支持:

<dependencies>
    <!-- 其他依赖... -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-cache</artifactId>
    </dependency>
</dependencies>

接下来,通过在Spring Boot应用主类上添加@EnableCaching注解启用缓存功能:

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

@SpringBootApplication
@EnableCaching
public class Application {

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

在需要进行缓存的方法上添加@Cacheable注解,并指定缓存名称:

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

@Service
public class MyService {

    @Cacheable("myCache")
    public String getCachedData(String key) {
        // 从数据库或其他数据源获取数据的逻辑
        return fetchDataFromDatabase(key);
    }

    private String fetchDataFromDatabase(String key) {
        // 模拟从数据库获取数据的逻辑
        // ...
    }
}

在上述示例中,getCachedData()方法使用了@Cacheable("myCache")注解,其中"myCache"是指定的缓存名称。当该方法被调用时,如果缓存中存在对应的结果,则直接从缓存中返回;如果缓存中不存在,则执行方法逻辑,并将结果放入缓存中。

你还可以指定一个或多个缓存键,以更精确地控制缓存。例如:

@Cacheable(value = "myCache", key = "#userId")
public User getUserById(String userId) {
    // 从数据库获取用户数据的逻辑
}

在上述示例中,getUserById()方法根据userId作为缓存键来进行缓存操作。

需要注意的是,为了使@Cacheable注解生效,你需要配置相应的缓存管理器。在Spring Boot中,你可以通过在application.properties(或application.yml)文件中添加以下配置来使用默认的缓存管理器:

spring.cache.type=redis

上述配置示例选择了Redis作为缓存后端,你也可以选择其他支持的缓存后端,如Ehcache、Caffeine等。

这只是一个简单的示例,你可以根据具体需求和业务场景进行更复杂的缓存配置。

文章来源:https://blog.csdn.net/lichongxyz/article/details/135557832
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。