SpringBoot Cache Simple类型

本文详细介绍如何在Spring Boot项目中配置和使用Spring Cache,包括添加依赖、配置application.properties、启用缓存注解,并通过示例展示了Service层的缓存操作和Controller层的调用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Maven依赖

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <artifactId>springboot-cache</artifactId>
    <groupId>com.bt</groupId>
    <version>1.8-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>springboot-cache</name>

    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <spring-boot.version>2.0.4.RELEASE</spring-boot.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>${spring-boot.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
            <version>${spring-boot.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
            <version>${spring-boot.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <version>${spring-boot.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
            <version>${spring-boot.version}</version>
        </dependency>

    </dependencies>

</project>

application.properties 配置文件

#Simple:基于ConcurrentHashMap实现的缓存,只适合单体应用或者开发环境使用。Spring自带的缓存类型,这个缓存与Spring Boot应用在同一个Java虚拟机内,适合单体应用系统。
#None:禁止使用缓存。
#Redis:使用Redis缓存。
#还有其他的诸多方式
spring.cache.type=Simple

Main 入口类

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


@EnableCaching //开启缓存注解
@SpringBootApplication
@ComponentScan(basePackages = {"com.common"})
public class MainApp {

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

Service 类

public interface IBaseService {

    String queryById(Integer id);

    void deleteById(Integer id);

    String resetById(Integer id);

    void clearAllCache();
}
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.Random;


@Service
public class BaseServiceImpl implements IBaseService {

    private Random random = new Random();

    /*
        value	缓存的名称,在 spring 配置文件中定义,必须指定至少一个   例如:@Cacheable(value=”mycache”) 或者@Cacheable(value={”cache1”,”cache2”})

        key	缓存的 key,可以为空,如果指定要按照 SpEL 表达式编写,如果不指定,则缺省按照方法的所有参数进行组合   例如:@Cacheable(value=”testcache”,key=”#id”)

        condition	缓存的条件,可以为空,使用 SpEL 编写,返回 true 或者 false,只有为 true 才进行缓存/清除缓存  例如:@Cacheable(value=”testcache”,condition=”#userName.length()>2”)

        unless	否定缓存。当条件结果为TRUE时,就不会缓存。  例如@Cacheable(value=”testcache”,unless=”#userName.length()>2”)

        allEntries(@CacheEvict)	是否清空所有缓存内容,缺省为 false,如果指定为 true,则方法调用后将立即清空所有缓存  例如:@CachEvict(value=”testcache”,allEntries=true)

        beforeInvocation(@CacheEvict)	是否在方法执行前就清空,缺省为 false,如果指定为 true,则在方法还没有执行的时候就清空缓存,缺省情况下,如果方法执行抛出异常,则不会清空缓存  例如:@CachEvict(value=”testcache”,beforeInvocation=true)

        其他说明请参见:https://www.cnblogs.com/bjlhx/p/9167210.html
    */
    @Override
    @Cacheable(cacheNames = "baseCache",unless = "#result == null" ,key= "#id" )//当结果为空时不缓存
    public String queryById(Integer id) {
        Integer result = random.nextInt(100) + 1;
        System.out.println("调用服务获取数据:"+id +"->" +result);
        //这里可以先取redis缓存再查数据库
        return String.format("%s->%s",id,result);
    }

    //删除缓存
    @CacheEvict(cacheNames ="baseCache",key = "#id")
    @Override
    public void deleteById(Integer id) {
        System.out.println("调用服务删除数据:"+id);
    }

    //重新加缓存-保证方法被调用,又希望结果被缓存。(与@Cacheable区别在于是否每次都调用方法,常用于更新)
    @Override
    @CachePut(cacheNames = "baseCache" ,key="#id")
    public String resetById(Integer id) {
        Integer result = random.nextInt(100) + 1;
        System.out.println("调用服务重置数据:"+id +"->" +result);
        //这里可以先取redis缓存再查数据库
        return String.format("%s->%s",id,result);
    }

    //是否清空所有缓存内容,缺省为 false,如果指定为 true,则方法调用后将立即清空所有缓存
    @Override
    @CacheEvict(cacheNames="baseCache",allEntries=true)
    public void clearAllCache() {
        System.out.println("调用服务清空所有缓存");
    }
}

Controller服务

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Random;

@Controller
@ResponseBody
public class TestController {

    @Autowired
    private IBaseService myService;

    private Random random = new Random();

    @RequestMapping(value ="/query", method = RequestMethod.GET)
    @ResponseBody
    public String query(Integer number) throws InterruptedException {
        int id = random.nextInt(6) + 1;
        if(null==number){
            number = id;
        }
        String value = myService.queryById(number);
        return "Hello World!"+" : ["+number+" - "+value+"]";
    }

    @RequestMapping(value ="/delete", method = RequestMethod.GET)
    @ResponseBody
    public String delete(Integer number) throws InterruptedException {
        int id = random.nextInt(6) + 1;
        if(null==number){
            number = id;
        }
        myService.deleteById(number);
        return "delete:"+" : ["+number+"]";
    }

    @RequestMapping(value ="/reset", method = RequestMethod.GET)
    @ResponseBody
    public String reset(Integer number) throws InterruptedException {
        int id = random.nextInt(6) + 1;
        if(null==number){
            number = id;
        }
        String value = myService.resetById(number);
        return "reset"+" : ["+number+" - "+value+"]";
    }

    @RequestMapping(value ="/clearAll", method = RequestMethod.GET)
    @ResponseBody
    public String clearAll() throws InterruptedException {
        myService.clearAllCache();
        return "删除所有缓存数据";
    }

}

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值