spring boot 缓存数据

2019-05-26  本文已影响0人  wanggs

maven工程配置引入依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

添加redis 配置文件

server:
  port: 80
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/babytun?useUnicode=true&characterEncoding=utf-8&useSSL=false
    username: root
    password: root
  mvc:
    favicon:
      enabled: false
  redis:
    database: 3
    host: 127.0.0.1
    port: 6379
    jedis:
      pool:
        max-active: 100
        max-idle: 100
        min-idle: 10
        max-wait: 1000ms
mybatis:
  mapper-locations: classpath:/mapper/*.xml
  configuration:
    map-underscore-to-camel-case: true

添加启动注解

@EnableCaching //开启声明式缓存,利用注解来控制缓存的读写

@SpringBootApplication
// 扫描mybatis实现的接口
@MapperScan("com.wanggs.babytun")
@EnableCaching //开启声明式缓存,利用注解来控制缓存的读写
public class BabytunApplication {

    public static void main(String[] args) {
        SpringApplication.run(BabytunApplication.class, args);
    }

}

使用

 //@Cacheable是声明式缓存的核心注解
    //第一次访问的时候将方法的返回结果放入缓存
    //第二次访问时不再执行方法内部的代码,而是从缓存中直接提取数据。
    @Cacheable(value="goods" , key = "#goodsId") //key:  goods::1  goods::2
    @Override
    public Goods findById(Long goodsId) {
        return goodsDao.findById(goodsId);
    }
    @Cacheable(value="covers" , key = "#goodsId")
    @Override
    public List<GoodsConver> findCovers(Long goodsId) {
        return goodsConverDao.findByGoodsId(goodsId);
    }
上一篇下一篇

猜你喜欢

热点阅读