Spring Boot 数据缓存与性能优化
Spring Boot 数据缓存技术通过 EhCache 和 Caffeine 实现,利用@Cacheable、@CachePut、@CacheEvict 注解管理缓存生命周期。集成步骤包括添加依赖、配置文件及启用缓存注解。实际应用中可缓存产品、用户等信息,减少数据库访问,提升系统性能。

Spring Boot 数据缓存技术通过 EhCache 和 Caffeine 实现,利用@Cacheable、@CachePut、@CacheEvict 注解管理缓存生命周期。集成步骤包括添加依赖、配置文件及启用缓存注解。实际应用中可缓存产品、用户等信息,减少数据库访问,提升系统性能。

学习目标:掌握 Spring Boot 数据缓存与性能优化的核心概念与使用方法,包括数据缓存的定义与特点、Spring Boot 与数据缓存的集成、配置、基本方法及实际应用场景。
重点:
数据缓存是 Java 开发中的重要组件。
定义:数据缓存是一种存储机制,用于将常用数据存储在高速存储设备中,以便快速访问。
作用:
常见的数据缓存:
结论:数据缓存是一种存储机制,作用是提高应用程序的性能、减少数据库的访问次数、提高用户体验。
特点:
结论:数据缓存的特点包括高速访问、数据一致性、可扩展性、易用性。
步骤:
示例:
pom.xml 文件中的依赖:
<dependencies>
<!-- Web 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Data JPA 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- H2 数据库依赖 -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<!-- EhCache 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
<!-- 测试依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
application.properties 文件中的 EhCache 配置:
# 服务器端口
server.port=8080
# 数据库连接信息
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
# JPA 配置
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
# H2 数据库控制台
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
# EhCache 配置
spring.cache.type=ehcache
spring.cache.ehcache.config=classpath:ehcache.xml
ehcache.xml 配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
<defaultCache maxEntriesLocalHeap="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="false"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"></defaultCache>
<cache name="productCache"
maxEntriesLocalHeap="1000"
eternal="false"
timeToIdleSeconds="60"
timeToLiveSeconds="60"
overflowToDisk="false"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"></cache>
</ehcache>
实体类:
import javax.persistence.*;
@Entity
@Table(name = "product")
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String productId;
private String productName;
private double price;
private int sales;
public Product() {}
public Product(String productId, String productName, double price, int sales) {
this.productId = productId;
this.productName = productName;
this.price = price;
this.sales = sales;
}
// Getter 和 Setter 方法
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getProductId() { return productId; }
public void setProductId(String productId) { this.productId = productId; }
public String getProductName() { return productName; }
public void setProductName(String productName) { this.productName = productName; }
public double getPrice() { return price; }
public void setPrice(double price) { this.price = price; }
public int getSales() { return sales; }
public void setSales(int sales) { this.sales = sales; }
@Override
public String toString() {
return "Product{" +
"id=" + id +
", productId='" + productId + '\'' +
", productName='" + productName + '\'' +
", price=" + price +
", sales=" + sales +
'}';
}
}
Repository 接口:
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {}
Service 类:
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.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
public class ProductService {
@Autowired
private ProductRepository productRepository;
@Transactional
@CachePut(value = "productCache", key = "#product.id")
public Product addProduct(Product product) {
return productRepository.save(product);
}
@Transactional
@CachePut(value = "productCache", key = "#product.id")
public Product updateProduct(Product product) {
return productRepository.save(product);
}
@Transactional
@CacheEvict(value = "productCache", key = "#id")
public void deleteProduct(Long id) {
productRepository.deleteById(id);
}
@Transactional(readOnly = true)
@Cacheable(value = "productCache", key = "#id")
public Product getProductById(Long id) {
System.out.println("从数据库查询产品:" + id);
return productRepository.findById(id).orElse(null);
}
@Transactional(readOnly = true)
public List<Product> getAllProducts() {
return productRepository.findAll();
}
}
控制器类:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/products")
public class ProductController {
@Autowired
private ProductService productService;
@GetMapping("/")
public List<Product> getAllProducts() {
return productService.getAllProducts();
}
@PostMapping("/")
public Product addProduct(@RequestBody Product product) {
return productService.addProduct(product);
}
@PutMapping("/{id}")
public Product updateProduct(@PathVariable Long id, @RequestBody Product product) {
product.setId(id);
return productService.updateProduct(product);
}
@DeleteMapping("/{id}")
public void deleteProduct(@PathVariable Long id) {
productService.deleteProduct(id);
}
@GetMapping("/{id}")
public Product getProductById(@PathVariable Long id) {
return productService.getProductById(id);
}
}
应用启动类:
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 ProductApplication {
public static void main(String[] args) {
SpringApplication.run(ProductApplication.class, args);
}
@Autowired
private ProductService productService;
public void run(String... args) {
// 初始化数据
productService.addProduct(new Product("P001", "手机", 1000.0, 100));
productService.addProduct(new Product("P002", "电脑", 5000.0, 50));
productService.addProduct(new Product("P003", "电视", 3000.0, 80));
productService.addProduct(new Product("P004", "手表", 500.0, 200));
productService.addProduct(new Product("P005", "耳机", 300.0, 150));
}
}
结论:集成 EhCache 的步骤包括创建 Spring Boot 项目、添加所需的依赖、配置 EhCache、创建数据访问层、创建业务层、创建控制器类、测试应用。
步骤:
示例:
pom.xml 文件中的依赖:
<dependencies>
<!-- Web 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Data JPA 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- H2 数据库依赖 -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Caffeine 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
</dependency>
<!-- 测试依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
application.properties 文件中的 Caffeine 缓存配置:
# 服务器端口
server.port=8080
# 数据库连接信息
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
# JPA 配置
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
# H2 数据库控制台
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
# Caffeine 缓存配置
spring.cache.type=caffeine
spring.cache.caffeine.spec=maximumSize=1000,expireAfterWrite=60s
结论:配置 Caffeine 缓存是指使用 Spring Boot 与 Caffeine 缓存集成的方法,步骤包括创建 Spring Boot 项目、添加所需的依赖、配置 Caffeine 缓存、创建数据访问层、创建业务层、创建控制器类、测试应用。
Spring Boot 与数据缓存的基本方法包括使用@Cacheable、@CachePut、@CacheEvict 注解。
作用:
示例:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
public class ProductService {
@Autowired
private ProductRepository productRepository;
@Transactional(readOnly = true)
@Cacheable(value = "productCache", key = "#id")
public Product getProductById(Long id) {
System.out.println("从数据库查询产品:" + id);
return productRepository.findById(id).orElse(null);
}
@Transactional(readOnly = true)
public List<Product> getAllProducts() {
return productRepository.findAll();
}
}
结论:使用@Cacheable 注解是指 Spring Boot 与数据缓存集成的基本方法之一,作用是实现数据缓存、提高应用程序的性能。
作用:
示例:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class ProductService {
@Autowired
private ProductRepository productRepository;
@Transactional
@CachePut(value = "productCache", key = "#product.id")
public Product addProduct(Product product) {
return productRepository.save(product);
}
@Transactional
@CachePut(value = "productCache", key = "#product.id")
public Product updateProduct(Product product) {
return productRepository.save(product);
}
@Transactional(readOnly = true)
@Cacheable(value = "productCache", key = "#id")
public Product getProductById(Long id) {
System.out.println("从数据库查询产品:" + id);
return productRepository.findById(id).orElse(null);
}
@Transactional(readOnly = true)
public List<Product> getAllProducts() {
return productRepository.findAll();
}
}
结论:使用@CachePut 注解是指 Spring Boot 与数据缓存集成的基本方法之一,作用是实现数据缓存、提高应用程序的性能。
作用:
示例:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class ProductService {
@Autowired
private ProductRepository productRepository;
@Transactional
@CachePut(value = "productCache", key = "#product.id")
public Product addProduct(Product product) {
return productRepository.save(product);
}
@Transactional
@CachePut(value = "productCache", key = "#product.id")
public Product updateProduct(Product product) {
return productRepository.save(product);
}
@Transactional
@CacheEvict(value = "productCache", key = "#id")
public void deleteProduct(Long id) {
productRepository.deleteById(id);
}
@Transactional(readOnly = true)
@Cacheable(value = "productCache", key = "#id")
public Product getProductById(Long id) {
System.out.println("从数据库查询产品:" + id);
return productRepository.findById(id).orElse(null);
}
@Transactional(readOnly = true)
public List<Product> getAllProducts() {
return productRepository.findAll();
}
}
结论:使用@CacheEvict 注解是指 Spring Boot 与数据缓存集成的基本方法之一,作用是实现数据缓存、提高应用程序的性能。
在实际开发中,Spring Boot 数据缓存与性能优化的应用场景非常广泛,如:
输出结果:
控制台输出:
从数据库查询产品:1
结论:在实际开发中,Spring Boot 数据缓存与性能优化的应用场景非常广泛,需要根据实际问题选择合适的缓存策略。
本章我们学习了 Spring Boot 数据缓存与性能优化,包括数据缓存的定义与特点、Spring Boot 与数据缓存的集成、配置、基本方法及实际应用场景。其中,数据缓存的定义与特点、Spring Boot 与数据缓存的集成、配置、基本方法及应用场景是本章的重点内容。从下一章开始,我们将学习 Spring Boot 的其他组件、微服务等内容。

微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
查找任何按下的键的javascript键代码、代码、位置和修饰符。 在线工具,Keycode 信息在线工具,online
JavaScript 字符串转义/反转义;Java 风格 \uXXXX(Native2Ascii)编码与解码。 在线工具,Escape 与 Native 编解码在线工具,online
使用 Prettier 在浏览器内格式化 JavaScript 或 HTML 片段。 在线工具,JavaScript / HTML 格式化在线工具,online
Terser 压缩、变量名混淆,或 javascript-obfuscator 高强度混淆(体积会增大)。 在线工具,JavaScript 压缩与混淆在线工具,online
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online