前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >spring boot使用自带缓存

spring boot使用自带缓存

作者头像
田维常
发布2019-07-16 10:59:21
6870
发布2019-07-16 10:59:21
举报

如何使用spring boot自带的缓存。按步骤来操作即

1,新建simple-cache模块,修改pom文件

代码语言:javascript
复制
<?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>
    <parent>
        <artifactId>spring_boot_in_action</artifactId>
        <groupId>com.laoxu</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <groupId>com.laoxu</groupId>
    <artifactId>simple-cache</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>simple-cache</name>
    <description>Demo project for Spring Boot</description>
     <properties>
        <java.version>1.8</java.version>
    </properties>
     <dependencies>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

2.配置application.yml文件

代码语言:javascript
复制
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    username: root
    password: root123
    url: jdbc:mysql://localhost:3306/spring_cache?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&serverTimezone=GMT&useSSL=false
 
mybatis:
  configuration:
    map-underscore-to-camel-case: true
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
 
debug: true

3.创建数据库spring_cache,并执行sql

代码语言:javascript
复制
DROP TABLE IF EXISTS `department`;
CREATE TABLE `department` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `department_name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
 
-- ----------------------------
-- Table structure for employee
-- ----------------------------
DROP TABLE IF EXISTS `employee`;
CREATE TABLE `employee` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `last_name` 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 DEFAULT CHARSET=utf8;

4,创建实体

代码语言:javascript
复制
package com.laoxu.springboot.bean;
public class Department {
  private Integer id;
  private String departmentName;
  //省略set get
}
代码语言:javascript
复制
package com.laoxu.springboot.bean;
public class Employee {
  private Integer id;
  private String lastName;
  private String email;
  private Integer gender; //性别 1男  0女
  //省略 set get
}

5,创建mapper

代码语言:javascript
复制
package com.laoxu.springboot.mapper;
 
import com.laoxu.springboot.bean.Employee;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;
 
@Repository
@Mapper
public interface EmployeeMapper {
    @Select("SELECT * FROM employee WHERE id=#{id}")
    Employee getEmpById(Integer id);
 
    @Update("update employee set last_name=#{lastName}, email=#{email},gender=#{gender},d_id=#{dId} where id=#{id}")
    void updateEmp(Employee employee);
 
    @Delete("delete from employee where id=#{id}")
    void deleteEmpById(Integer id);
 
    @Insert("insert into employee(last_name,email,gender,d_id)  values(#{lastName}, #{email}, #{gender}, #{dId})")
    void insertEmp(Employee employee);
 
    @Select("SELECT * FROM employee WHERE last_name=#{lastName}")
    Employee getEmpByLastName(String lastName);
 
}

6,创建service

代码语言:javascript
复制
package com.laoxu.springboot.service;
 
import com.laoxu.springboot.bean.Employee;
import com.laoxu.springboot.mapper.EmployeeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.*;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
 
@CacheConfig(cacheNames = "emp") //在此处加上就不用在每个方法上加了
@Service
public class EmployeeService {
    @Autowired
    EmployeeMapper employeeMapper;
 
    @Cacheable(/*cacheNames = "emp"*//*,keyGenerator = "myKeyGenerator",key = "#id", condition = "#a0>1" , unless = "#a0==1"*/)
    public Employee getEmp(Integer id){
        System.out.println("查询"+id+"号员工");
        return employeeMapper.getEmpById(id);
    }
 
    /**
     * 在方法后調用, 同步更新缓存
     * @param employee
     * @return
     */
    @CachePut(/*cacheNames = "emp",*/ key="#result.id")
    public Employee updateEmp(Employee employee){
        System.out.println("更新员工:"+employee);
        employeeMapper.updateEmp(employee);
 
        return employee;
    }
 
    /**
     * allEntries = true  删除所有emp缓存
     * beforeInvocation = true 无论方法是否成功 都会删掉缓存
     * @param id
     */
    @CacheEvict(/*value = "emp",*/ key = "#id")
    public void deleteEmp(Integer id){
        System.out.println("删除员工:"+id);
    }
 
    @Caching(
            cacheable = {
                    @Cacheable(/*value = "emp",*/ key = "#lastName")
            },
            put = {
                    @CachePut(/*value = "emp",*/ key = "#result.id"),
                    @CachePut(/*value = "email",*/ key = "#result.email")
            }
 
    )
    public Employee getEmpByLastName(String lastName){
        return employeeMapper.getEmpByLastName(lastName);
    }
}

7,创建controller

代码语言:javascript
复制
package com.laoxu.springboot.controller;
 
import com.laoxu.springboot.bean.Employee;
import com.laoxu.springboot.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
    EmployeeService employeeService;
 
    @GetMapping("/emp/{id}")
    public Employee getEmp(@PathVariable("id") Integer id){
        return employeeService.getEmp(id);
    }
 
    @GetMapping("/emp")
    public Employee update(Employee employee)
    {
        employeeService.updateEmp(employee);
        return employee;
    }
 
    @GetMapping("/delEmp/{id}")
    public String delete(@PathVariable("id") Integer id){
        employeeService.deleteEmp(id);
 
        return "success";
    }
 
    @GetMapping("/emp/lastName/{lastName}")
    public Employee getEmpByLastName(@PathVariable("lastName") String lastName){
        return employeeService.getEmpByLastName(lastName);
    }
}

8,创建启动类

代码语言:javascript
复制

package com.laoxu.springboot;
 
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
 
@MapperScan("com.laoxu.springboot.mapper")
@EnableCaching//启用缓存
@SpringBootApplication
public class SimpleCacheApplication {
    public static void main(String[] args) {
        SpringApplication.run(SimpleCacheApplication.class, args);
    }
}

9.创建自定义key生成器

代码语言:javascript
复制
package com.laoxu.springboot.config;
 
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
import java.lang.reflect.Method;
import java.util.Arrays;
 
@Configuration
public class MyCacheConfig {
    @Bean("myKeyGenerator")
    public KeyGenerator keyGenerator(){
        return new KeyGenerator() {
            @Override
            public Object generate(Object o, Method method, Object... objects) {
                String key=method.getName()+"["+ Arrays.asList(objects).toString()+"]";
                return key;
            }
        };
    }
}

10.反复执行以下测试路径,观察console的日志输出

查看resources文件夹下的readme.txt文件。

代码语言:javascript
复制
#查询
http://localhost:8080/emp/1
http://localhost:8080/emp/2
#更新
http://localhost:8080/emp?id=1&lastName=%E5%BC%A0%E4%B8%892&email=zhangsan1@1.com&gender=1&dId=1
#删除
http://localhost:8080/delEmp/1
#测试更新
http://localhost:8080/emp?id=1&lastName=%E5%BC%A0%E4%B8%891&email=zhangsan1@1.com&gender=1&dId=1
代码语言:javascript
复制
原文:
https://blog.csdn.net/IndexMan/article/details/86681275
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-06-28,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Java后端技术栈 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档