springboot与redis集成

1.添加redis依赖

<dependency>

  <group Id>org.springframework.boot</group Id>

  <actifact Id>spring-boot-starter-redis<actifact Id>

  <version>x.x.x.RELEASE</version>

</dependency>

2.添加缓存注释

@SpringBoot Application

@EnableCaching //注解开启缓存

public class application {

public static void main(String[] args) {

  SpringApplication.run(Application.class,args);

}

}

3.业务逻辑层方法添加@Cacheable注解来支持缓存

@Cacheable(value = "DemoDaoCahe", key = "'demoDao.getAllDemoDaos'") //key需要双引号+单引号

public List<DemoDao> getAllDemoDao() {

  return this.demoDaoMapper.getAllDemoDao();

}

4.实体实现序列化

public class DemoDao implements Serializable {

  private static fianl long serialVersionUID = 1L;

  ...

}

5.指定缓存主机的地址

在application.properties中添加redis配置

spring.redis.host=192.168.1.11

spring.redis.port=6666

 

6.启动测试

localhost:8080/demoDao.html

 

注意:刷新一次,数据就不用查询数据库,直接使用缓存数据,除非数据库数据变化

 

扩展

@CacheEvit(value="DemoDaoCahe", key="'demoDao.getAllDemoDaos'")  //对于增删改,需要清除缓存数据

public void deleteDemo(Inteer id)

{

  this.demoDaoMapper.delete(id);

}

 

posted @ 2019-06-13 09:50  Perry_Lee  阅读(181)  评论(1编辑  收藏  举报