Springboot如何集成spring cache缓存

发布时间:2022-06-02 10:57:50 作者:zzz
来源:亿速云 阅读:200

Spring Boot如何集成Spring Cache缓存

在现代的Web应用程序中,缓存是提高系统性能的重要手段之一。Spring框架提供了强大的缓存抽象,使得开发者可以轻松地在应用程序中集成缓存功能。Spring Cache是Spring框架中的一个模块,它提供了一种声明式的缓存机制,允许开发者通过简单的注解来管理缓存。

本文将介绍如何在Spring Boot项目中集成Spring Cache缓存,并通过示例代码展示如何使用Spring Cache来提高应用程序的性能。

1. 添加依赖

首先,我们需要在Spring Boot项目中添加Spring Cache的依赖。Spring Cache通常与具体的缓存实现(如EhCache、Redis等)一起使用。这里我们以EhCache为例,首先在pom.xml中添加相关依赖:

<dependencies>
    <!-- Spring Boot Starter Cache -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-cache</artifactId>
    </dependency>

    <!-- EhCache依赖 -->
    <dependency>
        <groupId>net.sf.ehcache</groupId>
        <artifactId>ehcache</artifactId>
    </dependency>
</dependencies>

2. 配置缓存

接下来,我们需要在Spring Boot项目中配置缓存。Spring Boot支持多种缓存实现,我们可以通过配置文件来指定使用哪种缓存实现。

application.propertiesapplication.yml中,添加以下配置:

# 启用缓存
spring.cache.type=ehcache

# EhCache配置文件路径
spring.cache.ehcache.config=classpath:ehcache.xml

然后,我们需要创建一个ehcache.xml文件来配置EhCache的缓存策略。在src/main/resources目录下创建ehcache.xml文件,内容如下:

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">

    <cache name="books"
           maxEntriesLocalHeap="100"
           timeToLiveSeconds="600">
    </cache>
</ehcache>

在这个配置文件中,我们定义了一个名为books的缓存,设置了最大堆内条目数为100,缓存项的存活时间为600秒。

3. 启用缓存

在Spring Boot项目中,我们需要在启动类上添加@EnableCaching注解来启用缓存功能:

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

@SpringBootApplication
@EnableCaching
public class CacheApplication {
    public static void main(String[] args) {
        SpringApplication.run(CacheApplication.class, args);
    }
}

4. 使用缓存

现在,我们可以在Service层中使用Spring Cache提供的注解来管理缓存。常用的注解包括@Cacheable@CachePut@CacheEvict

4.1 @Cacheable

@Cacheable注解用于标记方法的返回值应该被缓存。当方法被调用时,Spring会首先检查缓存中是否存在对应的结果,如果存在则直接返回缓存中的结果,否则执行方法并将结果缓存。

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

@Service
public class BookService {

    @Cacheable("books")
    public Book getBookById(Long id) {
        // 模拟从数据库获取数据
        simulateSlowService();
        return new Book(id, "Book " + id);
    }

    private void simulateSlowService() {
        try {
            Thread.sleep(3000L);
        } catch (InterruptedException e) {
            throw new IllegalStateException(e);
        }
    }
}

在这个例子中,getBookById方法的返回值会被缓存到名为books的缓存中。如果再次调用该方法并传入相同的id,Spring会直接从缓存中返回结果,而不会再次执行方法。

4.2 @CachePut

@CachePut注解用于更新缓存。与@Cacheable不同,@CachePut总是会执行方法,并将方法的返回值更新到缓存中。

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

@Service
public class BookService {

    @CachePut(value = "books", key = "#book.id")
    public Book updateBook(Book book) {
        // 模拟更新数据库
        return book;
    }
}

在这个例子中,updateBook方法会更新缓存中对应的Book对象。

4.3 @CacheEvict

@CacheEvict注解用于从缓存中移除数据。通常用于删除操作。

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

@Service
public class BookService {

    @CacheEvict(value = "books", key = "#id")
    public void deleteBookById(Long id) {
        // 模拟从数据库删除数据
    }
}

在这个例子中,deleteBookById方法会从缓存中移除对应的Book对象。

5. 测试缓存

为了验证缓存是否生效,我们可以编写一个简单的测试用例:

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class BookServiceTest {

    @Autowired
    private BookService bookService;

    @Test
    public void testCache() {
        // 第一次调用,会执行方法并将结果缓存
        Book book1 = bookService.getBookById(1L);
        System.out.println("Book 1: " + book1);

        // 第二次调用,直接从缓存中获取结果
        Book book2 = bookService.getBookById(1L);
        System.out.println("Book 2: " + book2);

        // 更新缓存
        Book updatedBook = new Book(1L, "Updated Book 1");
        bookService.updateBook(updatedBook);

        // 第三次调用,获取更新后的缓存结果
        Book book3 = bookService.getBookById(1L);
        System.out.println("Book 3: " + book3);

        // 删除缓存
        bookService.deleteBookById(1L);

        // 第四次调用,缓存已被删除,会再次执行方法
        Book book4 = bookService.getBookById(1L);
        System.out.println("Book 4: " + book4);
    }
}

运行这个测试用例,可以看到缓存的效果:第一次调用getBookById方法时会执行方法并将结果缓存,第二次调用时直接从缓存中获取结果,更新缓存后再次调用会获取更新后的结果,删除缓存后再次调用会重新执行方法。

6. 总结

通过Spring Cache,我们可以非常方便地在Spring Boot项目中集成缓存功能。Spring Cache提供了多种注解来管理缓存,开发者可以根据业务需求选择合适的注解来优化系统性能。本文介绍了如何在Spring Boot项目中集成Spring Cache,并通过示例代码展示了如何使用@Cacheable@CachePut@CacheEvict注解来管理缓存。希望本文能帮助你更好地理解和使用Spring Cache。

推荐阅读:
  1. Spring- Cache缓存
  2. SpringBoot如何集成Spring Security

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

springboot spring cache

上一篇:C语言的qsort()函数如何使用

下一篇:C++运算符重载方法怎么使用

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》