springboot整合redis緩存

使用springBoot添加redis緩存須要在POM文件裏引入html

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

<dependency>
     <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-redis</artifactId>
    <version>1.4.3.RELEASE</version>
</dependency>

咱們添加緩存的支持須要兩個依賴,一個是SpringBoot內部的緩存配置、另外則是咱們的redis緩存。node

配置Redis數據庫
依賴添加完成後,須要配置咱們本地的redis數據庫鏈接到項目中,咱們打開application-local.properties配置文件添加以下圖8所示的配置內容:redis

#redis
spring.redis.cluster.nodes=172.0.0.1:6379
spring.redis.pool.max-active=20
spring.redis.pool.max-idle=10
spring.redis.pool.min-idle=5
spring.redis.pool.max-wait=10
spring.redis.timeout=5000

一、簡易方式spring

@Configuration
    @EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
//生成key 
@Override
@Bean
public KeyGenerator keyGenerator() {
    return new KeyGenerator() {
        @Override
        public Object generate(Object target, Method method, Object... objects) {
            return UserConstant.REDIS_KEY; //常量key
        }
    };
}

} 數據庫

查看一下 Spring緩存註解@Cacheable、@CacheEvict、@CachePut使用參考
http://www.javashuo.com/article/p-yfruwgfl-dm.html
// serviceImpl 方法 @Cacheable("infos") 緩存

@Override
@Cacheable("infos")  
public List<User> queryUser() {
    return this.UserMapper.queryUser();
}

如上只須要加上一個註解就能夠 在調用查詢的時候先去緩存裏面找,沒有就執行方法 而後再存到緩存裏面app

在執行增、刪、改的時候須要刪除緩存以下:ide

@Override
@CacheEvict("infos")  
public void editUserStatus(Map<String, Object> info) {
    UserMapper.editStatus(info);
}

在對應的方法上加入註解 這樣就會刪除緩存spring-boot

最後去測試一下就能夠。測試

相關文章
相關標籤/搜索