0
点赞
收藏
分享

微信扫一扫

SpringBoot与Spring Framework提供的缓存抽象

脱下愤怒的小裤衩 2024-06-05 阅读 4

目录

缓存

项目总结

新建一个SpringBoot项目

pom.xml

application.properties

CacheConfig

Book

BookRepository接口

BookService服务类

BookController控制器

SpringbootCacheApplication启动类

启动项目,使用Postman测试


参考博文:

缓存

项目总结

新建一个SpringBoot项目

项目结构:

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.3.12.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.study</groupId>
	<artifactId>springboot_cache</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>springboot_cache</name>
	<description>Demo project for Spring Boot</description>
	<properties>
		<java.version>8</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-cache</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>com.mysql</groupId>
			<artifactId>mysql-connector-j</artifactId>
			<version>8.0.32</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<configuration>
					<excludes>
						<exclude>
							<groupId>org.projectlombok</groupId>
							<artifactId>lombok</artifactId>
						</exclude>
					</excludes>
				</configuration>
			</plugin>
		</plugins>
	</build>

</project>

application.properties

# test为数据库名
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=true
spring.datasource.username=root
spring.datasource.password=admin
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

# Hibernate配置属性,设置自动根据实体类创建,更新和验证数据库表结构
spring.jpa.properties.hibernate.hbm2ddl.auto=update
# Hibernate 将会使用 MySQL 5 InnoDB 存储引擎的方言来生成针对 MySQL 数据库的 SQL 查询和语句。
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
# 将运行期生成的SQL语句输出到日志以供调试
spring.jpa.show-sql=true

CacheConfig

package com.study.springboot_cache.config;

import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * 这是一个自定义的缓存键生成器(KeyGenerator)配置类。
 * 在这个配置类中,你重写了 CachingConfigurerSupport 类的 keyGenerator() 方法,
 * 用于生成缓存的键,避免出现重复的键。
 */
@Configuration
public class CacheConfig extends CachingConfigurerSupport {

    @Bean
    @Override //alt+insert
    public KeyGenerator keyGenerator() {
        return new KeyGenerator() {
            /**
             * 将目标对象的类名、方法名和参数数组拼接起来作为键的生成规则,以确保缓存的唯一性
             */
            @Override
            public Object generate(Object target, Method method, Object... objects) {
                StringBuilder sb = new StringBuilder();
                sb.append(target.getClass().getName())
                        .append(".")
                        .append(method.getName())
                        .append(Arrays.toString(objects));
                return sb.toString();
            }
        };
    }
}

Book

package com.study.springboot_cache.entity;

import lombok.Data;
import lombok.ToString;

import javax.persistence.*;
import java.time.LocalDate;

@Data
@ToString
@Entity
@Table(name = "books")
public class Book {

    //主键自动增长
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;//主键ID
    private String title;//书名
    private String author;//作者
    private String bookConcern;//出版社
    private LocalDate publishDate;//出版日期
    private Float price;//价格
}

BookRepository接口

package com.study.springboot_cache.repository;

import com.study.springboot_cache.entity.Book;
import org.springframework.data.jpa.repository.JpaRepository;

public interface BookRepository extends JpaRepository<Book,Integer> {
    Book getById(Integer id);
}

BookService服务类

package com.study.springboot_cache.service;

import com.study.springboot_cache.entity.Book;
import com.study.springboot_cache.repository.BookRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

/**
 * @CacheConfig(cacheNames = "book")在类级别共享一些共同的缓存相关配置
 * 设置缓存的名称为book
 */
@Service
@CacheConfig(cacheNames = "book")
public class BookService {

    @Autowired
    private BookRepository bookRepository;

    /**
     * @Cacheable根据方法参数将方法结果保存到缓存中,在后续使用相同参数调用方法时,
     * 会直接返回缓存中的值,而不再调用目标方法
     */
    @Cacheable
    public Book getBookById(Integer id){
        System.out.println("getBookById: "+id);
        return bookRepository.getById(id);
    }

    /**
     * @CachePut(key = "#result.id")调用方法以更新缓存
     * key = "#result.id": 缓存的key,其值为SpEL表达式
     */
    @CachePut(key = "#result.id")
    public Book saveBook(Book book){
        System.out.println("saveBook: "+book);
        book = bookRepository.save(book);
        return book;
    }

    @CachePut(key = "#result.id")
    public Book updateBook(Book book){
        System.out.println("updateBook: "+book);
        book = bookRepository.save(book);
        return book;
    }

    /**
     * @CacheEvict(beforeInvocation = true)删除缓存中过时或未使用的数据
     * beforeInvocation = true: 在方法执行前删除
     */
    @CacheEvict(beforeInvocation = true)
    public void deleteBook(Integer id){
        System.out.println("deleteBook: "+id);
        bookRepository.deleteById(id);
    }
}

BookController控制器

package com.study.springboot_cache.controller;

import com.study.springboot_cache.entity.Book;
import com.study.springboot_cache.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/book")
public class BookController {

    @Autowired
    private BookService bookService;

    @PostMapping
    public String saveBook(@RequestBody Book book){
        Book resultBook = bookService.saveBook(book);
        return resultBook.toString();
    }

    @GetMapping("/{id}")
    public String getBookById(@PathVariable Integer id){
        Book resultBook = bookService.getBookById(id);
        return resultBook.toString();
    }

    @PutMapping
    public String updateBook(@RequestBody Book book){
        Book resultBook = bookService.updateBook(book);
        return resultBook.toString();
    }

    @DeleteMapping
    public String deleteBook(@PathVariable Integer id){
        bookService.deleteBook(id);
        return "删除成功!";
    }
}

SpringbootCacheApplication启动类

package com.study.springboot_cache;

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

@SpringBootApplication
@EnableCaching //启用缓存
public class SpringbootCacheApplication {

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

}

启动项目,使用Postman测试

1、向表中添加数据

2、查询数据

3、 更改数据

 

举报

相关推荐

0 条评论