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里面也没有生成对应的缓存

     总结

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

  • 相关阅读:
    SpringMVC返回JSON数据时日期格式化问题
    elementUI-tree组件 懒加载
    vue elementUi tree 懒加载使用详情
    Mybatis ResultMap Collection 复合主键
    ElasticSearch-IK分词
    Spring中的InitializingBean接口的使用
    ContextLoadListener & DispatcherServlet 加载顺序以及加载过程
    Spring中查看加载配置文件中 加载类的个数及详情
    DispatcherServlet 被加载顺序
    JetBrainsIDEA-structure结构继承的图标说明
  • 原文地址:https://www.cnblogs.com/luzhanshi/p/13337744.html
Copyright © 2011-2022 走看看