springboot 缓存 20

2020-04-08  本文已影响0人  张力的程序园

本文将介绍springboot缓存。

1、环境约束

2、前提约束

3、操作步骤

@EnableCaching

在主启动类同级目录下创建一个CacheController.java

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RestController
public class UserController {

    @Resource
    UserDao userDao;

    @GetMapping("/query")
    @Cacheable(value = "user")
    //缓存所有数据,较少使用
    public List<User> query() {
        List<User> list = userDao.findAll();
        return list;

    }

    @GetMapping("/get")
    @Cacheable(value = "user", key = "#id")
    //方法中使用到了@Cacheable注解,这个注解在执行前先查看缓存中是不是已经存在了,
    //如果存在,直接返回。如果不存在,将方法的返回值放入缓存。
    public User get(int id) {
        return userDao.findById(id).get();
    }

    @GetMapping("/insert")
    @CachePut(value = "user", key = "#user.id")
    //方法中使用到了@CachePut注解,这个注解直接将返回值放入缓存中,通常用于保存和修改方法中
    public User insert(User user) {
        userDao.save(user);
        System.out.println("123");
        return user;
    }

    @GetMapping("/delete")
    @CacheEvict(value = "user", key = "#id")
    //方法中使用到了@CacheEvict注解,将特定缓存移除
    public String deleteHouse(Integer id) {
        return "success";
    }

    @GetMapping("/deletecache")
    @CacheEvict(value = "user", allEntries=true )
    //方法中使用到了@CacheEvict注解,这个注解是清除所有缓存
    public void deletecache(Integer id) {

    }
}
spring.jpa.show-sql=true
上一篇 下一篇

猜你喜欢

热点阅读