一。前言

作用:系统需要通过 Cache 来缓存不经常改变的数据以提高系统性能和增加系统吞吐量,避免直接访问数据库等低速的存储系统

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

使用场景:Spring Boot 自带的 Simple 缓存,需要注意的是,Simple 只适合单体应用或者开发环境使用,再或者是一个小微单系统,通常应用为分布式应用时,则需要集成 EhCache、Redis 等分布式缓存管理器。

使用举例:如用户权限、字典数据、状态数据.配置信息等。

存放:避免直接访问数据库等低速的存储系统。缓存的数据通常存放在访问速度更快的内存中或者是低延迟存取的存储器、服务器上。

简单配置增删查改:

@CachePut(key = "#user.id")   @Cacheable(key = "#id")  @CacheEvict(key = "#id") 即增改查删 均是把id作为key值,返回的结果作为value  这样组成Map形式,注意:缓存其实存放的是以注解里面的key为key 方法的返回值作为key的value,不是注解里面的value。
@CacheEvict(key = "#id",allEntries=true)//清理键值对
缺点: 1.当你需要清除缓存的时候,你无法指定多个缓存块。 2.复杂多样的增删查改操作无法使用(清除缓存的时候,你无法指定多个缓存块)

二。举例

1.添加依赖

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

2.配置缓存管理器,在 application.properties 中配置目标缓存管理器:

spring.cache.type=SIMPLE

3.启动类添加缓存注解

@SpringBootApplication
@EnableCaching  //开启缓存
@MapperScan("com.test.springboot.example.mapper")
public class SpringbootApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringbootApplication.class, args);
        }
    }
}

4.service层

package com.test.springboot.example.service;

import com.test.springboot.example.ennity.User;
import com.baomidou.mybatisplus.extension.service.IService;

/**
 * <p>
 *  服务类
 * </p>
 *
 * @author 一念花开
 * @since 2019-05-08
 */
public interface UserService extends IService<User> {

    /**
     * 新增用户
     */
    public User insertUser(User user);

    /**
     * 通过id查找单个用户
     */
    public User getUserById(Integer id);

    /**
     * 通过id修改单个用户
     */
    public User updateUserById(User user);

    /**
     * 通过id删除单个用户
     */
    public Integer deleteUserById(Integer id);
}

5.实现层  核心添加cache

package com.test.springboot.example.service.impl;

import com.test.springboot.example.ennity.User;
import com.test.springboot.example.mapper.UserMapper;
import com.test.springboot.example.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

/**
 * <p>
 *  @CachePut  @Cacheable  @CacheEvict(key = "#id") 即增改查删 均是把id作为key值,返回的结果作为value  这样组成Map形式
 *  @CacheEvict(key = "#id",allEntries=true)//清理键值对
 * </p>
 *
 * @author 一念花开
 * @since 2019-05-08
 */
@Service
@CacheConfig(cacheNames = "user")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {


    @Resource
    UserMapper UserMapper;


    /**
     * 新增用户
     */
    @CachePut(key = "#user.id")
    public User insertUser(User user) {
        UserMapper.insert(user);
        return user;
    }

    /**
     * 通过id查找单个用户
     */
    @Cacheable(key = "#id")//存在对应缓存则读取操作否则调用方法
    public User getUserById(Integer id) { //id不同 查询几次 缓存几次  ;id相同,仅仅缓存一次
        User user = this.UserMapper.selectById(id);
        return user;
    }

    /**
     * 通过id修改单个用户
     */
    @CachePut(key = "#user.id")//返回的结果更新缓存
    public User updateUserById(User user) {
        this.UserMapper.updateById(user);
        User user1 = UserMapper.selectById(user.getId());
        return user1;
    }

    /**
     * 通过id删除单个用户
     */
    @CacheEvict(key = "#id",allEntries=true)//清理这个key值
   //@CacheEvict(key = "#id")//返回的结果更新缓存,把value值改为null
    public Integer deleteUserById(Integer id) {
        this.UserMapper.deleteById(id);
        return null;
    }


//    cacheNames/value:指定缓存组件的名字,将方法的返回结果放在哪个缓存中,是数组的方式,可以指定多个缓存; 	例如:@Cacheable(cacheNames = {}"emp","dept"},key = "#root.args[0]")
//    key:可以用它来指定缓存数据使用的key,默认是使用方法参数的值;(也可以指定自己的生成策略)
//    keyGenerator:key的生成器;可以自己指定key的生成器的组件id;key/keyGenerator:二选一使用;
//    cacheManager:指定缓存管理器;或者cacheResolver指定获取解析器;
//    condition:指定符合条件的情况下才缓存;例如:@Cacheable(cacheNames = {}"emp","dept"},key = "#root.args[0]",condition="#root.args[0]>0")
//    unless:否定缓存;当unless指定的条件为true,方法的返回值就不会被缓存;可以获取到结果进行判断;
//    sync:是否使用异步模式

}

6.controller层测试:

package com.test.springboot.example.controller;
import com.test.springboot.bean.ResultModel;
import com.test.springboot.example.ennity.User;
import com.test.springboot.example.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;

/**
 * @Company:wftdlx
 * @Author: wjf
 * @Description:
 * @Date: Created in 11:28 2019/5/13
 */
@Controller
@RequestMapping("/cache")
public class CacheController {
    @Resource
    UserService userService;

    //查询
    @GetMapping("/user/{id}") //映射地址
    @ResponseBody //异步json数据
    public ResultModel select(@PathVariable(name = "id") Integer id) {//@PathVariable 获取url中的变量
        User user = userService.getUserById(id);
        return new ResultModel(ResultModel.SUCCESS, "查询成功", user);
    }


    //增加
    @PostMapping("/user")//仅仅可以使用post方法
    @ResponseBody //返回 异步json数据
    public ResultModel demo1(@RequestBody User user) {//接收json请求数据;必须post请求;仅仅一个;int数据可以使用引号或者不用;对象属性不用全写;@RequestParam()可以同时使用而且可以多个
        //正确结果
        User User = userService.insertUser(user);

        return new ResultModel(ResultModel.SUCCESS, "增加成功", user);

    }

    //删除
    @RequestMapping(value = "/user/{id}", method = RequestMethod.DELETE, produces = "application/json;charset=UTF-8")
    @ResponseBody //返回 异步json数据
    public ResultModel delete(@PathVariable(name = "id") Integer id) {//接收json请求数据;必须post请求;仅仅一个;int数据可以使用引号或者不用;对象属性不用全写;@RequestParam()可以同时使用而且可以多个
        userService.deleteUserById(Integer.valueOf(id));
        //排错
        return new ResultModel(ResultModel.SUCCESS, "删除成功");
    }
    
    //修改 全更新  无值赋空
    @RequestMapping(value = "/user", method = RequestMethod.PUT, produces = "application/json;charset=UTF-8")
    @ResponseBody //返回 异步json数据
    public ResultModel put(@RequestBody User user) {
        System.out.println(user.toString());
        User user2 = userService.updateUserById(user);

        return new ResultModel(ResultModel.SUCCESS, "修改成功", user2);

    }


}

  

 

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄