SpringBoot使用缓存注解

= SpringBoot使用缓存注解


缓存注解入门三个步骤

  1. 引入spring-boot-starter-cache模块
  2. 在启动类上使用@EnableCaching注解开启缓存。
  3. 在类、方法上使用注解即可

提示:下面是简单的Hello

一、入门体验缓存注解

1. 创建SpringBoot项目,仅导入web和cache的依赖
   <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <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>
    </dependencies>
2. 在启动类上加上@EnableCaching注解
@SpringBootApplication
@EnableCaching
public class SpringBootCacheDemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringBootCacheDemoApplication.class, args);
	}
}
3.在方法上使用缓存注解
@Service
public class CacheService {

	@Cacheable(cacheNames = "testCache")
	public String word(Integer id){
		System.out.println("访问了word");
		return "aa";
	}
}

@RestController
@RequestMapping("/cache")
public class CacheController {
	@Autowired
	private CacheService cacheService;
	@RequestMapping("/world")
	public String world(Integer id){
		return cacheService.word(id);
	}
}

演示效果,多次访问该方法

在这里插入图片描述

二、整合mysql环境搭建

1.基础sql
CREATE TABLE `employee` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `lastName` varchar(255) DEFAULT NULL,
  `email` varchar(255) DEFAULT NULL,
  `gender` int(2) DEFAULT NULL,
  `d_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of employee
-- ----------------------------
INSERT INTO `employee` VALUES ('1', 'wangwu32', '13631785646@qq.com', '3', '11');
INSERT INTO `employee` VALUES ('2', '2', '2', '2', '2');

2、引入mysql依赖
 <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
3、数据库连接信息
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springboot_cache
spring.datasource.username=root
spring.datasource.password=root
4、启动mapper扫描,在注解上使用@MapperScan注解
@SpringBootApplication
@EnableCaching
@MapperScan("csdn.xiaozheng.com.springbootcachedemo.mapper")
public class SpringBootCacheDemoApplication {

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

}
5、实体和接口定义
package csdn.xiaozheng.com.springbootcachedemo.bean;

import java.io.Serializable;

public class Employee implements Serializable {
	
	private Integer id;
	private String lastName;
	private String email;
	private Integer gender; //性别 1男  0女
	private Integer dId;
	
	
	public Employee() {
		super();
	}

	
	public Employee(Integer id, String lastName, String email, Integer gender, Integer dId) {
		super();
		this.id = id;
		this.lastName = lastName;
		this.email = email;
		this.gender = gender;
		this.dId = dId;
	}
	
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public Integer getGender() {
		return gender;
	}
	public void setGender(Integer gender) {
		this.gender = gender;
	}
	public Integer getdId() {
		return dId;
	}
	public void setdId(Integer dId) {
		this.dId = dId;
	}
	@Override
	public String toString() {
		return "Employee [id=" + id + ", lastName=" + lastName + ", email=" + email + ", gender=" + gender + ", dId="
				+ dId + "]";
	}
	
	

}

package csdn.xiaozheng.com.springbootcachedemo.bean;

import java.io.Serializable;

public class Employee implements Serializable {
	
	private Integer id;
	private String lastName;
	private String email;
	private Integer gender; //性别 1男  0女
	private Integer dId;
	
	
	public Employee() {
		super();
	}

	
	public Employee(Integer id, String lastName, String email, Integer gender, Integer dId) {
		super();
		this.id = id;
		this.lastName = lastName;
		this.email = email;
		this.gender = gender;
		this.dId = dId;
	}
	
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public Integer getGender() {
		return gender;
	}
	public void setGender(Integer gender) {
		this.gender = gender;
	}
	public Integer getdId() {
		return dId;
	}
	public void setdId(Integer dId) {
		this.dId = dId;
	}
	@Override
	public String toString() {
		return "Employee [id=" + id + ", lastName=" + lastName + ", email=" + email + ", gender=" + gender + ", dId="
				+ dId + "]";
	}
	
}

package csdn.xiaozheng.com.springbootcachedemo.mapper;


import csdn.xiaozheng.com.springbootcachedemo.bean.Employee;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

@Mapper
public interface EmployeeMapper {
	@Select("select * from employee where id = #{id}")
	public Employee getEmployeeById(Integer id);

	@Update("update employee set lastName = #{lastName},email = #{email},gender=#{gender}, d_id = #{dId} where id=#{id}")
	public void updateEmployee(Employee employee);

	@Delete("delete from employee where id = #{id}")
	public void deleteEmployee(Integer id);

	@Insert("insert into employee(lastName, email, gender, d_id) values (#{lastName}, #{email}, #{gender}, #{d_id})")
	public void insertEmployee(Employee employee);

	@Select("select * from employee where lastName = #{lastName}")
	public Employee getEmployeeByLastName(String lastName);

}

package csdn.xiaozheng.com.springbootcachedemo.service;

import csdn.xiaozheng.com.springbootcachedemo.bean.Employee;
import csdn.xiaozheng.com.springbootcachedemo.mapper.EmployeeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.stereotype.Service;

@Service
public class EmployeeService {
	@Autowired
	private EmployeeMapper employeeMapper;


	public Employee getEmployee(Integer id){
		System.out.println("EmployeeService.getEmployee.id is :" + id);
		return employeeMapper.getEmployeeById(id);
	}

}

package csdn.xiaozheng.com.springbootcachedemo.controller;

import csdn.xiaozheng.com.springbootcachedemo.bean.Employee;
import csdn.xiaozheng.com.springbootcachedemo.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class EmployeeController {
	@Autowired
	private EmployeeService employeeService;

	@GetMapping("/emp/{id}")
	public Employee getEmployee(@PathVariable("id") Integer id){
		return employeeService.getEmployee(id);
	}

}

在这里插入图片描述

注意

1、启动mysql打印日志

logging.level.com.dgut.edu.cn.springbootcache.mapper=debug

2、开启驼峰命名法

mybatis.configuration.map-underscore-to-camel-case=true

在这里插入图片描述
在这里插入图片描述

代码如下(示例):

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.filterwarnings('ignore')
import  ssl
ssl._create_default_https_context = ssl._create_unverified_context

三、注解详情

在这里插入图片描述
在这里插入图片描述

体验常用注解

@Cacheable

在这里插入图片描述

  1. value和cacheName定义一样,缓存组件的名字,在CacheManager下管理多个缓存,例如员工缓存,部门缓存、用户缓存,通过cacheName区分。
  2. key:缓存数据使用的Key,可以通过它来指定,默认是使用方法的参数的值 1-方法的返回值
  3. keyGenerator: key的生成器,可以自己指定Key的生成器的组件Id
  4. cacheManager: 指定缓存管理器,或者cacheResolver指定获取解析器。
  5. condition:指定符合条件下才缓存,支持EL表达式
  6. unless:否定缓存,当unless指定的条件为true时,不会缓存,与condition相反。
  7. sync:是否使用异步模式
实验

相同方法、指定不同的cacheName,各自的缓存组件不会干预,看到想象,请求数据库两次
在这里插入图片描述
在这里插入图片描述
默认Key

该处使用的url网络请求的数据。


总结

提示:这里对文章进行总结:
例如:以上就是今天要讲的内容,本文仅仅简单介绍了pandas的使用,而pandas提供了大量能使我们快速便捷地处理数据的函数和方法。

在Spring Boot中,你可以使用`@Cacheable`注解来启用缓存功能,并且可以与Redis集成来实现缓存。 `@Cacheable`注解可以应用在方法上,用于指示Spring在调用此方法之前,首先从缓存中查找对应的数据。如果缓存中有数据,则直接返回缓存中的数据,不再执行方法体内的代码。如果缓存中没有数据,则会执行方法体内的代码,并将返回值存储到缓存中。 要使用`@Cacheable`注解,你需要在启动类上添加`@EnableCaching`注解来启用缓存功能。此外,还需要配置Redis作为缓存的存储介质。 首先,引入依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 接下来,在`application.properties`或`application.yml`中配置Redis连接信息: ```yaml spring.redis.host=your_redis_host spring.redis.port=your_redis_port ``` 然后,在需要使用缓存方法上添加`@Cacheable`注解,指定缓存的名称: ```java @Cacheable("myCache") public String getData(String key) { // 从数据库或其他数据源获取数据的逻辑 } ``` 以上示例中,方法`getData()`会先从名为`myCache`的缓存中查找数据,如果找到则直接返回缓存中的数据;如果没有找到,则执行方法体内的代码,并将返回值缓存起来。 注意:为了使`@Cacheable`注解生效,需要在启动类上添加`@EnableCaching`注解。 这样,你就可以在Spring Boot中使用Redis缓存注解来提高应用的性能了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值