SpringBoot使用缓存注解

= SpringBoot使用缓存注解

文章目录

  • = SpringBoot使用缓存注解
  • 缓存注解入门三个步骤
  • 一、入门体验缓存注解
        • 1. 创建SpringBoot项目,仅导入web和cache的依赖
        • 2. 在启动类上加上@EnableCaching注解
        • 3.在方法上使用缓存注解
      • 演示效果,多次访问该方法
  • 二、整合mysql环境搭建
        • 1.基础sql
        • 2、引入mysql依赖
        • 3、数据库连接信息
        • 4、启动mapper扫描,在注解上使用@MapperScan注解
        • 5、实体和接口定义
        • 注意
  • 三、注解详情
  • 体验常用注解
      • @Cacheable
        • 实验
  • 总结


缓存注解入门三个步骤

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

提示:下面是简单的Hello

一、入门体验缓存注解

1. 创建SpringBoot项目,仅导入web和cache的依赖

   
        
            mysql
            mysql-connector-java
            runtime
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.boot
            spring-boot-starter-cache
        
    

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);
	}
}

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

SpringBoot使用缓存注解_第1张图片

二、整合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', '[email protected]', '3', '11');
INSERT INTO `employee` VALUES ('2', '2', '2', '2', '2');

2、引入mysql依赖

 
            mysql
            mysql-connector-java
            runtime
        

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);
	}

}

SpringBoot使用缓存注解_第2张图片

注意

1、启动mysql打印日志

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

2、开启驼峰命名法

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

SpringBoot使用缓存注解_第3张图片
SpringBoot使用缓存注解_第4张图片

代码如下(示例):

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

三、注解详情

SpringBoot使用缓存注解_第5张图片
SpringBoot使用缓存注解_第6张图片

体验常用注解

@Cacheable

SpringBoot使用缓存注解_第7张图片

  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,各自的缓存组件不会干预,看到想象,请求数据库两次
SpringBoot使用缓存注解_第8张图片
SpringBoot使用缓存注解_第9张图片
默认Key

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


总结

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

你可能感兴趣的:(SpringBoot基础+应用,java)