Spring Cache優(yōu)化數(shù)據(jù)庫訪問的項目實踐
在這篇博客中,我們將學習如何使用Spring Cache來優(yōu)化數(shù)據(jù)庫訪問,提高系統(tǒng)性能。我們將創(chuàng)建一個簡單的圖書管理應(yīng)用作為示例,并演示如何通過緩存減少對數(shù)據(jù)庫的頻繁查詢。
1. 項目結(jié)構(gòu)
首先,我們看一下項目的基本結(jié)構(gòu):
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. 數(shù)據(jù)庫配置
配置MySQL數(shù)據(jù)庫連接信息和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. 數(shù)據(jù)訪問層
創(chuàng)建一個JPA Repository接口 BookRepository,用于數(shù)據(jù)庫交互:
public interface BookRepository extends JpaRepository<Book, Long> {
Book findByTitle(String title);
void deleteByTitle(String title);
}
6. 服務(wù)層
實現(xiàn)一個 BookService 接口,并創(chuàng)建具體的服務(wù)實現(xiàn) BookServiceImpl。在服務(wù)實現(xiàn)中,使用Spring Cache注解來優(yōu)化數(shù)據(jù)庫訪問:
@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. 控制器層
創(chuàng)建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. 主應(yīng)用程序類
在主應(yīng)用程序類 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

到此這篇關(guān)于Spring Cache優(yōu)化數(shù)據(jù)庫訪問的項目實踐的文章就介紹到這了,更多相關(guān)Spring Cache數(shù)據(jù)庫訪問內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Kotlin基礎(chǔ)教程之伴生對象,getter,setter,內(nèi)部,局部,匿名類,可變參數(shù)
這篇文章主要介紹了Kotlin基礎(chǔ)教程之伴生對象,getter,setter,內(nèi)部,局部,匿名類,可變參數(shù)的相關(guān)資料,需要的朋友可以參考下2017-05-05
解決rocketmq-client查詢手動發(fā)送消息異常問題
這篇文章主要介紹了解決rocketmq-client查詢手動發(fā)送消息異常問題,具有很好的參考價值,希望對大家大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-08-08
springboot?@PostConstruct無效的解決
這篇文章主要介紹了springboot?@PostConstruct無效的解決,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-11-11
Mybatis Plus條件構(gòu)造器ConditionConstructor用法實例解析
這篇文章主要介紹了Mybatis Plus條件構(gòu)造器ConditionConstructor用法實例解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-08-08
Java擴展庫RxJava的基本結(jié)構(gòu)與適用場景小結(jié)
RxJava(GitHub: https://github.com/ReactiveX/RxJava)能夠幫助Java進行異步與事務(wù)驅(qū)動的程序編寫,這里我們來作一個Java擴展庫RxJava的基本結(jié)構(gòu)與適用場景小結(jié),剛接觸RxJava的同學不妨看一下^^2016-06-06
使用lombok注解導致mybatis-plus TypeHandler失效的解決
這篇文章主要介紹了使用lombok注解導致mybatis-plus TypeHandler失效的解決,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-07-07

