zoukankan      html  css  js  c++  java
  • SpringBoot--使用Spring Cache整合redis

    一、简介

      Spring Cache是Spring对缓存的封装,适用于 EHCache、Redis、Guava等缓存技术。

    二、作用

      主要是可以使用注解的方式来处理缓存,例如,我们使用redis缓存时,查询数据,如果查询到,会判断查到的结果是否为空,如果不为空,则会将结果存入redis缓存,此处需要一层判断;而如果使用Spring Cache的注解进行处理,则不需要判断就可以达到目的。

      示例:

      使用前:

    public List<User> selectByUsernameRedis(String username) {
            String key = "user:username:"+username;
            List<User> userList = userMapper.selectByuserName(username);
            if(!userList.isEmpty()){
                stringRedisTemplate.opsForValue().set(key, JSON.toJSONString(userList));
            }
            return userList;
        }

      使用后:

    @Cacheable(value = "user", key = "#username")
        public List<User> selectByUsernameRedis1(String username) {
            return userMapper.selectByuserName(username);
        }

    三、配置及使用

      导入包和配置文件与单独集成redis时一致,此处不做描述。

      1、主函数增加@EnableCaching配置,如果主函数不添加@EnableCaching配置,则后面的配置不生效。

      

    package com.example.demo;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cache.annotation.EnableCaching;
    
    @SpringBootApplication
    @EnableCaching
    public class DemoApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(DemoApplication.class, args);
        }
    
    }

      2、代码实现

      主要有@Cacheable、@CachePut、@CacheEvict三个注解,对应关系如下:

      @Cacheable  查询,先查询缓存,如果存在直接返回;如果不存在,查询数据库,结果不为空,直接存入缓存。

      @CachePut 存入缓存,适用于新增或更新方法。

      @CacheEvict  删除缓存,适用于删除方法。

        @CachePut(value = "user")
        @Override
        public String saveOrUpdate(User user) {
            userMapper.insert(user);
            return JSON.toJSONString(user);
        }
    
        @Cacheable(value = "user", key = "#id")
        @Override
        public String get(Long id) {
            return JSON.toJSONString(userMapper.selectByUserId(id));
        }
    
        @CacheEvict(value = "user", key = "#id")
        @Override
        public void delete(Long id) {
            userMapper.deleteByUserId(id);
        }
  • 相关阅读:
    设计模式---策略模式
    maven+eclipse创建web项目
    【Mybatis】多对多实例
    【Mybatis】一对多实例
    【Mybatis】一对一实例
    S5PV210的开发与学习:2.6 UBOOT学习笔记(uboot源码分析3-uboot如何启动内核)
    S5PV210的开发与学习:2.5 UBOOT学习笔记(uboot源码分析2-启动第二阶段)
    S5PV210的开发与学习:2.4 UBOOT学习笔记(uboot源码分析1-启动第一阶段)
    uboot 移植文件差异比较报告
    S5PV210的开发与学习:2.3 UBOOT学习笔记(uboot配置和编译过程详解)
  • 原文地址:https://www.cnblogs.com/liconglong/p/11698705.html
Copyright © 2011-2022 走看看