Spring Boot Redis缓存

Spring Boot Redis缓存

在本文中,我们将设置一个简单的Spring Boot应用程序,并将其与Redis缓存集成。虽然Redis是一个开源的内存数据结构存储,用作数据库、缓存和消息代理,但本课程将仅演示缓存集成。我们将使用Spring Initializr工具快速设置项目。

Spring Boot Redis项目设置

我们将使用Spring Initializr工具快速设置项目。我们将使用如下所示的3个依赖项:下载项目并解压缩。我们使用了H2数据库依赖项,因为我们将使用一个嵌入式数据库,该数据库在应用程序停止后将丢失所有数据。

Spring Boot Redis Cache Maven Dependencies

尽管我们已经使用工具完成了设置,如果你想手动设置,我们在这个项目中使用了Maven构建系统,以下是我们使用的依赖关系:

<parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>1.5.9.RELEASE</version>
  <relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  <java.version>1.8</java.version>
</properties>
<dependencies>
  <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-data-redis</artifactId>
  </dependency>

  <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-web</artifactId>
  </dependency>

  <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-test</artifactId>
     <scope>test</scope>
  </dependency>

  <!-- for JPA support -->
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
  </dependency>

  <!-- for embedded database support -->
  <dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>runtime</scope>
  </dependency>

</dependencies>

<build>
  <plugins>
     <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
     </plugin>
  </plugins>
</build>

确保从中央仓库使用Spring Boot的稳定版本。

定义模型

为了将对象保存到Redis数据库中,我们定义了一个具有基本字段的Person模型对象:

package com.journaldev.rediscachedemo;

import javax.persistence.*;
import java.io.Serializable;

@Entity
public class User implements Serializable {

    private static final long serialVersionUID = 7156526077883281623L;

    @Id
    @SequenceGenerator(name = "SEQ_GEN", sequenceName = "SEQ_USER", allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_GEN")
    private Long id;
    private String name;
    private long followers;

    public User() {
    }

    public User(String name, long followers) {
        this.name = name;
        this.followers = followers;
    }

    //标准的getter和setter

    @Override
    public String toString() {
        return String.format("User{id=%d, name='%s', followers=%d}", id, name, followers);
    }
}

这是一个带有getter和setter的标准POJO。

配置Redis缓存

使用Spring Boot和已经在Maven中工作的所需依赖,我们可以在application.properties文件中仅用三行配置本地Redis实例:

# Redis配置
spring.cache.type=redis
spring.redis.host=localhost
spring.redis.port=6379

还要在Spring Boot主类上使用@EnableCaching注解:

package com.journaldev.rediscachedemo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@EnableCaching
public class Application implements CommandLineRunner {

  private final Logger LOG = LoggerFactory.getLogger(getClass());
  private final UserRepository userRepository;

  @Autowired
  public Application(UserRepository userRepository) {
    this.userRepository = userRepository;
  }

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

  @Override
  public void run(String... strings) {
    //在这里填充嵌入式数据库
    LOG.info("Saving users. Current user count is {}.", userRepository.count());
    User shubham = new User("Shubham", 2000);
    User pankaj = new User("Pankaj", 29000);
    User lewis = new User("Lewis", 550);

    userRepository.save(shubham);
    userRepository.save(pankaj);
    userRepository.save(lewis);
    LOG.info("Done saving users. Data: {}.", userRepository.findAll());
  }
}

我们已经添加了一个CommandLineRunner,因为我们希望在嵌入式H2数据库中填充一些示例数据。

定义存储库

在展示Redis的工作方式之前,我们将仅定义一个与JPA相关功能的存储库:

package com.journaldev.rediscachedemo;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface UserRepository extends JpaRepository { }

目前它没有任何方法调用,因为我们不需要任何方法。

定义控制器

控制器是调用Redis缓存执行操作的地方。实际上,这是这样做的最佳地方,因为作为与之直接关联的缓存,请求甚至不必进入服务代码等待缓存结果。以下是控制器的框架:

package com.journaldev.rediscachedemo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

@RestController
public class UserController {

  private final Logger LOG = LoggerFactory.getLogger(getClass());

  private final UserRepository userRepository;

  @Autowired
  public UserController(UserRepository userRepository) {
    this.userRepository = userRepository;
  }
   ...
}

现在,要将某些内容放入缓存中,我们使用@Cacheable注解:

@Cacheable(value = "users", key = "#userId", unless = "#result.followers < 12000")
@RequestMapping(value = "/{userId}", method = RequestMethod.GET)
public User getUser(@PathVariable String userId) {
  LOG.info("Getting user with ID {}.", userId);
  return userRepository.findOne(Long.valueOf(userId));
}

在上面的映射中,getUser方法将把一个人放入名为’users’的缓存中,通过’userId’键标识该人,并且只会存储关注者超过12000的用户。这确保了缓存中填充了那些非常受欢迎且经常被查询的用户。此外,我们在API调用中故意添加了一个日志语句。让我们此刻从Postman中进行一些API调用。这些是我们进行的调用:

localhost:8090/1
localhost:8090/1
localhost:8090/2
localhost:8090/2

如果我们注意日志,它们将如下所示:

... : Getting user with ID 1.
... : Getting user with ID 1.
... : Getting user with ID 2.

注意到了吗?我们进行了四次API调用,但只有三个日志记录存在。这是因为ID为2的用户有29000个关注者,所以其数据已缓存。这意味着当对其进行API调用时,数据是从缓存中返回的,而不是为此进行数据库调用!

更新缓存

缓存值在其实际对象值更新时也应该更新。这可以使用@CachePut注释来实现:

@CachePut(value = "users", key = "#user.id")
@PutMapping("/update")
public User updatePersonByID(@RequestBody User user) {
  userRepository.save(user);
  return user;
}

通过这个,一个人再次通过他的ID来识别,并用结果进行更新。

清除缓存

如果要从实际数据库中删除一些数据,那么将它们保留在缓存中就没有意义了。我们可以使用@CacheEvict注释来清除缓存数据:

@CacheEvict(value = "users", allEntries=true)
@DeleteMapping("/{id}")
public void deleteUserByID(@PathVariable Long id) {
  LOG.info("deleting person with id {}", id);
  userRepository.delete(id);
}

在最后的映射中,我们只是驱逐了缓存条目,没有做其他事情。

运行Spring Boot Redis缓存应用程序

我们可以通过使用一个简单的命令来运行这个应用程序:

mvn spring-boot:run

Redis缓存限制

虽然Redis非常快,但在64位系统上存储任意数量的数据仍然没有限制。在32位系统上,它只能存储3GB的数据。更多的可用内存可能会导致更高的命中率,但是一旦Redis占用了过多内存,这种情况就会停止。当缓存大小达到内存限制时,旧数据将被删除以为新数据腾出空间。

总结

在这节课上,我们了解了Redis缓存提供的强大功能,以及如何在Spring Boot中进行最小而又强大的配置。请随时在下方留言。

下载Spring Boot Redis缓存项目

Source:
https://www.digitalocean.com/community/tutorials/spring-boot-redis-cache