java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Spring Cache数据库访问

Spring Cache优化数据库访问的项目实践

作者:冷风扇666

本文主要介绍了Spring Cache优化数据库访问的项目实践,将创建一个简单的图书管理应用作为示例,并演示如何通过缓存减少对数据库的频繁查询,感兴趣的可以了解一下

在这篇博客中,我们将学习如何使用Spring Cache来优化数据库访问,提高系统性能。我们将创建一个简单的图书管理应用作为示例,并演示如何通过缓存减少对数据库的频繁查询。

1. 项目结构

首先,我们看一下项目的基本结构:

lfsun-study-cacheable
|-- src
|   |-- main
|       |-- java
|           |-- com.lfsun.cacheable
|               |-- controller
|                   |-- BookController.java
|               |-- dao
|                   |-- BookRepository.java
|               |-- entity
|                   |-- Book.java
|               |-- service
|                   |-- BookService.java
|                   |-- impl
|                       |-- BookServiceImpl.java
|               |-- LfsunStudyCacheableApplication.java
|       |-- resources
|           |-- application.properties
|-- pom.xml

2. 项目依赖

我们使用了Spring Boot和Spring Data JPA来简化项目配置。以下是主要的Maven依赖:

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

<!-- Spring Boot Starter Test -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

<!-- Spring Boot Starter Web -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<!-- Spring Boot Starter Data JPA -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<!-- Lombok for easy POJOs -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>

<!-- MySQL Connector -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.28</version>
</dependency>

3. 数据库配置

配置MySQL数据库连接信息和Hibernate方言:

spring.datasource.url=jdbc:mysql://localhost:3306/lfsun_study
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect

4. 实体类

定义一个简单的实体类Book,用于表示图书信息:

@Entity
@Data
@Table(name = "cacheable_book")
public class Book implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String title;
    private String author;
}

5. 数据访问层

创建一个JPA Repository接口 BookRepository,用于数据库交互:

public interface BookRepository extends JpaRepository<Book, Long> {
    Book findByTitle(String title);
    void deleteByTitle(String title);
}

6. 服务层

实现一个 BookService 接口,并创建具体的服务实现 BookServiceImpl。在服务实现中,使用Spring Cache注解来优化数据库访问:

@Service
@AllArgsConstructor
public class BookServiceImpl implements BookService {

    private final BookRepository bookRepository;

    @Override
    @Cacheable(value = "books", key = "#title")
    public Book getByTitle(String title) {
        System.out.println("Getting book from database for title: " + title);
        return bookRepository.findByTitle(title);
    }

    @Override
    @CachePut(value = "books", key = "#result.title")
    public Book save(Book book) {
        System.out.println("Saving book to database: " + book.getTitle());
        return bookRepository.save(book);
    }

    @Override
    @Transactional
    @CacheEvict(value = "books", key = "#title")
    public void deleteByTitle(String title) {
        System.out.println("Deleting book from database for title: " + title);
        bookRepository.deleteByTitle(title);
    }
}

7. 控制器层

创建REST控制器 BookController 处理图书的获取、保存和删除操作:

@RestController
@RequestMapping("/books")
@AllArgsConstructor
public class BookController {

    private final BookService bookService;

    @GetMapping("/{title}")
    public Book getBookByTitle(@PathVariable String title) {
        return bookService.getByTitle(title);
    }

    @PostMapping
    public Book saveBook(@RequestBody Book book) {
        return bookService.save(book);
    }

    @PostMapping("/delete/{title}")
    public ResponseEntity<String> deleteBookByTitle(@PathVariable String title) {
        bookService.deleteByTitle(title);
        return new ResponseEntity<>("Book deleted successfully", HttpStatus.OK);
    }
}

8. 主应用程序类

在主应用程序类 LfsunStudyCacheableApplication 上启用Spring缓存:

@SpringBootApplication
@EnableCaching
public class LfsunStudyCacheableApplication {

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

测试

1. 新增图书

POST http://localhost:8888/books
Content-Type: application/json

{
  "title": "JavaStudy777",
  "author": "冷风扇",
  "isbn": "1234567890"
}

2. 获取图书信息

# GET请求
GET http://localhost:8888/books/JavaStudy777

3. 删除图书

# POST请求
POST http://localhost:8888/books/delete/JavaStudy777

image.png

到此这篇关于Spring Cache优化数据库访问的项目实践的文章就介绍到这了,更多相关Spring Cache数据库访问内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家! 

您可能感兴趣的文章:
阅读全文