SpringBoot数据缓存Cache

本文介绍如何在Spring Boot应用中实现缓存管理,通过添加依赖并利用Spring提供的缓存注解,有效提升程序性能。具体介绍了@Cacheable、@CachePut、@CacheEvict等注解的使用场景。

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

        我们知道一个程序的瓶颈在于数据库,我们也知道内存的速度是大大快于硬盘的速度的。当我们需要重复的获取相同的市局的时候,我们一次又一次的请求数据库或者远程服务,导致大量的时间耗费在数据库查询或者远程方法调用上,导致程序性能的恶化,这边是数据缓存要解决的问题。

首先得添加依赖

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-cache</artifactId>
		</dependency>

声明是缓存注解

Spring提供了四个注解来声明缓存规则(又是使用注解式的AOP的一个生动例子),这四个注解如下:

@Cacheable    在方法执行前Spring先查看缓存中是否有数据,如果有数据,则直接返回缓存数据;如果没有数据,调用方法讲方法返回值放进缓存

@CachePut      无论怎么样,都回将方法返回值放入缓存中。@CachePut属性与@Cacheable保持一致

@CacheEvict    将一条或多条数据从缓存中删除

@Caching        可以通过@Caching注解组合多个注解策略在一个方法上

@Cacheable,@CachePut,@CacheEvit都有Value属性,指定的是要用缓存的名称;key属性指定的是缓存数据在缓存中存储的键值。

开启声明式缓存支持直接在启动类加个注解就好

package com.cn.sola;

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

import springfox.documentation.swagger2.annotations.EnableSwagger2;

@SpringBootApplication
@EnableSwagger2
@EnableCaching
public class BootEhcacheApplication {

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

实例------------------------------------------------------------------

此例子以Spring Boot默认的ConcurrentMapCacheManager作为缓存技术,最后会用Ehcache,Guava来替换缓存技术

实体类

package com.cn.sola.bean;

import java.io.Serializable;

public class Emp implements Serializable{

	private String id;
	private String name;
	private String age;
	
	private String job;
	private String boss;
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAge() {
		return age;
	}
	public void setAge(String age) {
		this.age = age;
	}
	public String getJob() {
		return job;
	}
	public void setJob(String job) {
		this.job = job;
	}
	public String getBoss() {
		return boss;
	}
	public void setBoss(String boss) {
		this.boss = boss;
	}
	
}

Controller

package com.cn.sola.controller;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.cn.sola.bean.Emp;
import com.cn.sola.service.EhcacheService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping("xe")
@Api(tags= {"Ehcache学习"})
public class EhcacheController {
	
	@Autowired
	private EhcacheService ehcacheservice;

	@ApiOperation("ehcache查询")
	@GetMapping("getlist")
	public List<Map<String,Object>> getEmp(String id){
		return ehcacheservice.getEmp(id);
		
	}
	
	@ApiOperation("ehcache删除")
	@GetMapping("remove")
	public boolean removetOne(String id){
		return ehcacheservice.removetOne(id);
		
	}
	
	@ApiOperation("ehcache新增")
	@PostMapping("add")
	public boolean add(@RequestBody Emp emp){
		return ehcacheservice.add(emp);
		
	}
	
	
}

Service

package com.cn.sola.service;

import java.util.List;
import java.util.Map;

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 com.cn.sola.bean.Emp;
import com.cn.sola.dao.EhcacheMapper;

@Service
public class EhcacheService {

	@Autowired
	private EhcacheMapper ehcachemapper;
	
	@Cacheable(value="sola",key="#id")//value属性是指缓存名 key是指就是key
	public List<Map<String, Object>> getEmp(String id) {
		
		return ehcachemapper.getEmp(id);
	}

	@CacheEvict(value="sola")//从缓存SOLA中删除key为id的数据
	public boolean removetOne(String id) {
		// TODO Auto-generated method stub
		return ehcachemapper.removetOne(id);
	}

	@CachePut(value="sola",key="#emp.id")//缓存新增的或更新数据到缓存,其中缓存的名称为sola,数据的Key是emp的id
	public boolean add(Emp emp) {
		// TODO Auto-generated method stub
		
		return ehcachemapper.add(emp);
	}
	
	

}
剩下部分正常没区别,运行时记得要开启缓存支持~~~~~



额。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。

### Spring Boot 实现 Cache 缓存机制 示例教程 #### 配置缓存支持 为了使项目能够使用声明式的缓存特性,在配置类中添加 `@EnableCaching` 注解来开启这一功能[^1]。 ```java @Configuration @EnableCaching public class CacheConfig { // 可在此处进一步自定义缓存设置 } ``` #### 使用内置缓存管理器 当应用程序未提供特定类型的 `CacheManager` 或者 `cacheResolver` Bean 组件时,Spring Boot 将自动选择合适的缓存方案,默认情况下会选择通用型(`Generic`)的实现方式[^2]。 #### 方法级别的缓存控制 对于希望被缓存的方法操作,可以利用 `@Cacheable` 注解来进行标记。此注解允许开发者指明哪个缓存应该用于存储该方法的结果,并且可以根据参数的不同组合形成不同的键值对记录下来[^4]。 ```java @Service public class MyService { @Cacheable(value = "myCache", key = "#id") public String getDataById(String id){ System.out.println("Fetching data from database..."); return "Data for ID:" + id; } } ``` 以上代码片段展示了如何在一个服务层的方法上调用 `@Cacheable` 来启用缓存行为。每当传入相同的 `id` 参数时,除非缓存过期或清除,否则不会再次触发实际的数据获取过程而是直接返回之前保存下来的响应结果。 #### 测试缓存效果 可以通过多次调用带有相同输入的服务端点来验证缓存的效果。首次请求会打印日志表明是从数据库取数;而后续具有同样参数的请求则不会再有这条消息输出,证明已经命中了缓存中的数据[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值