zoukankan      html  css  js  c++  java
  • 十二,springBoot整合redis

    1.依赖

    <!--        redis依赖-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-redis</artifactId>
                <version>1.3.8.RELEASE</version>
            </dependency>

    2.开启springBoot对缓存的支持

    在启动类上添加@EnableCaching注解:

    @SpringBootApplication
    @EnableCaching//开启springBoot对缓存的支持
    public class CleanSpringBootApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(CleanSpringBootApplication.class, args);
        }
    }

    3.业务层实现类使用缓存

    import com.example.dao.IUserDao;
    import com.example.dao.IUserMapper;
    import com.example.pojo.User;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.cache.annotation.Cacheable;
    import org.springframework.stereotype.Service;
    import java.util.List;
    /**
     * 用户业务层实现类
     */
    @Service("userService")
    public class UserServiceImpl  implements UserService {
        @Autowired
        private IUserMapper iUserMapper;
      
      @Override
        @Cacheable(value = "findAllCache",key = "'userFindAll'")//表示当前方法使用缓存,并存入redis数据库中
        /**
         * @Cacheable
         *      value属性:存入redis数据库的key
         *      key属性:用于指定方法返回值的key,该属性是spring用的,支持el表达式,
         *              不写也有默认值(空字符串),写的时候要先写使用单引号包裹内容;
         *              (当该方法有许多重载,方法返回值又不大一样时才使用)
         *
         */
        public List<User> findAll() {
        
    System.out.println("执行去数据库查询");  
    return iUserMapper.findAll();
        }
    }

    4.测试

    浏览器访问:

     此时我们看控制台打印:

     我们再次刷新浏览器访问然后看控制台:

     我们发现"去数据库查询"只打印了一次,也就是说,第二次再查询出来的数据并没有去查询数据库

    5.查看redis里面也没有生成对应的缓存

     总结

    上面我们通过简单地配置就实现了哪个方法想使用缓存就可以使用缓存的功能

  • 相关阅读:
    [树形dp] Luogu P4516 潜入行动
    [kruskal][Trie] Codeforces 888G Xor-MST
    [线性基] Luogu P4151 最大XOR和路径
    [线段树] Luogu P4560 砖墙
    [递归][重心] Luogu P4886 快递员
    [Trie][贪心][堆] LibreOJ #3048 异或粽子
    [长链剖分][优先队列] LibreOJ #3052 春节十二响
    [支配树] Bzoj P2815 灾难
    [长链剖分][线段树] Bzoj P1758 重建计划
    [dsu on tree] Codeforces 600E Lomsat gelral
  • 原文地址:https://www.cnblogs.com/luzhanshi/p/13337744.html
Copyright © 2011-2022 走看看