当前位置: 代码网 > it编程>编程语言>Java > Spring Boot 缓存管理与优化实例教程

Spring Boot 缓存管理与优化实例教程

2026年04月28日 Java 我要评论
spring boot 缓存管理与优化35.1 学习目标与重点提示学习目标:掌握spring boot缓存管理与优化的核心概念与使用方法,包括缓存的定义与特点、spring boot与缓存的集成、缓存

spring boot 缓存管理与优化

35.1 学习目标与重点提示

学习目标:掌握spring boot缓存管理与优化的核心概念与使用方法,包括缓存的定义与特点、spring boot与缓存的集成、缓存策略的配置与优化、spring boot的实际应用场景,学会在实际开发中处理缓存管理与优化问题。
重点:缓存的定义与特点spring boot与缓存的集成缓存策略的配置与优化spring boot的实际应用场景

35.2 缓存管理与优化概述

缓存管理与优化是java开发中的重要组件,用于提高系统的性能和响应速度。

35.2.1 缓存的定义

定义:缓存是一种将数据暂时存储在高速存储介质中的技术,用于提高数据访问速度。
作用

  • 提高数据访问速度。
  • 减少数据库压力。
  • 提高系统的响应速度。

常见的缓存

  • 内存缓存。
  • 磁盘缓存。
  • 分布式缓存。

✅ 结论:缓存是一种将数据暂时存储在高速存储介质中的技术,作用是提高数据访问速度、减少数据库压力、提高系统的响应速度。

35.2.2 缓存管理的定义

定义:缓存管理是指对缓存进行管理和优化,确保缓存的有效性和高性能。
作用

  • 提高缓存的有效性。
  • 提高系统的性能。
  • 确保缓存的可靠性。

常见的缓存管理

  • 缓存的添加。
  • 缓存的删除。
  • 缓存的更新。
  • 缓存的淘汰。

✅ 结论:缓存管理是指对缓存进行管理和优化,作用是提高缓存的有效性、提高系统的性能、确保缓存的可靠性。

35.3 spring boot与缓存的集成

spring boot与缓存的集成是java开发中的重要内容。

35.3.1 集成spring cache的步骤

定义:集成spring cache的步骤是指使用spring boot与spring cache集成的方法。
步骤

  1. 创建spring boot项目。
  2. 添加所需的依赖。
  3. 配置缓存。
  4. 创建实体类。
  5. 创建业务层。
  6. 创建控制器类。
  7. 测试应用。

示例
pom.xml文件中的依赖:

<dependencies>
    <!-- web依赖 -->
    <dependency>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-starter-web</artifactid>
    </dependency>
    <!-- 缓存依赖 -->
    <dependency>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-starter-cache</artifactid>
    </dependency>
    <!-- 数据验证依赖 -->
    <dependency>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-starter-validation</artifactid>
    </dependency>
    <!-- 测试依赖 -->
    <dependency>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-starter-test</artifactid>
        <scope>test</scope>
    </dependency>
</dependencies>

application.properties文件中的配置:

# 服务器端口
server.port=8080
# 缓存配置
spring.cache.type=simple

实体类:

import javax.validation.constraints.*;
public class product {
    private long id;
    @notblank(message = "产品id不能为空")
    @size(min = 3, max = 10, message = "产品id长度必须在3到10个字符之间")
    private string productid;
    @notblank(message = "产品名称不能为空")
    @size(min = 2, max = 50, message = "产品名称长度必须在2到50个字符之间")
    private string productname;
    @min(value = 0, message = "价格必须大于等于0")
    @max(value = 10000, message = "价格必须小于等于10000")
    private double price;
    @min(value = 0, message = "库存必须大于等于0")
    private int stock;
    public product() {
    }
    public product(long id, string productid, string productname, double price, int stock) {
        this.id = id;
        this.productid = productid;
        this.productname = productname;
        this.price = price;
        this.stock = stock;
    }
    // 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 getstock() {
        return stock;
    }
    public void setstock(int stock) {
        this.stock = stock;
    }
    @override
    public string tostring() {
        return "product{" +
                "id=" + id +
                ", productid='" + productid + '\'' +
                ", productname='" + productname + '\'' +
                ", price=" + price +
                ", stock=" + stock +
                '}';
    }
}

repository接口:

import org.springframework.stereotype.repository;
import java.util.arraylist;
import java.util.list;
import java.util.stream.collectors;
@repository
public class productrepository {
    private list<product> products = new arraylist<>();
    public productrepository() {
        products.add(new product(1l, "p001", "手机", 1000.0, 100));
        products.add(new product(2l, "p002", "电脑", 5000.0, 50));
        products.add(new product(3l, "p003", "电视", 3000.0, 80));
        products.add(new product(4l, "p004", "手表", 500.0, 200));
        products.add(new product(5l, "p005", "耳机", 300.0, 150));
    }
    public list<product> getallproducts() {
        return products;
    }
    public product getproductbyid(long id) {
        return products.stream().filter(product -> product.getid().equals(id)).findfirst().orelse(null);
    }
    public void addproduct(product product) {
        product.setid((long) (products.size() + 1));
        products.add(product);
    }
    public void updateproduct(product product) {
        product existingproduct = getproductbyid(product.getid());
        if (existingproduct != null) {
            existingproduct.setproductid(product.getproductid());
            existingproduct.setproductname(product.getproductname());
            existingproduct.setprice(product.getprice());
            existingproduct.setstock(product.getstock());
        }
    }
    public void deleteproduct(long id) {
        products.removeif(product -> product.getid().equals(id));
    }
}

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 java.util.list;
@service
public class productservice {
    @autowired
    private productrepository productrepository;
    @cacheable("products")
    public list<product> getallproducts() {
        system.out.println("从数据库获取所有产品");
        return productrepository.getallproducts();
    }
    @cacheable(value = "product", key = "#id")
    public product getproductbyid(long id) {
        system.out.println("从数据库获取产品:" + id);
        return productrepository.getproductbyid(id);
    }
    @cacheput(value = "product", key = "#product.id")
    public product addproduct(product product) {
        system.out.println("添加产品到数据库");
        productrepository.addproduct(product);
        return product;
    }
    @cacheput(value = "product", key = "#product.id")
    public product updateproduct(product product) {
        system.out.println("更新产品到数据库:" + product.getid());
        productrepository.updateproduct(product);
        return product;
    }
    @cacheevict(value = {"product", "products"}, key = "#id")
    public void deleteproduct(long id) {
        system.out.println("删除产品:" + id);
        productrepository.deleteproduct(id);
    }
}

控制器类:

import org.springframework.beans.factory.annotation.autowired;
import org.springframework.validation.bindingresult;
import org.springframework.validation.fielderror;
import org.springframework.web.bind.annotation.*;
import javax.validation.valid;
import java.util.hashmap;
import java.util.list;
import java.util.map;
@restcontroller
@requestmapping("/api/products")
public class productcontroller {
    @autowired
    private productservice productservice;
    @getmapping("/")
    public list<product> getallproducts() {
        return productservice.getallproducts();
    }
    @getmapping("/{id}")
    public product getproductbyid(@pathvariable long id) {
        return productservice.getproductbyid(id);
    }
    @postmapping("/add")
    public map<string, object> addproduct(@valid @requestbody product product, bindingresult bindingresult) {
        map<string, object> result = new hashmap<>();
        if (bindingresult.haserrors()) {
            map<string, string> errors = new hashmap<>();
            for (fielderror error : bindingresult.getfielderrors()) {
                errors.put(error.getfield(), error.getdefaultmessage());
            }
            result.put("success", false);
            result.put("errors", errors);
            return result;
        }
        productservice.addproduct(product);
        result.put("success", true);
        result.put("message", "产品添加成功");
        return result;
    }
    @putmapping("/edit/{id}")
    public map<string, object> editproduct(@pathvariable long id, @valid @requestbody product product, bindingresult bindingresult) {
        map<string, object> result = new hashmap<>();
        if (bindingresult.haserrors()) {
            map<string, string> errors = new hashmap<>();
            for (fielderror error : bindingresult.getfielderrors()) {
                errors.put(error.getfield(), error.getdefaultmessage());
            }
            result.put("success", false);
            result.put("errors", errors);
            return result;
        }
        product.setid(id);
        productservice.updateproduct(product);
        result.put("success", true);
        result.put("message", "产品更新成功");
        return result;
    }
    @deletemapping("/delete/{id}")
    public map<string, object> deleteproduct(@pathvariable long id) {
        map<string, object> result = new hashmap<>();
        productservice.deleteproduct(id);
        result.put("success", true);
        result.put("message", "产品删除成功");
        return result;
    }
}

应用启动类:

import org.springframework.boot.springapplication;
import org.springframework.boot.autoconfigure.springbootapplication;
import org.springframework.cache.annotation.enablecaching;
@springbootapplication
@enablecaching
public class cacheapplication {
    public static void main(string[] args) {
        springapplication.run(cacheapplication.class, args);
    }
}

测试类:

import org.junit.jupiter.api.test;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.boot.test.context.springboottest;
import org.springframework.boot.test.web.client.testresttemplate;
import org.springframework.boot.web.server.localserverport;
import org.springframework.http.*;
import java.util.hashmap;
import java.util.map;
import static org.assertj.core.api.assertions.assertthat;
@springboottest(webenvironment = springboottest.webenvironment.random_port)
class cacheapplicationtests {
    @localserverport
    private int port;
    @autowired
    private testresttemplate resttemplate;
    @test
    void contextloads() {
    }
    @test
    void testaddproduct() {
        map<string, object> product = new hashmap<>();
        product.put("productid", "p006");
        product.put("productname", "耳机");
        product.put("price", 300.0);
        product.put("stock", 150);
        httpheaders headers = new httpheaders();
        headers.setcontenttype(mediatype.application_json);
        httpentity<map<string, object>> request = new httpentity<>(product, headers);
        responseentity<map> response = resttemplate.exchange(
                "http://localhost:" + port + "/api/products/add",
                httpmethod.post,
                request,
                map.class
        );
        assertthat(response.getstatuscode()).isequalto(httpstatus.ok);
        assertthat(response.getbody().get("success")).isequalto(true);
    }
    @test
    void testgetproductbyid() {
        responseentity<product> response = resttemplate.getforentity("http://localhost:" + port + "/api/products/1", product.class);
        assertthat(response.getstatuscode()).isequalto(httpstatus.ok);
        assertthat(response.getbody()).isnotnull();
        // 第二次请求,应该从缓存获取
        response = resttemplate.getforentity("http://localhost:" + port + "/api/products/1", product.class);
        assertthat(response.getstatuscode()).isequalto(httpstatus.ok);
        assertthat(response.getbody()).isnotnull();
    }
    @test
    void testupdateproduct() {
        map<string, object> product = new hashmap<>();
        product.put("productid", "p001-update");
        product.put("productname", "手机-更新");
        product.put("price", 1500.0);
        product.put("stock", 150);
        httpheaders headers = new httpheaders();
        headers.setcontenttype(mediatype.application_json);
        httpentity<map<string, object>> request = new httpentity<>(product, headers);
        responseentity<map> response = resttemplate.exchange(
                "http://localhost:" + port + "/api/products/edit/1",
                httpmethod.put,
                request,
                map.class
        );
        assertthat(response.getstatuscode()).isequalto(httpstatus.ok);
        assertthat(response.getbody().get("success")).isequalto(true);
    }
    @test
    void testdeleteproduct() {
        responseentity<map> response = resttemplate.exchange(
                "http://localhost:" + port + "/api/products/delete/1",
                httpmethod.delete,
                null,
                map.class
        );
        assertthat(response.getstatuscode()).isequalto(httpstatus.ok);
        assertthat(response.getbody().get("success")).isequalto(true);
    }
}

✅ 结论:集成spring cache的步骤包括创建spring boot项目、添加所需的依赖、配置缓存、创建实体类、创建业务层、创建控制器类、测试应用。

35.4 缓存策略的配置与优化

缓存策略的配置与优化是java开发中的重要内容。

35.4.1 缓存策略的定义

定义:缓存策略是指对缓存进行配置和优化的方法,包括缓存的添加、删除、更新、淘汰等策略。
作用

  • 提高缓存的有效性。
  • 提高系统的性能。
  • 确保缓存的可靠性。

常见的缓存策略

  • 缓存的添加策略。
  • 缓存的删除策略。
  • 缓存的更新策略。
  • 缓存的淘汰策略。

✅ 结论:缓存策略是指对缓存进行配置和优化的方法,作用是提高缓存的有效性、提高系统的性能、确保缓存的可靠性。

35.4.2 缓存策略的配置与优化

定义:缓存策略的配置与优化是指对缓存进行配置和优化的方法。
示例

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 java.util.list;
@service
class productservice {
    @autowired
    private productrepository productrepository;
    @cacheable("products")
    public list<product> getallproducts() {
        system.out.println("从数据库获取所有产品");
        return productrepository.getallproducts();
    }
    @cacheable(value = "product", key = "#id")
    public product getproductbyid(long id) {
        system.out.println("从数据库获取产品:" + id);
        return productrepository.getproductbyid(id);
    }
    @cacheput(value = "product", key = "#product.id")
    public product addproduct(product product) {
        system.out.println("添加产品到数据库");
        productrepository.addproduct(product);
        return product;
    }
    @cacheput(value = "product", key = "#product.id")
    public product updateproduct(product product) {
        system.out.println("更新产品到数据库:" + product.getid());
        productrepository.updateproduct(product);
        return product;
    }
    @cacheevict(value = {"product", "products"}, key = "#id")
    public void deleteproduct(long id) {
        system.out.println("删除产品:" + id);
        productrepository.deleteproduct(id);
    }
}
import javax.validation.constraints.*;
class product {
    private long id;
    @notblank(message = "产品id不能为空")
    @size(min = 3, max = 10, message = "产品id长度必须在3到10个字符之间")
    private string productid;
    @notblank(message = "产品名称不能为空")
    @size(min = 2, max = 50, message = "产品名称长度必须在2到50个字符之间")
    private string productname;
    @min(value = 0, message = "价格必须大于等于0")
    @max(value = 10000, message = "价格必须小于等于10000")
    private double price;
    @min(value = 0, message = "库存必须大于等于0")
    private int stock;
    public product() {
    }
    public product(long id, string productid, string productname, double price, int stock) {
        this.id = id;
        this.productid = productid;
        this.productname = productname;
        this.price = price;
        this.stock = stock;
    }
    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 getstock() {
        return stock;
    }
    public void setstock(int stock) {
        this.stock = stock;
    }
    @override
    public string tostring() {
        return "product{" +
                "id=" + id +
                ", productid='" + productid + '\'' +
                ", productname='" + productname + '\'' +
                ", price=" + price +
                ", stock=" + stock +
                '}';
    }
}
import org.springframework.stereotype.repository;
import java.util.arraylist;
import java.util.list;
import java.util.stream.collectors;
@repository
class productrepository {
    private list<product> products = new arraylist<>();
    public productrepository() {
        products.add(new product(1l, "p001", "手机", 1000.0, 100));
        products.add(new product(2l, "p002", "电脑", 5000.0, 50));
        products.add(new product(3l, "p003", "电视", 3000.0, 80));
        products.add(new product(4l, "p004", "手表", 500.0, 200));
        products.add(new product(5l, "p005", "耳机", 300.0, 150));
    }
    public list<product> getallproducts() {
        return products;
    }
    public product getproductbyid(long id) {
        return products.stream().filter(product -> product.getid().equals(id)).findfirst().orelse(null);
    }
    public void addproduct(product product) {
        product.setid((long) (products.size() + 1));
        products.add(product);
    }
    public void updateproduct(product product) {
        product existingproduct = getproductbyid(product.getid());
        if (existingproduct != null) {
            existingproduct.setproductid(product.getproductid());
            existingproduct.setproductname(product.getproductname());
            existingproduct.setprice(product.getprice());
            existingproduct.setstock(product.getstock());
        }
    }
    public void deleteproduct(long id) {
        products.removeif(product -> product.getid().equals(id));
    }
}
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.validation.bindingresult;
import org.springframework.validation.fielderror;
import org.springframework.web.bind.annotation.*;
import javax.validation.valid;
import java.util.hashmap;
import java.util.list;
import java.util.map;
@restcontroller
@requestmapping("/api/products")
class productcontroller {
    @autowired
    private productservice productservice;
    @getmapping("/")
    public list<product> getallproducts() {
        return productservice.getallproducts();
    }
    @getmapping("/{id}")
    public product getproductbyid(@pathvariable long id) {
        return productservice.getproductbyid(id);
    }
    @postmapping("/add")
    public map<string, object> addproduct(@valid @requestbody product product, bindingresult bindingresult) {
        map<string, object> result = new hashmap<>();
        if (bindingresult.haserrors()) {
            map<string, string> errors = new hashmap<>();
            for (fielderror error : bindingresult.getfielderrors()) {
                errors.put(error.getfield(), error.getdefaultmessage());
            }
            result.put("success", false);
            result.put("errors", errors);
            return result;
        }
        productservice.addproduct(product);
        result.put("success", true);
        result.put("message", "产品添加成功");
        return result;
    }
    @putmapping("/edit/{id}")
    public map<string, object> editproduct(@pathvariable long id, @valid @requestbody product product, bindingresult bindingresult) {
        map<string, object> result = new hashmap<>();
        if (bindingresult.haserrors()) {
            map<string, string> errors = new hashmap<>();
            for (fielderror error : bindingresult.getfielderrors()) {
                errors.put(error.getfield(), error.getdefaultmessage());
            }
            result.put("success", false);
            result.put("errors", errors);
            return result;
        }
        product.setid(id);
        productservice.updateproduct(product);
        result.put("success", true);
        result.put("message", "产品更新成功");
        return result;
    }
    @deletemapping("/delete/{id}")
    public map<string, object> deleteproduct(@pathvariable long id) {
        map<string, object> result = new hashmap<>();
        productservice.deleteproduct(id);
        result.put("success", true);
        result.put("message", "产品删除成功");
        return result;
    }
}
@springbootapplication
@enablecaching
public class cacheapplication {
    public static void main(string[] args) {
        springapplication.run(cacheapplication.class, args);
    }
}
// 测试类
@springboottest(webenvironment = springboottest.webenvironment.random_port)
class cacheapplicationtests {
    @localserverport
    private int port;
    @autowired
    private testresttemplate resttemplate;
    @test
    void contextloads() {
    }
    @test
    void testaddproduct() {
        map<string, object> product = new hashmap<>();
        product.put("productid", "p006");
        product.put("productname", "耳机");
        product.put("price", 300.0);
        product.put("stock", 150);
        httpheaders headers = new httpheaders();
        headers.setcontenttype(mediatype.application_json);
        httpentity<map<string, object>> request = new httpentity<>(product, headers);
        responseentity<map> response = resttemplate.exchange(
                "http://localhost:" + port + "/api/products/add",
                httpmethod.post,
                request,
                map.class
        );
        assertthat(response.getstatuscode()).isequalto(httpstatus.ok);
        assertthat(response.getbody().get("success")).isequalto(true);
    }
    @test
    void testgetproductbyid() {
        responseentity<product> response = resttemplate.getforentity("http://localhost:" + port + "/api/products/1", product.class);
        assertthat(response.getstatuscode()).isequalto(httpstatus.ok);
        assertthat(response.getbody()).isnotnull();
        response = resttemplate.getforentity("http://localhost:" + port + "/api/products/1", product.class);
        assertthat(response.getstatuscode()).isequalto(httpstatus.ok);
        assertthat(response.getbody()).isnotnull();
    }
    @test
    void testupdateproduct() {
        map<string, object> product = new hashmap<>();
        product.put("productid", "p001-update");
        product.put("productname", "手机-更新");
        product.put("price", 1500.0);
        product.put("stock", 150);
        httpheaders headers = new httpheaders();
        headers.setcontenttype(mediatype.application_json);
        httpentity<map<string, object>> request = new httpentity<>(product, headers);
        responseentity<map> response = resttemplate.exchange(
                "http://localhost:" + port + "/api/products/edit/1",
                httpmethod.put,
                request,
                map.class
        );
        assertthat(response.getstatuscode()).isequalto(httpstatus.ok);
        assertthat(response.getbody().get("success")).isequalto(true);
    }
    @test
    void testdeleteproduct() {
        responseentity<map> response = resttemplate.exchange(
                "http://localhost:" + port + "/api/products/delete/1",
                httpmethod.delete,
                null,
                map.class
        );
        assertthat(response.getstatuscode()).isequalto(httpstatus.ok);
        assertthat(response.getbody().get("success")).isequalto(true);
    }
}

✅ 结论:缓存策略的配置与优化是指对缓存进行配置和优化的方法,需要根据实际问题选择合适的缓存策略。

35.5 spring boot的实际应用场景

在实际开发中,spring boot缓存管理与优化的应用场景非常广泛,如:

  • 实现产品信息的缓存。
  • 实现用户信息的缓存。
  • 实现订单信息的缓存。
  • 实现页面数据的缓存。

示例

import javax.validation.constraints.*;
class product {
    private long id;
    @notblank(message = "产品id不能为空")
    @size(min = 3, max = 10, message = "产品id长度必须在3到10个字符之间")
    private string productid;
    @notblank(message = "产品名称不能为空")
    @size(min = 2, max = 50, message = "产品名称长度必须在2到50个字符之间")
    private string productname;
    @min(value = 0, message = "价格必须大于等于0")
    @max(value = 10000, message = "价格必须小于等于10000")
    private double price;
    @min(value = 0, message = "库存必须大于等于0")
    private int stock;
    public product() {
    }
    public product(long id, string productid, string productname, double price, int stock) {
        this.id = id;
        this.productid = productid;
        this.productname = productname;
        this.price = price;
        this.stock = stock;
    }
    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 getstock() {
        return stock;
    }
    public void setstock(int stock) {
        this.stock = stock;
    }
    @override
    public string tostring() {
        return "product{" +
                "id=" + id +
                ", productid='" + productid + '\'' +
                ", productname='" + productname + '\'' +
                ", price=" + price +
                ", stock=" + stock +
                '}';
    }
}
import org.springframework.stereotype.repository;
import java.util.arraylist;
import java.util.list;
import java.util.stream.collectors;
@repository
class productrepository {
    private list<product> products = new arraylist<>();
    public productrepository() {
        products.add(new product(1l, "p001", "手机", 1000.0, 100));
        products.add(new product(2l, "p002", "电脑", 5000.0, 50));
        products.add(new product(3l, "p003", "电视", 3000.0, 80));
        products.add(new product(4l, "p004", "手表", 500.0, 200));
        products.add(new product(5l, "p005", "耳机", 300.0, 150));
    }
    public list<product> getallproducts() {
        return products;
    }
    public product getproductbyid(long id) {
        return products.stream().filter(product -> product.getid().equals(id)).findfirst().orelse(null);
    }
    public void addproduct(product product) {
        product.setid((long) (products.size() + 1));
        products.add(product);
    }
    public void updateproduct(product product) {
        product existingproduct = getproductbyid(product.getid());
        if (existingproduct != null) {
            existingproduct.setproductid(product.getproductid());
            existingproduct.setproductname(product.getproductname());
            existingproduct.setprice(product.getprice());
            existingproduct.setstock(product.getstock());
        }
    }
    public void deleteproduct(long id) {
        products.removeif(product -> product.getid().equals(id));
    }
}
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 java.util.list;
@service
class productservice {
    @autowired
    private productrepository productrepository;
    @cacheable("products")
    public list<product> getallproducts() {
        system.out.println("从数据库获取所有产品");
        return productrepository.getallproducts();
    }
    @cacheable(value = "product", key = "#id")
    public product getproductbyid(long id) {
        system.out.println("从数据库获取产品:" + id);
        return productrepository.getproductbyid(id);
    }
    @cacheput(value = "product", key = "#product.id")
    public product addproduct(product product) {
        system.out.println("添加产品到数据库");
        productrepository.addproduct(product);
        return product;
    }
    @cacheput(value = "product", key = "#product.id")
    public product updateproduct(product product) {
        system.out.println("更新产品到数据库:" + product.getid());
        productrepository.updateproduct(product);
        return product;
    }
    @cacheevict(value = {"product", "products"}, key = "#id")
    public void deleteproduct(long id) {
        system.out.println("删除产品:" + id);
        productrepository.deleteproduct(id);
    }
}
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.validation.bindingresult;
import org.springframework.validation.fielderror;
import org.springframework.web.bind.annotation.*;
import javax.validation.valid;
import java.util.hashmap;
import java.util.list;
import java.util.map;
@restcontroller
@requestmapping("/api/products")
class productcontroller {
    @autowired
    private productservice productservice;
    @getmapping("/")
    public list<product> getallproducts() {
        return productservice.getallproducts();
    }
    @getmapping("/{id}")
    public product getproductbyid(@pathvariable long id) {
        return productservice.getproductbyid(id);
    }
    @postmapping("/add")
    public map<string, object> addproduct(@valid @requestbody product product, bindingresult bindingresult) {
        map<string, object> result = new hashmap<>();
        if (bindingresult.haserrors()) {
            map<string, string> errors = new hashmap<>();
            for (fielderror error : bindingresult.getfielderrors()) {
                errors.put(error.getfield(), error.getdefaultmessage());
            }
            result.put("success", false);
            result.put("errors", errors);
            return result;
        }
        productservice.addproduct(product);
        result.put("success", true);
        result.put("message", "产品添加成功");
        return result;
    }
    @putmapping("/edit/{id}")
    public map<string, object> editproduct(@pathvariable long id, @valid @requestbody product product, bindingresult bindingresult) {
        map<string, object> result = new hashmap<>();
        if (bindingresult.haserrors()) {
            map<string, string> errors = new hashmap<>();
            for (fielderror error : bindingresult.getfielderrors()) {
                errors.put(error.getfield(), error.getdefaultmessage());
            }
            result.put("success", false);
            result.put("errors", errors);
            return result;
        }
        product.setid(id);
        productservice.updateproduct(product);
        result.put("success", true);
        result.put("message", "产品更新成功");
        return result;
    }
    @deletemapping("/delete/{id}")
    public map<string, object> deleteproduct(@pathvariable long id) {
        map<string, object> result = new hashmap<>();
        productservice.deleteproduct(id);
        result.put("success", true);
        result.put("message", "产品删除成功");
        return result;
    }
}
@springbootapplication
@enablecaching
public class cacheapplication {
    public static void main(string[] args) {
        springapplication.run(cacheapplication.class, args);
    }
}
// 测试类
@springboottest(webenvironment = springboottest.webenvironment.random_port)
class cacheapplicationtests {
    @localserverport
    private int port;
    @autowired
    private testresttemplate resttemplate;
    @test
    void contextloads() {
    }
    @test
    void testaddproduct() {
        map<string, object> product = new hashmap<>();
        product.put("productid", "p006");
        product.put("productname", "耳机");
        product.put("price", 300.0);
        product.put("stock", 150);
        httpheaders headers = new httpheaders();
        headers.setcontenttype(mediatype.application_json);
        httpentity<map<string, object>> request = new httpentity<>(product, headers);
        responseentity<map> response = resttemplate.exchange(
                "http://localhost:" + port + "/api/products/add",
                httpmethod.post,
                request,
                map.class
        );
        assertthat(response.getstatuscode()).isequalto(httpstatus.ok);
        assertthat(response.getbody().get("success")).isequalto(true);
    }
    @test
    void testgetproductbyid() {
        responseentity<product> response = resttemplate.getforentity("http://localhost:" + port + "/api/products/1", product.class);
        assertthat(response.getstatuscode()).isequalto(httpstatus.ok);
        assertthat(response.getbody()).isnotnull();
        response = resttemplate.getforentity("http://localhost:" + port + "/api/products/1", product.class);
        assertthat(response.getstatuscode()).isequalto(httpstatus.ok);
        assertthat(response.getbody()).isnotnull();
    }
    @test
    void testupdateproduct() {
        map<string, object> product = new hashmap<>();
        product.put("productid", "p001-update");
        product.put("productname", "手机-更新");
        product.put("price", 1500.0);
        product.put("stock", 150);
        httpheaders headers = new httpheaders();
        headers.setcontenttype(mediatype.application_json);
        httpentity<map<string, object>> request = new httpentity<>(product, headers);
        responseentity<map> response = resttemplate.exchange(
                "http://localhost:" + port + "/api/products/edit/1",
                httpmethod.put,
                request,
                map.class
        );
        assertthat(response.getstatuscode()).isequalto(httpstatus.ok);
        assertthat(response.getbody().get("success")).isequalto(true);
    }
    @test
    void testdeleteproduct() {
        responseentity<map> response = resttemplate.exchange(
                "http://localhost:" + port + "/api/products/delete/1",
                httpmethod.delete,
                null,
                map.class
        );
        assertthat(response.getstatuscode()).isequalto(httpstatus.ok);
        assertthat(response.getbody().get("success")).isequalto(true);
    }
}

输出结果

  • 第一次请求获取所有产品:从数据库获取所有产品。
  • 第二次请求获取所有产品:从缓存获取。
  • 第一次请求获取产品1:从数据库获取。
  • 第二次请求获取产品1:从缓存获取。

✅ 结论:在实际开发中,spring boot缓存管理与优化的应用场景非常广泛,需要根据实际问题选择合适的缓存策略和优化方法。

总结

本章我们学习了spring boot缓存管理与优化,包括缓存的定义与特点、spring boot与缓存的集成、缓存策略的配置与优化、spring boot的实际应用场景,学会了在实际开发中处理缓存管理与优化问题。其中,缓存的定义与特点、spring boot与缓存的集成、缓存策略的配置与优化、spring boot的实际应用场景是本章的重点内容。从下一章开始,我们将学习spring boot的其他组件、微服务等内容。

到此这篇关于spring boot 缓存管理与优化实例教程的文章就介绍到这了,更多相关springboot缓存管理与优化内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com