zoukankan      html  css  js  c++  java
  • Spring_对缓存的支持


     使用SpringBoot开启缓存分为两步:

    • 开启基于注解的缓存
    • 标注缓存注解即可

     如上就是一个简单的缓存示例


     默认使用的是ConcurrentHashMap组件用来缓存的

    package ustc.anmin.springboot.service;
    
    import org.springframework.beans.factory.annotation.Autowired;
    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 ustc.anmin.springboot.bean.User;
    import ustc.anmin.springboot.mapper.UserMapper;
    
    //抽取缓存的公共配置
    @CacheConfig(cacheNames = "user")
    @Service
    public class UserService {
        @Autowired
        UserMapper userMapper;
    
        /**
         * cacheNames:缓存的名字
         * key:指定key的名字  可以使用spel表达式
         * condition:指定条件下符合  才进行缓存  #args[0]>1  第一个参数的值大于一才进行缓存
         */
    
        @Cacheable(cacheNames = "user")
        public User getUserById(int id) {
            System.out.println("查询了" + id + "号员工");
            return userMapper.selectUserById(id);
        }
    
        /**
         * 既调用方法  又更新缓存数据
         * 注意缓存的key
         * 默认的key是传入的对象  value是返回的对象
         */
        @CachePut(cacheNames = "user", key = "#user.id")
        public User updateUser(User user) {
            System.out.println("更新了" + user.getId() + "号员工");
            userMapper.updateUser(user);
            return user;
        }
    
        /**
         * 清除缓存
         * beforeInvocation=false  是否在方法执行之前清空缓存 方法出错就不清除
         * allEntries 是否清除所有的缓存
         * */
        @CacheEvict(cacheNames = "user",key="#id"/*,allEntries = true*/)
        public String deleteUser(int id){
            System.out.println("删除"+id+"号员工");
            return "delete success!";
        }
    }
  • 相关阅读:
    支付宝及时到帐接口使用详解
    简便无刷新文件上传系统
    EyesBaby功能实现之窗口拖拽与缩放功能
    Jquery各行换色 click变色
    纯CSS圆角框3-圆角化图片
    WINFORM自定义皮肤制作(上)
    EyesBaby1.0使用帮助文档
    C#实现小写金额转大写金额
    在winform中运用FusionCharts图表(一)
    第一章、基本的圆角框
  • 原文地址:https://www.cnblogs.com/ustc-anmin/p/11059460.html
Copyright © 2011-2022 走看看